hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
b85c6f79ba47071da63889439c0ed916c6c90d2b
9,297
cpp
C++
deps/src/boost_1_65_1/libs/algorithm/test/clamp_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
deps/src/boost_1_65_1/libs/algorithm/test/clamp_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
deps/src/boost_1_65_1/libs/algorithm/test/clamp_test.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2020-10-21T17:46:28.000Z
2020-10-21T17:46:28.000Z
// (C) Copyright Jesse Williamson 2009 // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <vector> #include <boost/config.hpp> #include <boost/algorithm/clamp.hpp> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> namespace ba = boost::algorithm; bool intGreater ( int lhs, int rhs ) { return lhs > rhs; } bool doubleGreater ( double lhs, double rhs ) { return lhs > rhs; } class custom { public: custom ( int x ) : v(x) {} custom ( const custom &rhs ) : v(rhs.v) {} ~custom () {} custom & operator = ( const custom &rhs ) { v = rhs.v; return *this; } bool operator < ( const custom &rhs ) const { return v < rhs.v; } bool operator == ( const custom &rhs ) const { return v == rhs.v; } // need this for the test std::ostream & print ( std::ostream &os ) const { return os << v; } int v; }; std::ostream & operator << ( std::ostream & os, const custom &x ) { return x.print ( os ); } bool customLess ( const custom &lhs, const custom &rhs ) { return lhs.v < rhs.v; } void test_ints() { // Inside the range, equal to the endpoints, and outside the endpoints. BOOST_CHECK_EQUAL ( 3, ba::clamp ( 3, 1, 10 )); BOOST_CHECK_EQUAL ( 1, ba::clamp ( 1, 1, 10 )); BOOST_CHECK_EQUAL ( 1, ba::clamp ( 0, 1, 10 )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 10, 1, 10 )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 11, 1, 10 )); BOOST_CHECK_EQUAL ( 3, ba::clamp ( 3, 10, 1, intGreater )); BOOST_CHECK_EQUAL ( 1, ba::clamp ( 1, 10, 1, intGreater )); BOOST_CHECK_EQUAL ( 1, ba::clamp ( 0, 10, 1, intGreater )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 10, 10, 1, intGreater )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 11, 10, 1, intGreater )); // Negative numbers BOOST_CHECK_EQUAL ( -3, ba::clamp ( -3, -10, -1 )); BOOST_CHECK_EQUAL ( -1, ba::clamp ( -1, -10, -1 )); BOOST_CHECK_EQUAL ( -1, ba::clamp ( 0, -10, -1 )); BOOST_CHECK_EQUAL ( -10, ba::clamp ( -10, -10, -1 )); BOOST_CHECK_EQUAL ( -10, ba::clamp ( -11, -10, -1 )); // Mixed positive and negative numbers BOOST_CHECK_EQUAL ( 5, ba::clamp ( 5, -10, 10 )); BOOST_CHECK_EQUAL ( -10, ba::clamp ( -10, -10, 10 )); BOOST_CHECK_EQUAL ( -10, ba::clamp ( -15, -10, 10 )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 10, -10, 10 )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 15, -10, 10 )); // Unsigned BOOST_CHECK_EQUAL ( 5U, ba::clamp ( 5U, 1U, 10U )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 1U, 1U, 10U )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 0U, 1U, 10U )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 10U, 1U, 10U )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 15U, 1U, 10U )); // Mixed (1) BOOST_CHECK_EQUAL ( 5U, ba::clamp ( 5U, 1, 10 )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 1U, 1, 10 )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 0U, 1, 10 )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 10U, 1, 10 )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 15U, 1, 10 )); // Mixed (3) BOOST_CHECK_EQUAL ( 5U, ba::clamp ( 5U, 1, 10. )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 1U, 1, 10. )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 0U, 1, 10. )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 10U, 1, 10. )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 15U, 1, 10. )); short foo = 50; BOOST_CHECK_EQUAL ( 56, ba::clamp ( foo, 56.9, 129 )); BOOST_CHECK_EQUAL ( 24910, ba::clamp ( foo, 12345678, 123456999 )); } void test_floats() { // Inside the range, equal to the endpoints, and outside the endpoints. BOOST_CHECK_EQUAL ( 3.0, ba::clamp ( 3.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 1.0, ba::clamp ( 1.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 1.0, ba::clamp ( 0.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 10.0, ba::clamp ( 10.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 10.0, ba::clamp ( 11.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 3.0, ba::clamp ( 3.0, 10.0, 1.0, doubleGreater )); BOOST_CHECK_EQUAL ( 1.0, ba::clamp ( 1.0, 10.0, 1.0, doubleGreater )); BOOST_CHECK_EQUAL ( 1.0, ba::clamp ( 0.0, 10.0, 1.0, doubleGreater )); BOOST_CHECK_EQUAL ( 10.0, ba::clamp ( 10.0, 10.0, 1.0, doubleGreater )); BOOST_CHECK_EQUAL ( 10.0, ba::clamp ( 11.0, 10.0, 1.0, doubleGreater )); // Negative numbers BOOST_CHECK_EQUAL ( -3.f, ba::clamp ( -3.f, -10.f, -1.f )); BOOST_CHECK_EQUAL ( -1.f, ba::clamp ( -1.f, -10.f, -1.f )); BOOST_CHECK_EQUAL ( -1.f, ba::clamp ( 0.f, -10.f, -1.f )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -10.f, -10.f, -1.f )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -11.f, -10.f, -1.f )); // Mixed positive and negative numbers BOOST_CHECK_EQUAL ( 5.f, ba::clamp ( 5.f, -10.f, 10.f )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -10.f, -10.f, 10.f )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -15.f, -10.f, 10.f )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 10.f, -10.f, 10.f )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 15.f, -10.f, 10.f )); // Mixed (1) BOOST_CHECK_EQUAL ( 5.f, ba::clamp ( 5.f, -10., 10. )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -10.f, -10., 10. )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -15.f, -10., 10. )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 10.f, -10., 10. )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 15.f, -10., 10. )); // Mixed (2) BOOST_CHECK_EQUAL ( 5.f, ba::clamp ( 5.f, -10, 10 )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -10.f, -10, 10 )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -15.f, -10, 10 )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 10.f, -10, 10 )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 15.f, -10, 10 )); } void test_custom() { // Inside the range, equal to the endpoints, and outside the endpoints. BOOST_CHECK_EQUAL ( custom( 3), ba::clamp ( custom( 3), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom( 1), ba::clamp ( custom( 1), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom( 1), ba::clamp ( custom( 0), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom(10), ba::clamp ( custom(10), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom(10), ba::clamp ( custom(11), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom( 3), ba::clamp ( custom( 3), custom(1), custom(10), customLess )); BOOST_CHECK_EQUAL ( custom( 1), ba::clamp ( custom( 1), custom(1), custom(10), customLess )); BOOST_CHECK_EQUAL ( custom( 1), ba::clamp ( custom( 0), custom(1), custom(10), customLess )); BOOST_CHECK_EQUAL ( custom(10), ba::clamp ( custom(10), custom(1), custom(10), customLess )); BOOST_CHECK_EQUAL ( custom(10), ba::clamp ( custom(11), custom(1), custom(10), customLess )); // Fail!! // BOOST_CHECK_EQUAL ( custom(1), ba::clamp ( custom(11), custom(1), custom(10))); } #define elementsof(v) (sizeof (v) / sizeof (v[0])) #define a_begin(v) (&v[0]) #define a_end(v) (v + elementsof (v)) #define a_range(v) v #define b_e(v) a_begin(v),a_end(v) void test_int_range () { int inputs [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 19, 99, 999, -1, -3, -99, 234234 }; int outputs [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, -1, -1, -1, 10 }; std::vector<int> results; std::vector<int> in_v; std::copy ( a_begin(inputs), a_end(inputs), std::back_inserter ( in_v )); ba::clamp_range ( a_begin(inputs), a_end(inputs), std::back_inserter ( results ), -1, 10 ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( in_v.begin (), in_v.end (), std::back_inserter ( results ), -1, 10 ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( a_begin(inputs), a_end(inputs), std::back_inserter ( results ), 10, -1, intGreater ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( in_v.begin (), in_v.end (), std::back_inserter ( results ), 10, -1, intGreater ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( a_range(inputs), std::back_inserter ( results ), -1, 10 ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( in_v, std::back_inserter ( results ), -1, 10 ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( a_range(inputs), std::back_inserter ( results ), 10, -1, intGreater ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( in_v, std::back_inserter ( results ), 10, -1, intGreater ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); int junk[elementsof(inputs)]; ba::clamp_range ( inputs, junk, 10, -1, intGreater ); BOOST_CHECK ( std::equal ( b_e(junk), outputs )); } BOOST_AUTO_TEST_CASE( test_main ) { test_ints (); test_floats (); test_custom (); test_int_range (); // test_float_range (); // test_custom_range (); }
42.452055
107
0.591481
[ "vector" ]
b85e1c4fdaf2518d2f583f0846a31802f1ba5b23
16,070
hxx
C++
Modules/Filtering/ImageLabel/include/itkBinaryContourImageFilter.hxx
Kronephon/itktest
a34e46226638c08bba315a257e33550a68203d97
[ "Apache-2.0" ]
null
null
null
Modules/Filtering/ImageLabel/include/itkBinaryContourImageFilter.hxx
Kronephon/itktest
a34e46226638c08bba315a257e33550a68203d97
[ "Apache-2.0" ]
null
null
null
Modules/Filtering/ImageLabel/include/itkBinaryContourImageFilter.hxx
Kronephon/itktest
a34e46226638c08bba315a257e33550a68203d97
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkBinaryContourImageFilter_hxx #define itkBinaryContourImageFilter_hxx #include "itkBinaryContourImageFilter.h" // don't think we need the indexed version as we only compute the // index at the start of each run, but there isn't a choice #include "itkImageLinearIteratorWithIndex.h" #include "itkConstShapedNeighborhoodIterator.h" #include "itkImageRegionIterator.h" #include "itkMaskImageFilter.h" #include "itkConnectedComponentAlgorithm.h" #include "itkMath.h" namespace itk { template< typename TInputImage, typename TOutputImage > BinaryContourImageFilter< TInputImage, TOutputImage > ::BinaryContourImageFilter() { m_FullyConnected = false; m_ForegroundValue = NumericTraits< InputImagePixelType >::max(); m_BackgroundValue = NumericTraits< OutputImagePixelType >::ZeroValue(); m_NumberOfThreads = 0; this->SetInPlace(false); this->DynamicMultiThreadingOn(); } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // We need all the input. InputImagePointer input = const_cast< InputImageType * >( this->GetInput() ); if ( !input ) { return; } input->SetRequestedRegionToLargestPossibleRegion(); } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::EnlargeOutputRequestedRegion(DataObject *) { OutputImagePointer output = this->GetOutput(); output->SetRequestedRegionToLargestPossibleRegion(); } template<typename TInputImage, typename TOutputImage> void BinaryContourImageFilter<TInputImage, TOutputImage> ::GenerateData() { this->UpdateProgress(0.0f); this->AllocateOutputs(); this->BeforeThreadedGenerateData(); this->UpdateProgress(0.05f); RegionType reqRegion = this->GetOutput()->GetRequestedRegion(); this->GetMultiThreader()->SetNumberOfThreads(this->GetNumberOfThreads()); //parallelize in a way which does not split the region along X axis //to accomplish this, we parallelize a region with lower dimension //which we extend with full scanlines along X this->GetMultiThreader()->ParallelizeImageRegion( ImageDimension - 1, &reqRegion.GetIndex()[1], &reqRegion.GetSize()[1], [&](const IndexValueType index[], const SizeValueType size[]) { RegionType r; r.SetIndex(0, reqRegion.GetIndex(0)); r.SetSize(0, reqRegion.GetSize(0)); for (unsigned d = 1; d < ImageDimension; d++) { r.SetIndex(d, index[d - 1]); r.SetSize(d, size[d - 1]); } this->DynamicThreadedGenerateData(r); }, nullptr); this->UpdateProgress(0.5f); //avoid splitting the region along X this->GetMultiThreader()->ParallelizeImageRegion( ImageDimension - 1, &reqRegion.GetIndex()[1], &reqRegion.GetSize()[1], [&](const IndexValueType index[], const SizeValueType size[]) { RegionType r; r.SetIndex(0, reqRegion.GetIndex(0)); r.SetSize(0, reqRegion.GetSize(0)); for (unsigned d = 1; d < ImageDimension; d++) { r.SetIndex(d, index[d - 1]); r.SetSize(d, size[d - 1]); } this->ThreadedIntegrateData(r); }, nullptr); this->UpdateProgress(0.99f); this->AfterThreadedGenerateData(); this->UpdateProgress(1.0f); } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::BeforeThreadedGenerateData() { OutputImagePointer output = this->GetOutput(); InputImageConstPointer input = this->GetInput(); RegionType reqRegion = output->GetRequestedRegion(); SizeValueType pixelcount = reqRegion.GetNumberOfPixels(); SizeValueType xsize = reqRegion.GetSize()[0]; SizeValueType linecount = pixelcount / xsize; m_ForegroundLineMap.clear(); m_ForegroundLineMap.resize(linecount); m_BackgroundLineMap.clear(); m_BackgroundLineMap.resize(linecount); } template<typename TInputImage, typename TOutputImage> SizeValueType BinaryContourImageFilter<TInputImage, TOutputImage> ::IndexToLinearIndex(IndexType index) { SizeValueType li = 0; SizeValueType stride = 1; RegionType r = this->GetOutput()->GetRequestedRegion(); //ignore x axis, which is always full size for (unsigned d = 1; d < ImageDimension; d++) { itkAssertOrThrowMacro(r.GetIndex(d) <= index[d], "Index must be within requested region!"); li += (index[d] - r.GetIndex(d))*stride; stride *= r.GetSize(d); } return li; } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::DynamicThreadedGenerateData(const RegionType & outputRegionForThread) { OutputImagePointer output = this->GetOutput(); InputImageConstPointer input = this->GetInput(); using InputLineIteratorType = itk::ImageLinearConstIteratorWithIndex<InputImageType>; InputLineIteratorType inLineIt(input, outputRegionForThread); inLineIt.SetDirection(0); using OutputLineIteratorType = itk::ImageLinearIteratorWithIndex<OutputImageType>; OutputLineIteratorType outLineIt(output, outputRegionForThread); outLineIt.SetDirection(0); outLineIt.GoToBegin(); for ( inLineIt.GoToBegin(); !inLineIt.IsAtEnd(); inLineIt.NextLine(), outLineIt.NextLine() ) { inLineIt.GoToBeginOfLine(); outLineIt.GoToBeginOfLine(); LineEncodingType fgLine; LineEncodingType bgLine; while ( !inLineIt.IsAtEndOfLine() ) { InputImagePixelType PVal = inLineIt.Get(); if ( Math::AlmostEquals(PVal, m_ForegroundValue) ) { // We've hit the start of a run SizeValueType length = 0; IndexType thisIndex = inLineIt.GetIndex(); outLineIt.Set(m_BackgroundValue); ++length; ++inLineIt; ++outLineIt; while ( !inLineIt.IsAtEndOfLine() && Math::AlmostEquals( inLineIt.Get(), m_ForegroundValue ) ) { outLineIt.Set(m_BackgroundValue); ++length; ++inLineIt; ++outLineIt; } // create the run length object to go in the vector fgLine.push_back( runLength( length, thisIndex ) ); } else { // We've hit the start of a run SizeValueType length = 0; IndexType thisIndex = inLineIt.GetIndex(); outLineIt.Set(PVal); ++length; ++inLineIt; ++outLineIt; while ( !inLineIt.IsAtEndOfLine() && Math::NotAlmostEquals( inLineIt.Get(), m_ForegroundValue ) ) { outLineIt.Set( inLineIt.Get() ); ++length; ++inLineIt; ++outLineIt; } // create the run length object to go in the vector bgLine.push_back( runLength( length, thisIndex ) ); } } SizeValueType lineId = IndexToLinearIndex(inLineIt.GetIndex()); m_ForegroundLineMap[lineId] = fgLine; m_BackgroundLineMap[lineId] = bgLine; lineId++; } } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::ThreadedIntegrateData(const RegionType & outputRegionForThread) { OutputImagePointer output = this->GetOutput(); using OutputLineIteratorType = itk::ImageLinearIteratorWithIndex<OutputImageType>; OutputLineIteratorType outLineIt(output, outputRegionForThread); outLineIt.SetDirection(0); OffsetVec LineOffsets; SetupLineOffsets(LineOffsets); RegionType reqRegion = output->GetRequestedRegion(); SizeValueType pixelcount = reqRegion.GetNumberOfPixels(); SizeValueType xsize = reqRegion.GetSize()[0]; OffsetValueType linecount = pixelcount / xsize; for (outLineIt.GoToBegin(); !outLineIt.IsAtEnd(); outLineIt.NextLine()) { SizeValueType thisIdx = IndexToLinearIndex(outLineIt.GetIndex()); if ( !m_ForegroundLineMap[thisIdx].empty() ) { for ( typename OffsetVec::const_iterator I = LineOffsets.begin(); I != LineOffsets.end(); ++I ) { OffsetValueType NeighIdx = thisIdx + ( *I ); // check if the neighbor is in the map if ( NeighIdx >= 0 && NeighIdx < OffsetValueType(linecount) && !m_BackgroundLineMap[NeighIdx].empty() ) { // Now check whether they are really neighbors bool areNeighbors = CheckNeighbors(m_ForegroundLineMap[thisIdx][0].m_Where, m_BackgroundLineMap[NeighIdx][0].m_Where); if ( areNeighbors ) { // Compare the two lines CompareLines(m_ForegroundLineMap[thisIdx], m_BackgroundLineMap[NeighIdx]); } } } } } } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::AfterThreadedGenerateData() { m_ForegroundLineMap.clear(); m_BackgroundLineMap.clear(); } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::SetupLineOffsets(OffsetVec & LineOffsets) { // Create a neighborhood so that we can generate a table of offsets // to "previous" line indexes // We are going to mis-use the neighborhood iterators to compute the // offset for us. All this messing around produces an array of // offsets that will be used to index the map OutputImagePointer output = this->GetOutput(); const unsigned int PretendDimension = ImageDimension - 1; using PretendImageType = Image< OffsetValueType, PretendDimension >; using PretendImagePointer = typename PretendImageType::Pointer; using PretendImageRegionType = typename PretendImageType::RegionType; using PretendSizeType = typename PretendImageType::RegionType::SizeType; using PretendIndexType = typename PretendImageType::RegionType::IndexType; PretendImagePointer fakeImage = PretendImageType::New(); PretendImageRegionType LineRegion; //LineRegion = PretendImageType::RegionType::New(); OutputSizeType OutSize = output->GetRequestedRegion().GetSize(); PretendSizeType PretendSize; // The first dimension has been collapsed for ( unsigned int i = 0; i < PretendDimension; i++ ) { PretendSize[i] = OutSize[i + 1]; } LineRegion.SetSize(PretendSize); fakeImage->SetRegions(LineRegion); PretendSizeType kernelRadius; kernelRadius.Fill(1); using LineNeighborhoodType = ConstShapedNeighborhoodIterator< PretendImageType >; LineNeighborhoodType lnit(kernelRadius, fakeImage, LineRegion); setConnectivity(&lnit, m_FullyConnected); typename LineNeighborhoodType::IndexListType ActiveIndexes; ActiveIndexes = lnit.GetActiveIndexList(); typename LineNeighborhoodType::IndexListType::const_iterator LI; PretendIndexType idx = LineRegion.GetIndex(); OffsetValueType offset = fakeImage->ComputeOffset(idx); for ( LI = ActiveIndexes.begin(); LI != ActiveIndexes.end(); ++LI ) { LineOffsets.push_back( fakeImage->ComputeOffset( idx + lnit.GetOffset(*LI) ) - offset ); } LineOffsets.push_back(0); // LineOffsets is the thing we wanted. } template< typename TInputImage, typename TOutputImage > bool BinaryContourImageFilter< TInputImage, TOutputImage > ::CheckNeighbors(const OutputIndexType & A, const OutputIndexType & B) { // this checks whether the line encodings are really neighbors. The // first dimension gets ignored because the encodings are along that // axis for ( unsigned int i = 1; i < ImageDimension; i++ ) { if ( itk::Math::abs( A[i] - B[i] ) > 1 ) { return ( false ); } } return ( true ); } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::CompareLines(LineEncodingType & current, const LineEncodingType & Neighbour) { bool sameLine = true; OutputOffsetType Off = current[0].m_Where - Neighbour[0].m_Where; for ( unsigned int i = 1; i < ImageDimension; i++ ) { if ( Off[i] != 0 ) { sameLine = false; break; } } OffsetValueType offset = 0; if ( m_FullyConnected || sameLine ) { offset = 1; } OutputImagePointer output = this->GetOutput(); // out marker iterator auto mIt = Neighbour.begin(); for ( auto cIt = current.begin(); cIt != current.end(); ++cIt ) { // the start x position OffsetValueType cStart = cIt->m_Where[0]; OffsetValueType cLast = cStart + cIt->m_Length - 1; bool lineCompleted = false; for ( auto nIt = mIt; nIt != Neighbour.end() && !lineCompleted; ++nIt ) { OffsetValueType nStart = nIt->m_Where[0]; OffsetValueType nLast = nStart + nIt->m_Length - 1; // there are a few ways that neighbouring lines might overlap // neighbor S------------------E // current S------------------------E //------------- // neighbor S------------------E // current S----------------E //------------- // neighbor S------------------E // current S------------------E //------------- // neighbor S------------------E // current S-------E //------------- OffsetValueType ss1 = nStart - offset; OffsetValueType ee2 = nLast + offset; bool eq = false; OffsetValueType oStart = 0; OffsetValueType oLast = 0; // the logic here can probably be improved a lot if ( ( ss1 >= cStart ) && ( ee2 <= cLast ) ) { // case 1 eq = true; oStart = ss1; oLast = ee2; } else if ( ( ss1 <= cStart ) && ( ee2 >= cLast ) ) { // case 4 eq = true; oStart = cStart; oLast = cLast; } else if ( ( ss1 <= cLast ) && ( ee2 >= cLast ) ) { // case 2 eq = true; oStart = ss1; oLast = cLast; } else if ( ( ss1 <= cStart ) && ( ee2 >= cStart ) ) { // case 3 eq = true; oStart = cStart; oLast = ee2; } if ( eq ) { itkAssertOrThrowMacro( ( oStart <= oLast ), "Start and Last out of order" ); IndexType idx = cIt->m_Where; for ( OffsetValueType x = oStart; x <= oLast; x++ ) { idx[0] = x; output->SetPixel(idx, m_ForegroundValue); } if ( oStart == cStart && oLast == cLast ) { lineCompleted = true; } } } } } template< typename TInputImage, typename TOutputImage > void BinaryContourImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "FullyConnected: " << m_FullyConnected << std::endl; os << indent << "ForegroundValue: " << static_cast< typename NumericTraits< InputImagePixelType >::PrintType >( m_ForegroundValue ) << std::endl; os << indent << "BackgroundValue: " << static_cast< typename NumericTraits< OutputImagePixelType >::PrintType >( m_BackgroundValue ) << std::endl; } } // end namespace itk #endif
30.609524
115
0.651338
[ "object", "vector" ]
b85fb919ef045aceb281c685401769c925b94067
5,045
cpp
C++
components/m8rscript/GC.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
1
2018-01-30T19:37:27.000Z
2018-01-30T19:37:27.000Z
components/m8rscript/GC.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
null
null
null
components/m8rscript/GC.cpp
cmarrin/m8rscript
4e24800e1be2c2c5e2ec1b7b52aa6df787e6460c
[ "MIT" ]
3
2017-04-01T23:41:35.000Z
2019-12-14T23:26:24.000Z
/*------------------------------------------------------------------------- This source file is a part of m8rscript For the latest info, see http:www.marrin.org/ Copyright (c) 2018-2019, Chris Marrin All rights reserved. Use of this source code is governed by the MIT license that can be found in the LICENSE file. -------------------------------------------------------------------------*/ #include "GC.h" #include "Containers.h" #include "Executable.h" #include "Object.h" #include "MStream.h" #include "SystemInterface.h" using namespace m8rscript; using namespace m8r; static Vector<RawMad> _objectStore; static Vector<RawMad> _stringStore; static Vector<SharedPtr<Executable>> _executableStore; static Vector<RawMad> _staticObjects; GC::GCState GC::gcState = GCState::ClearMarkedObj; uint32_t GC::prevGCObjects = 0; uint32_t GC::prevGCStrings = 0; uint8_t GC::countSinceLastGC = 0; bool GC::inGC = false; void GC::gc(bool force) { if (inGC) { return; } force = true; inGC = true; bool didFullCycle = gcState == GCState::ClearMarkedObj; while (1) { switch(gcState) { case GCState::ClearMarkedObj: if (!force && _objectStore.size() - prevGCObjects < MaxGCObjectDiff && _stringStore.size() - prevGCStrings < MaxGCStringDiff && ++countSinceLastGC < MaxCountSinceLastGC) { inGC = false; return; } for (RawMad& it : _objectStore) { Mad<Object> obj = Mad<Object>(it); obj->setMarked(false); } gcState = GCState::ClearMarkedStr; break; case GCState::ClearMarkedStr: for (RawMad& it : _stringStore) { Mad<String> str = Mad<String>(it); str->setMarked(false); } gcState = GCState::MarkActive; break; case GCState::MarkActive: for (auto it : _executableStore) { it->gcMark(); } gcState = GCState::MarkStatic; break; case GCState::MarkStatic: for (RawMad& it : _staticObjects) { Mad<Object> obj = Mad<Object>(it); obj->gcMark(); } gcState = GCState::SweepObj; break; case GCState::SweepObj: { auto it = std::remove_if(_objectStore.begin(), _objectStore.end(), [](RawMad m) { Mad<Object> obj = Mad<Object>(m); if (!obj->isMarked()) { delete obj.get(); return true; } return false; }); _objectStore.erase(it, _objectStore.end()); gcState = GCState::SweepStr; break; } case GCState::SweepStr: { auto it = std::remove_if(_stringStore.begin(), _stringStore.end(), [](RawMad m) { Mad<String> str = Mad<String>(m); if (!str->isMarked()) { str.destroy(); return true; } return false; }); _stringStore.erase(it, _stringStore.end()); gcState = GCState::ClearMarkedObj; if (!force || didFullCycle) { inGC = false; return; } didFullCycle = true; break; } } if (!force) { break; } } inGC = false; } namespace m8rscript { template<> void GC::addToStore<MemoryType::Object>(RawMad v) { _objectStore.push_back(v); } template<> void GC::addToStore<MemoryType::String>(RawMad v) { _stringStore.push_back(v); } template<> void GC::removeFromStore<MemoryType::Object>(RawMad v) { auto it = std::find(_objectStore.begin(), _objectStore.end(), v); if (it != _objectStore.end()) { _objectStore.erase(it); } } template<> void GC::removeFromStore<MemoryType::String>(RawMad v) { auto it = std::find(_stringStore.begin(), _stringStore.end(), v); if (it != _stringStore.end()) { _stringStore.erase(it); } } } void GC::addStaticObject(RawMad obj) { _staticObjects.push_back(obj); } void GC::removeStaticObject(RawMad obj) { auto it = std::find(_staticObjects.begin(), _staticObjects.end(), obj); if (it != _staticObjects.end()) { _staticObjects.erase(it); } } void GC::addExecutable(const SharedPtr<Executable>& eu) { _executableStore.push_back(eu); } void GC::removeExecutable(const SharedPtr<Executable>& eu) { auto it = std::find(_executableStore.begin(), _executableStore.end(), eu); if (it != _executableStore.end()) { _executableStore.erase(it); } }
28.828571
187
0.513181
[ "object", "vector" ]
b866dad274713028d23e1105a905532cbd5350a8
4,630
cpp
C++
roadway_objects/test/TestRoadwayObjectsWorker.cpp
harderthan/carma-platform
29921896a761a866db9cfee473f02a481d8bb9c9
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
roadway_objects/test/TestRoadwayObjectsWorker.cpp
harderthan/carma-platform
29921896a761a866db9cfee473f02a481d8bb9c9
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
null
null
null
roadway_objects/test/TestRoadwayObjectsWorker.cpp
harderthan/carma-platform
29921896a761a866db9cfee473f02a481d8bb9c9
[ "Apache-2.0", "CC-BY-4.0", "MIT" ]
1
2021-06-01T21:05:20.000Z
2021-06-01T21:05:20.000Z
/* * Copyright (C) 2019-2020 LEIDOS. * * 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 <roadway_objects/RoadwayObjectsWorker.h> #include <carma_wm/CARMAWorldModel.h> #include <tf2/LinearMath/Transform.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <gtest/gtest.h> #include "TestHelpers.h" namespace objects { TEST(RoadwayObjectsWorkerTest, testExternalObjectCallback) { std::shared_ptr<carma_wm::CARMAWorldModel> cmw = std::make_shared<carma_wm::CARMAWorldModel>(); // Build map auto p1 = carma_wm::getPoint(9, 0, 0); auto p2 = carma_wm::getPoint(9, 9, 0); auto p3 = carma_wm::getPoint(2, 0, 0); auto p4 = carma_wm::getPoint(2, 9, 0); lanelet::LineString3d right_ls_1(lanelet::utils::getId(), { p1, p2 }); lanelet::LineString3d left_ls_1(lanelet::utils::getId(), { p3, p4 }); auto ll_1 = carma_wm::getLanelet(left_ls_1, right_ls_1); lanelet::LaneletMapPtr map = lanelet::utils::createMap({ ll_1 }, {}); // Build external object geometry_msgs::Pose pose; pose.position.x = 6; pose.position.y = 5; pose.position.z = 0; tf2::Quaternion tf_orientation; tf_orientation.setRPY(0, 0, 1.5708); pose.orientation.x = tf_orientation.getX(); pose.orientation.y = tf_orientation.getY(); pose.orientation.z = tf_orientation.getZ(); pose.orientation.w = tf_orientation.getW(); geometry_msgs::Vector3 size; size.x = 4; size.y = 2; size.z = 1; cav_msgs::ExternalObject obj; obj.id = 1; obj.object_type = cav_msgs::ExternalObject::SMALL_VEHICLE; obj.pose.pose = pose; obj.velocity.twist.linear.x = 1.0; cav_msgs::PredictedState pred; auto pred_pose = obj.pose.pose; pred_pose.position.y += 1; pred.predicted_position = pred_pose; pred.predicted_position_confidence = 1.0; obj.predictions.push_back(pred); // Build roadway objects worker to test cav_msgs::RoadwayObstacleList resulting_objs; RoadwayObjectsWorker row(std::static_pointer_cast<const carma_wm::WorldModel>(cmw), [&](const cav_msgs::RoadwayObstacleList& objs) -> void { resulting_objs = objs; }); ASSERT_EQ(resulting_objs.roadway_obstacles.size(), 0); // Verify resulting_objs is empty // Build external object list cav_msgs::ExternalObjectList obj_list; obj_list.objects.push_back(obj); cav_msgs::ExternalObjectListConstPtr obj_list_msg_ptr(new cav_msgs::ExternalObjectList(obj_list)); // Test with no map set row.externalObjectsCallback(obj_list_msg_ptr); // Call function under test ASSERT_EQ(resulting_objs.roadway_obstacles.size(), 0); // Test with empty map lanelet::LaneletMapPtr empty_map = lanelet::utils::createMap({}, {}); cmw->setMap(empty_map); row.externalObjectsCallback(obj_list_msg_ptr); // Call function under test ASSERT_EQ(resulting_objs.roadway_obstacles.size(), 0); // Test with regular map cmw->setMap(map); row.externalObjectsCallback(obj_list_msg_ptr); // Call function under test ASSERT_EQ(resulting_objs.roadway_obstacles.size(), 1); cav_msgs::RoadwayObstacle obs = resulting_objs.roadway_obstacles[0]; ASSERT_EQ(obs.object.id, obj.id); // Check that the object was coppied ASSERT_EQ(obs.lanelet_id, ll_1.id()); ASSERT_EQ(obs.connected_vehicle_type.type, cav_msgs::ConnectedVehicleType::NOT_CONNECTED); ASSERT_NEAR(obs.cross_track, 0.5, 0.00001); ASSERT_NEAR(obs.down_track, 5.0, 0.00001); ASSERT_EQ(obs.predicted_lanelet_ids.size(), 1); ASSERT_EQ(obs.predicted_lanelet_ids[0], ll_1.id()); ASSERT_EQ(obs.predicted_lanelet_id_confidences.size(), 1); ASSERT_NEAR(obs.predicted_lanelet_id_confidences[0], 0.9, 0.00001); ASSERT_EQ(obs.predicted_cross_tracks.size(), 1); ASSERT_NEAR(obs.predicted_cross_tracks[0], 0.5, 0.00001); ASSERT_EQ(obs.predicted_cross_track_confidences.size(), 1); ASSERT_NEAR(obs.predicted_cross_track_confidences[0], 0.9, 0.00001); ASSERT_EQ(obs.predicted_down_tracks.size(), 1); ASSERT_NEAR(obs.predicted_down_tracks[0], 6.0, 0.00001); ASSERT_EQ(obs.predicted_down_track_confidences.size(), 1); ASSERT_NEAR(obs.predicted_down_track_confidences[0], 0.9, 0.00001); } } // namespace objects
33.309353
110
0.738661
[ "object", "transform" ]
b86f5e95989b6beff144d08a4d2f1ced11f7f522
9,392
cpp
C++
Game/PhysicsWorld.cpp
dwarfcrank/FantasyQuest
e5a35a8631dc056db8ffbc114354244b1530eaa6
[ "MIT" ]
1
2020-05-09T20:03:04.000Z
2020-05-09T20:03:04.000Z
Game/PhysicsWorld.cpp
dwarfcrank/FantasyQuest
e5a35a8631dc056db8ffbc114354244b1530eaa6
[ "MIT" ]
null
null
null
Game/PhysicsWorld.cpp
dwarfcrank/FantasyQuest
e5a35a8631dc056db8ffbc114354244b1530eaa6
[ "MIT" ]
null
null
null
#include "pch.h" #include "Transform.h" #include "PhysicsWorld.h" #include "Scene.h" #include "Mesh.h" #include "Math.h" #include "Components/Transform.h" #include <im3d.h> #include <unordered_map> #include <bullet/btBulletDynamicsCommon.h> using namespace math; static void setEntity(btCollisionObject* obj, entt::entity e) { obj->setUserIndex(int(e)); } static entt::entity getEntity(const btCollisionObject* obj) { if (auto idx = obj->getUserIndex(); idx != -1) { return entt::entity{ idx }; } return entt::null; } PhysicsWorld::PhysicsWorld(Scene& scene) : m_scene(scene) { m_collisionConfiguration = std::make_unique<btDefaultCollisionConfiguration>(); m_dispatcher = std::make_unique<btCollisionDispatcher>(m_collisionConfiguration.get()); m_overlappingPairCache = std::make_unique<btDbvtBroadphase>(); m_solver = std::make_unique<btSequentialImpulseConstraintSolver>(); m_dynamicsWorld = std::make_unique<btDiscreteDynamicsWorld>( m_dispatcher.get(), m_overlappingPairCache.get(), m_solver.get(), m_collisionConfiguration.get()); m_dynamicsWorld->setGravity(btVector3(0.0f, -10.0f, 0.0f)); m_dynamicsWorld->setDebugDrawer(&m_debugDraw); auto shape = m_collisionShapes.emplace_back(std::make_unique<btBoxShape>(btVector3(0.5f, 0.5f, 0.5f))).get(); m_collisionMeshes["basic_box"] = shape; } PhysicsWorld::~PhysicsWorld() { for (auto&& obj : m_collisionObjects) { m_dynamicsWorld->removeCollisionObject(obj.get()); } } void PhysicsWorld::onCreatePhysicsComponent(entt::registry& reg, entt::entity entity) { // TODO: most of this should be handled in the Physics component constructor // and this should just add the component to the simulation auto [tc, pc] = reg.get<components::Transform, components::Physics>(entity); pc.collisionShape = getCollisionMesh("basic_box"); btTransform transform; transform.setIdentity(); transform.setOrigin(btVector3(tc.position.x, tc.position.y, tc.position.z)); btQuaternion rot; rot.set128(tc.rotationQuat); transform.setRotation(rot); btVector3 localInertia(0.0f, 0.0f, 0.0f); if (pc.mass != 0.0f) { pc.collisionShape->calculateLocalInertia(pc.mass, localInertia); } auto motionState = std::make_unique<btDefaultMotionState>(transform); btRigidBody::btRigidBodyConstructionInfo info(pc.mass, motionState.get(), pc.collisionShape, localInertia); auto body = std::make_unique<btRigidBody>(info); setEntity(body.get(), reg.entity(entity)); m_dynamicsWorld->addRigidBody(body.get()); pc.collisionObject = std::move(body); pc.motionState = std::move(motionState); } void PhysicsWorld::onDestroyPhysicsComponent(entt::registry& reg, entt::entity entity) { auto& pc = reg.get<components::Physics>(entity); m_dynamicsWorld->removeCollisionObject(pc.collisionObject.get()); } void PhysicsWorld::onCreateCollisionComponent(entt::registry& reg, entt::entity entity) { // TODO: most of this should be handled in the Physics component constructor // and this should just add the component to the simulation auto [tc, cc] = reg.get<components::Transform, components::Collision>(entity); cc.collisionShape = getCollisionMesh("basic_box"); btQuaternion rot; rot.set128(tc.rotationQuat); btTransform transform; transform.setIdentity(); transform.setOrigin(btVector3(tc.position.x, tc.position.y, tc.position.z)); transform.setRotation(rot); auto obj = std::make_unique<btCollisionObject>(); //obj->setWorldTransform(transform); obj->setWorldTransform(btTransform(rot, btVector3(tc.position.x, tc.position.y, tc.position.z))); obj->setCollisionShape(cc.collisionShape); setEntity(obj.get(), reg.entity(entity)); m_dynamicsWorld->addCollisionObject(obj.get()); cc.collisionObject = std::move(obj); } void PhysicsWorld::onDestroyCollisionComponent(entt::registry& reg, entt::entity entity) { auto& cc = reg.get<components::Collision>(entity); m_dynamicsWorld->removeCollisionObject(cc.collisionObject.get()); } void PhysicsWorld::addBox(float hw, float hh, float hd, float mass, float x, float y, float z) { auto shape = m_collisionShapes.emplace_back(new btBoxShape(btVector3(hw, hh, hd))).get(); btTransform t; t.setIdentity(); t.setOrigin(btVector3(x, y, z)); auto motionState = std::make_unique<btDefaultMotionState>(t); btRigidBody::btRigidBodyConstructionInfo info(mass, motionState.get(), shape); auto body = std::make_unique<btRigidBody>(info); body->setUserPointer(nullptr); m_dynamicsWorld->addRigidBody(body.get()); m_collisionObjects.emplace_back(std::move(body)); m_motionStates.emplace_back(std::move(motionState)); } void PhysicsWorld::addSphere(float radius, float mass, float x, float y, float z) { auto shape = m_collisionShapes.emplace_back(new btSphereShape(radius)).get(); btTransform t; t.setIdentity(); t.setOrigin(btVector3(x, y, z)); btVector3 localInertia(0.0f, 0.0f, 0.0f); shape->calculateLocalInertia(mass, localInertia); auto motionState = std::make_unique<btDefaultMotionState>(t); btRigidBody::btRigidBodyConstructionInfo info(mass, motionState.get(), shape, localInertia); auto body = std::make_unique<btRigidBody>(info); body->setUserPointer(nullptr); m_dynamicsWorld->addRigidBody(body.get()); m_collisionObjects.emplace_back(std::move(body)); m_motionStates.emplace_back(std::move(motionState)); } btCollisionShape* PhysicsWorld::createCollisionMesh(const std::string& name, const Mesh& mesh) { assert(!m_collisionMeshes.contains(name)); const auto& indices = mesh.getIndices(); const auto& vIn = mesh.getVertices(); std::vector<XMFLOAT3> vOut(indices.size()); for (size_t i = 0; i < indices.size(); i++) { vOut[i] = vIn[indices[i]].Position; } auto shape = std::make_unique<btConvexHullShape>(&vOut[0].x, int(vOut.size()), int(sizeof(XMFLOAT3))); shape->optimizeConvexHull(); shape->initializePolyhedralFeatures(); m_collisionMeshes[name] = shape.get(); return m_collisionShapes.emplace_back(std::move(shape)).get(); } btCollisionShape* PhysicsWorld::getCollisionMesh(const std::string& name) { if (auto it = m_collisionMeshes.find(name); it != m_collisionMeshes.end()) { return it->second; } return nullptr; } void PhysicsWorld::editorUpdate() { m_dynamicsWorld->updateAabbs(); m_dynamicsWorld->computeOverlappingPairs(); } void PhysicsWorld::update(float dt) { m_dynamicsWorld->stepSimulation(dt, 10); m_scene.reg.view<components::Transform, components::Physics>() .each([&](entt::entity entity, const components::Transform&, const components::Physics& pc) { btTransform ft; if (pc.motionState) { pc.motionState->getWorldTransform(ft); } else { ft = pc.collisionObject->getWorldTransform(); } const auto& origin = ft.getOrigin(); m_scene.reg.patch<components::Transform>(entity, [&](components::Transform& tc) { tc.position = XMFLOAT3(origin.x(), origin.y(), origin.z()); tc.rotationQuat = ft.getRotation().get128(); }); }); } void PhysicsWorld::setDebugDrawMode(int mode) { m_debugDraw.setDebugMode(mode); } void PhysicsWorld::render() { Im3d::PushMatrix(Im3d::Mat4(1.0f)); m_dynamicsWorld->debugDrawWorld(); Im3d::PopMatrix(); } RaycastHit PhysicsWorld::raycast(math::WorldVector from0, math::WorldVector to0) { btVector3 from, to; from.set128(from0.vec); to.set128(to0.vec); btCollisionWorld::ClosestRayResultCallback result(from, to); m_dynamicsWorld->rayTest(from, to, result); if (result.hasHit()) { RaycastHit hit; btVector3 h(0.1f, 0.1f, 0.1f); hit.entity = getEntity(result.m_collisionObject); hit.position.vec = XMVectorSetW(result.m_hitPointWorld.get128(), 1.0f); hit.normal.vec = XMVectorSetW(result.m_hitNormalWorld.get128(), 0.0f); return hit; } return RaycastHit{}; } void PhysicsDebugDraw::drawLine(const btVector3& from, const btVector3& to, const btVector3& color) { u32 c2 = 0x00'00'00'ff; c2 |= (u32(color.x() * 255.0f) << 24); c2 |= (u32(color.y() * 255.0f) << 16); c2 |= (u32(color.z() * 255.0f) << 8); Im3d::DrawLine( Im3d::Vec3(from.x(), from.y(), from.z()), Im3d::Vec3(to.x(), to.y(), to.z()), 2.0f, c2 ); } void PhysicsDebugDraw::drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color) { } void PhysicsDebugDraw::reportErrorWarning(const char* warningString) { } void PhysicsDebugDraw::draw3dText(const btVector3& location, const char* textString) { } void PhysicsDebugDraw::setDebugMode(int debugMode) { m_debugMode = debugMode; } int PhysicsDebugDraw::getDebugMode() const { return m_debugMode; }
31.516779
152
0.672061
[ "mesh", "render", "shape", "vector", "transform" ]
b8725fc761b56a8c2237df010525d9711b6dcb70
4,184
hxx
C++
opencascade/LocOpe_SplitDrafts.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/LocOpe_SplitDrafts.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/LocOpe_SplitDrafts.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1996-10-02 // Created by: Jacques GOUSSARD // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _LocOpe_SplitDrafts_HeaderFile #define _LocOpe_SplitDrafts_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <TopoDS_Shape.hxx> #include <TopTools_DataMapOfShapeListOfShape.hxx> #include <Standard_Real.hxx> #include <Standard_Boolean.hxx> #include <TopTools_ListOfShape.hxx> class StdFail_NotDone; class Standard_NoSuchObject; class Standard_ConstructionError; class Standard_NullObject; class TopoDS_Shape; class TopoDS_Face; class TopoDS_Wire; class gp_Dir; class gp_Pln; //! This class provides a tool to realize the //! following operations on a shape : //! - split a face of the shape with a wire, //! - put draft angle on both side of the wire. //! For each side, the draft angle may be different. class LocOpe_SplitDrafts { public: DEFINE_STANDARD_ALLOC //! Empty constructor. LocOpe_SplitDrafts(); //! Creates the algoritm on the shape <S>. LocOpe_SplitDrafts(const TopoDS_Shape& S); //! Initializes the algoritm with the shape <S>. Standard_EXPORT void Init (const TopoDS_Shape& S); //! Splits the face <F> of the former given shape with //! the wire <W>. The wire is assumed to lie on the //! face. Puts a draft angle on both parts of the //! wire. <Extractg>, <Nplg>, <Angleg> define the //! arguments for the left part of the wire. //! <Extractd>, <Npld>, <Angled> define the arguments //! for the right part of the wire. The draft angle is //! measured with the direction <Extract>. <Npl> //! defines the neutral plane (points belonging to the //! neutral plane are not modified). <Angle> is the //! value of the draft angle. If <ModifyLeft> is set //! to <Standard_False>, no draft angle is applied to //! the left part of the wire. If <ModifyRight> is set //! to <Standard_False>,no draft angle is applied to //! the right part of the wire. Standard_EXPORT void Perform (const TopoDS_Face& F, const TopoDS_Wire& W, const gp_Dir& Extractg, const gp_Pln& NPlg, const Standard_Real Angleg, const gp_Dir& Extractd, const gp_Pln& NPld, const Standard_Real Angled, const Standard_Boolean ModifyLeft = Standard_True, const Standard_Boolean ModifyRight = Standard_True); //! Splits the face <F> of the former given shape with //! the wire <W>. The wire is assumed to lie on the //! face. Puts a draft angle on the left part of the //! wire. The draft angle is measured with the //! direction <Extract>. <Npl> defines the neutral //! plane (points belonging to the neutral plane are //! not modified). <Angle> is the value of the draft //! angle. Standard_EXPORT void Perform (const TopoDS_Face& F, const TopoDS_Wire& W, const gp_Dir& Extract, const gp_Pln& NPl, const Standard_Real Angle); //! Returns <Standard_True> if the modification has //! been succesfully performed. Standard_Boolean IsDone() const; const TopoDS_Shape& OriginalShape() const; //! Returns the modified shape. Standard_EXPORT const TopoDS_Shape& Shape() const; //! Manages the descendant shapes. Standard_EXPORT const TopTools_ListOfShape& ShapesFromShape (const TopoDS_Shape& S) const; protected: private: TopoDS_Shape myShape; TopoDS_Shape myResult; TopTools_DataMapOfShapeListOfShape myMap; }; #include <LocOpe_SplitDrafts.lxx> #endif // _LocOpe_SplitDrafts_HeaderFile
32.6875
323
0.728011
[ "shape" ]
b87defdd4d1bdfebabdc8a150be3395541d15553
6,078
hpp
C++
boost/proto/transform/impl.hpp
mike-code/boost_1_38_0
7ff8b2069344ea6b0b757aa1f0778dfb8526df3c
[ "BSL-1.0" ]
null
null
null
boost/proto/transform/impl.hpp
mike-code/boost_1_38_0
7ff8b2069344ea6b0b757aa1f0778dfb8526df3c
[ "BSL-1.0" ]
null
null
null
boost/proto/transform/impl.hpp
mike-code/boost_1_38_0
7ff8b2069344ea6b0b757aa1f0778dfb8526df3c
[ "BSL-1.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// \file impl.hpp /// Contains definition of transform<> and transform_impl<> helpers. // // Copyright 2008 Eric Niebler. 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) #ifndef BOOST_PROTO_TRANSFORM_IMPL_HPP_EAN_04_03_2008 #define BOOST_PROTO_TRANSFORM_IMPL_HPP_EAN_04_03_2008 #include <boost/proto/detail/prefix.hpp> #include <boost/proto/proto_fwd.hpp> #include <boost/proto/detail/suffix.hpp> namespace boost { namespace proto { template<typename PrimitiveTransform, typename Expr, typename State = int, typename Data = int> struct apply_transform : PrimitiveTransform::template impl<Expr, State, Data> {}; struct transform_base { BOOST_PROTO_CALLABLE() BOOST_PROTO_TRANSFORM() }; struct empty_base {}; template< typename PrimitiveTransform , typename Base BOOST_PROTO_WHEN_BUILDING_DOCS(= transform_base) > struct transform : Base { typedef PrimitiveTransform transform_type; template<typename Sig> struct result; template<typename This, typename Expr> struct result<This(Expr)> { typedef typename PrimitiveTransform::template impl<Expr, int, int>::result_type type; }; template<typename This, typename Expr, typename State> struct result<This(Expr, State)> { typedef typename PrimitiveTransform::template impl<Expr, State, int>::result_type type; }; template<typename This, typename Expr, typename State, typename Data> struct result<This(Expr, State, Data)> { typedef typename PrimitiveTransform::template impl<Expr, State, Data>::result_type type; }; template<typename Expr> typename apply_transform<PrimitiveTransform, Expr &>::result_type operator ()(Expr &e) const { int i = 0; return apply_transform<PrimitiveTransform, Expr &>()(e, i, i); } template<typename Expr, typename State> typename apply_transform<PrimitiveTransform, Expr &, State &>::result_type operator ()(Expr &e, State &s) const { int i = 0; return apply_transform<PrimitiveTransform, Expr &, State &>()(e, s, i); } template<typename Expr, typename State> typename apply_transform<PrimitiveTransform, Expr &, State const &>::result_type operator ()(Expr &e, State const &s) const { int i = 0; return apply_transform<PrimitiveTransform, Expr &, State const &>()(e, s, i); } template<typename Expr, typename State, typename Data> typename apply_transform<PrimitiveTransform, Expr &, State &, Data &>::result_type operator ()(Expr &e, State &s, Data &d) const { return apply_transform<PrimitiveTransform, Expr &, State &, Data &>()(e, s, d); } template<typename Expr, typename State, typename Data> typename apply_transform<PrimitiveTransform, Expr &, State const &, Data &>::result_type operator ()(Expr &e, State const &s, Data &d) const { return apply_transform<PrimitiveTransform, Expr &, State const &, Data &>()(e, s, d); } }; template<typename Expr, typename State, typename Data> struct transform_impl { typedef Expr const expr; typedef Expr const &expr_param; typedef State const state; typedef State const &state_param; typedef Data const data; typedef Data const &data_param; }; template<typename Expr, typename State, typename Data> struct transform_impl<Expr &, State, Data> { typedef Expr expr; typedef Expr &expr_param; typedef State const state; typedef State const &state_param; typedef Data const data; typedef Data const &data_param; }; template<typename Expr, typename State, typename Data> struct transform_impl<Expr, State &, Data> { typedef Expr const expr; typedef Expr const &expr_param; typedef State state; typedef State &state_param; typedef Data const data; typedef Data const &data_param; }; template<typename Expr, typename State, typename Data> struct transform_impl<Expr, State, Data &> { typedef Expr const expr; typedef Expr const &expr_param; typedef State const state; typedef State const &state_param; typedef Data data; typedef Data &data_param; }; template<typename Expr, typename State, typename Data> struct transform_impl<Expr &, State &, Data> { typedef Expr expr; typedef Expr &expr_param; typedef State state; typedef State &state_param; typedef Data const data; typedef Data const &data_param; }; template<typename Expr, typename State, typename Data> struct transform_impl<Expr &, State, Data &> { typedef Expr expr; typedef Expr &expr_param; typedef State const state; typedef State const &state_param; typedef Data data; typedef Data &data_param; }; template<typename Expr, typename State, typename Data> struct transform_impl<Expr, State &, Data &> { typedef Expr const expr; typedef Expr const &expr_param; typedef State state; typedef State &state_param; typedef Data data; typedef Data &data_param; }; template<typename Expr, typename State, typename Data> struct transform_impl<Expr &, State &, Data &> { typedef Expr expr; typedef Expr &expr_param; typedef State state; typedef State &state_param; typedef Data data; typedef Data &data_param; }; }} // namespace boost::proto #endif
31.82199
100
0.627015
[ "transform" ]
b8893c44f29ea91c3baf27f9f39bf0792f984c89
2,055
hpp
C++
SRC/GLD/Window.hpp
GustavoGLD/CLI-Graphics-Library
0f5a884f42618ac2a39ec2061a30d1be5a438e9f
[ "MIT" ]
1
2021-08-29T01:01:41.000Z
2021-08-29T01:01:41.000Z
SRC/GLD/Window.hpp
GustavoGLD/Fast-CLI-Game-Engine
0f5a884f42618ac2a39ec2061a30d1be5a438e9f
[ "MIT" ]
null
null
null
SRC/GLD/Window.hpp
GustavoGLD/Fast-CLI-Game-Engine
0f5a884f42618ac2a39ec2061a30d1be5a438e9f
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <thread> #include "Vectors.hpp" #include "Drawable.hpp" #include "Impl/TimeImpl.hpp" #include "Impl/InputImpl.hpp" #include "Colors.hpp" #include "Input.hpp" #if defined(_WIN32) || defined(_WIN64) #define ClearPrompt() system("cls"); #endif #if defined(__linux__) || defined(__FreeBSD__) #define ClearPrompt() system("clear"); #endif namespace gld { class Window : public gld::Time { private: unsigned int height, width; std::vector<std::vector<std::string>> map; std::thread input_thr; public: inline Window(unsigned int width,unsigned int height, bool sync_with_stdio = false) { setTimeInit(); this->height = height; this->width = width; std::ios_base::sync_with_stdio(sync_with_stdio); map = std::vector<std::vector<std::string>>(height, std::vector<std::string>(width)); input_thr = std::thread(Input::getInput); } inline void clear(gld::AnsiColor backgroud = gld::ANSI::Black) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { map[y][x] = backgroud; } } } inline void clear(gld::RgbColor background) { clear(gld::getAnsiColor(background)); } inline void clear(uint8_t R, uint8_t G, uint8_t B) { clear(gld::getAnsiColor(R, G, B)); } inline void draw(gld::Drawable& drawable) { drawable.draw(map); } inline void display() { setFrameInit(); ClearPrompt(); std::string buffer; gld::AnsiColor last_color; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (map[y][x] != last_color){ buffer += map[y][x]; last_color = map[y][x]; } else { buffer += " "; } } buffer += "\r\n"; } std::cout.write(buffer.data(), buffer.size()); } }; }
22.096774
93
0.537713
[ "vector" ]
b88adf002963b8486be40bfeaf8881685314e327
5,026
hpp
C++
oss_src/sketches/countsketch.hpp
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
493
2016-07-11T13:35:24.000Z
2022-02-15T13:04:29.000Z
oss_src/sketches/countsketch.hpp
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
27
2016-07-13T20:01:07.000Z
2022-02-01T18:55:28.000Z
oss_src/sketches/countsketch.hpp
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
229
2016-07-12T10:39:54.000Z
2022-02-15T13:04:31.000Z
/** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #ifndef GRAPHLAB_SKETCHES_COUNTSKETCH_HPP #define GRAPHLAB_SKETCHES_COUNTSKETCH_HPP #include <cmath> #include <cstdint> #include <functional> #include <random/random.hpp> #include <util/cityhash_gl.hpp> #include <logger/assertions.hpp> namespace graphlab { namespace sketches { typedef int64_t counter_int; /** * An implementation of the CountSketch for estimating the frequency * of each item in a stream. * * Usage is simple. * \code * countsketch<T> c; // for approximate counting of a stream with type T * // repeatedly call * c.add(x) // x can be anything that is hashable. * c.estimate(x) // will return an estimate of the frequency for * // a given element * \endcode * */ template <typename T> class countsketch { private: size_t num_hash = 0; /// Number of hash functions to use size_t num_bits = 0; /// 2^b is the number of hash bins size_t num_bins = 0; /// equal to 2^b: The number of buckets std::vector<size_t> seeds; std::vector<size_t> seeds_binary; std::vector<std::vector<counter_int> > counts; /// Buckets public: /** * Constructs a CountSketch having "width" 2^bits and "depth". * The size of the matrix of counts will be depth x 2^bits. * * \param bits The number of bins will be 2^bits. * * \param depth The "depth" of the sketch is the number of hash functions * that will be used on each item. */ explicit inline countsketch(size_t bits = 16, size_t depth = 5, size_t seed = 1000): num_hash(depth), num_bits(bits), num_bins(1 << num_bits) { ASSERT_GE(num_bins, 16); random::generator gen; gen.seed(seed); // Initialize hash functions and count matrix for (size_t j = 0; j < num_hash; ++j) { seeds.push_back(gen.fast_uniform<size_t>(0, std::numeric_limits<size_t>::max())); seeds_binary.push_back(gen.fast_uniform<size_t>(0, std::numeric_limits<size_t>::max())); counts.push_back(std::vector<counter_int>(num_bins)); } } /** * Adds an arbitrary object to be counted. Any object type can be used, * and there are no restrictions as long as std::hash<T> can be used to * obtain a hash value. * * Note: * Theoretical properties only apply to the situation where count is 1. */ void add(const T& t, size_t count = 1) { // Create a 64-bit number from the object size_t i = hash64(std::hash<T>()(t)); for (size_t j = 0; j < num_hash; ++j) { // convert trailing bit to 1 or -1 counter_int s = (counter_int)( hash64(seeds_binary[j] ^ i) & 1); s = 2*s - 1; // compute which bin to increment size_t bin = hash64(seeds[j] ^ i) % num_bins; // TODO: bit mask counts[j][bin] += s * (counter_int) count; } } /** * Returns the estimate of the frequency for a given object. */ inline counter_int estimate(const T& t) { // Create a 64-bit number from the object size_t i = hash64(std::hash<T>()(t)); // Compute the minimum value across hashes. std::vector<counter_int> estimates; for (size_t j = 0; j < num_hash; ++j) { // convert trailing bit to 1 or -1 counter_int s = (counter_int) (hash64(seeds_binary[j] ^ i) & 1); // convert trailing bit to 1 or -1 s = 2*s - 1; // compute which bin to increment size_t bin = hash64(seeds[j] ^ i) % num_bins; // TODO: bit mask counter_int estimate = s * counts[j][bin]; estimates.push_back(estimate); } // Return the median std::nth_element(estimates.begin(), estimates.begin() + estimates.size()/2, estimates.end()); return estimates[estimates.size()/2]; } /** * Merge two CountSketch datastructures. * The two countsketch objects must have the same width and depth. */ void combine(const countsketch& other) { ASSERT_EQ(num_bins, other.num_bins); ASSERT_EQ(num_hash, other.num_hash); for (size_t j = 0; j < num_hash; ++j) { for (size_t b = 0; b < num_bins; ++b) { counts[j][b] += other.counts[j][b]; } } } ///// HELPER FUNCTIONS ///////////////// /** * Prints the internal matrix containing the current counts. */ inline void print() { for (size_t j = 0; j < num_hash; ++j) { std::cout << ">>> "; for (size_t b = 0; b < num_bins; ++b) { std::cout << counts[j][b] << " "; } std::cout << std::endl; } } /** * Computes the density of the internal counts matrix. */ inline double density() { size_t count = 0; for (size_t j = 0; j < num_hash; ++j) { for (size_t b = 0; b < num_bins; ++b) { if (counts[j][b] != 0) count += 1; } } return (double) count / (double) (num_hash * num_bins); } }; // countsketch } // namespace sketches } // namespace graphlab #endif
29.22093
106
0.616992
[ "object", "vector" ]
b894074238b8775de332871a1436920e18b08338
9,579
cxx
C++
vtkm/worklet/testing/UnitTestExtractStructured.cxx
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
1
2020-03-02T17:31:48.000Z
2020-03-02T17:31:48.000Z
vtkm/worklet/testing/UnitTestExtractStructured.cxx
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
1
2019-06-03T17:04:59.000Z
2019-06-05T15:13:28.000Z
vtkm/worklet/testing/UnitTestExtractStructured.cxx
yisyuanliou/VTK-m
cc483c8c2319a78b58b3ab849da8ca448e896220
[ "BSD-3-Clause" ]
1
2020-07-20T06:43:49.000Z
2020-07-20T06:43:49.000Z
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. // // Copyright 2014 National Technology & Engineering Solutions of Sandia, LLC (NTESS). // Copyright 2014 UT-Battelle, LLC. // Copyright 2014 Los Alamos National Security. // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Under the terms of Contract DE-AC52-06NA25396 with Los Alamos National // Laboratory (LANL), the U.S. Government retains certain rights in // this software. //============================================================================ #include <vtkm/worklet/ExtractStructured.h> #include <vtkm/cont/DataSet.h> #include <vtkm/cont/testing/MakeTestDataSet.h> #include <vtkm/cont/testing/Testing.h> using vtkm::cont::testing::MakeTestDataSet; template <typename DeviceAdapter> class TestingExtractStructured { public: void TestUniform2D() const { std::cout << "Testing extract structured uniform 2D" << std::endl; typedef vtkm::cont::CellSetStructured<2> CellSetType; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make2DUniformDataSet1(); CellSetType cellSet; dataSet.GetCellSet(0).CopyTo(cellSet); // RangeId3 and subsample vtkm::RangeId3 range(1, 4, 1, 4, 0, 1); vtkm::Id3 sample(1, 1, 1); bool includeBoundary = false; vtkm::worklet::ExtractStructured worklet; auto outCellSet = worklet.Run(cellSet, range, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 9), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 4), "Wrong result for ExtractStructured worklet"); } void TestUniform3D() const { std::cout << "Testing extract structured uniform 3D" << std::endl; typedef vtkm::cont::CellSetStructured<3> CellSetType; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make3DUniformDataSet1(); CellSetType cellSet; dataSet.GetCellSet(0).CopyTo(cellSet); vtkm::worklet::ExtractStructured worklet; vtkm::worklet::ExtractStructured::DynamicCellSetStructured outCellSet; // RangeId3 within dataset vtkm::RangeId3 range0(1, 4, 1, 4, 1, 4); vtkm::Id3 sample(1, 1, 1); bool includeBoundary = false; outCellSet = worklet.Run(cellSet, range0, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 27), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 8), "Wrong result for ExtractStructured worklet"); // RangeId3 surrounds dataset vtkm::RangeId3 range1(-1, 8, -1, 8, -1, 8); outCellSet = worklet.Run(cellSet, range1, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 125), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 64), "Wrong result for ExtractStructured worklet"); // RangeId3 intersects dataset on near boundary vtkm::RangeId3 range2(-1, 3, -1, 3, -1, 3); outCellSet = worklet.Run(cellSet, range2, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 27), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 8), "Wrong result for ExtractStructured worklet"); // RangeId3 intersects dataset on far boundary vtkm::RangeId3 range3(1, 8, 1, 8, 1, 8); outCellSet = worklet.Run(cellSet, range3, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 64), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 27), "Wrong result for ExtractStructured worklet"); // RangeId3 intersects dataset without corner vtkm::RangeId3 range4(2, 8, 1, 4, 1, 4); outCellSet = worklet.Run(cellSet, range4, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 27), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 8), "Wrong result for ExtractStructured worklet"); // RangeId3 intersects dataset with plane vtkm::RangeId3 range5(2, 8, 1, 2, 1, 4); outCellSet = worklet.Run(cellSet, range5, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 9), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 4), "Wrong result for ExtractStructured worklet"); } void TestUniform3D1() const { std::cout << "Testing extract structured uniform with sampling" << std::endl; typedef vtkm::cont::CellSetStructured<3> CellSetType; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make3DUniformDataSet1(); CellSetType cellSet; dataSet.GetCellSet(0).CopyTo(cellSet); vtkm::worklet::ExtractStructured worklet; vtkm::worklet::ExtractStructured::DynamicCellSetStructured outCellSet; // RangeId3 within data set with sampling vtkm::RangeId3 range0(0, 5, 0, 5, 1, 4); vtkm::Id3 sample0(2, 2, 1); bool includeBoundary0 = false; outCellSet = worklet.Run(cellSet, range0, sample0, includeBoundary0, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 27), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 8), "Wrong result for ExtractStructured worklet"); // RangeId3 and subsample vtkm::RangeId3 range1(0, 5, 0, 5, 1, 4); vtkm::Id3 sample1(3, 3, 2); bool includeBoundary1 = false; outCellSet = worklet.Run(cellSet, range1, sample1, includeBoundary1, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 8), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 1), "Wrong result for ExtractStructured worklet"); // RangeId3 and subsample vtkm::RangeId3 range2(0, 5, 0, 5, 1, 4); vtkm::Id3 sample2(3, 3, 2); bool includeBoundary2 = true; outCellSet = worklet.Run(cellSet, range2, sample2, includeBoundary2, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 18), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 4), "Wrong result for ExtractStructured worklet"); } void TestRectilinear2D() const { std::cout << "Testing extract structured rectilinear" << std::endl; typedef vtkm::cont::CellSetStructured<2> CellSetType; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make2DRectilinearDataSet0(); CellSetType cellSet; dataSet.GetCellSet(0).CopyTo(cellSet); // RangeId3 and subsample vtkm::RangeId3 range(0, 2, 0, 2, 0, 1); vtkm::Id3 sample(1, 1, 1); bool includeBoundary = false; // Extract subset vtkm::worklet::ExtractStructured worklet; auto outCellSet = worklet.Run(cellSet, range, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 4), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 1), "Wrong result for ExtractStructured worklet"); } void TestRectilinear3D() const { std::cout << "Testing extract structured rectilinear" << std::endl; typedef vtkm::cont::CellSetStructured<3> CellSetType; // Create the input uniform cell set vtkm::cont::DataSet dataSet = MakeTestDataSet().Make3DRectilinearDataSet0(); CellSetType cellSet; dataSet.GetCellSet(0).CopyTo(cellSet); // RangeId3 and subsample vtkm::RangeId3 range(0, 2, 0, 2, 0, 2); vtkm::Id3 sample(1, 1, 1); bool includeBoundary = false; // Extract subset vtkm::worklet::ExtractStructured worklet; auto outCellSet = worklet.Run(cellSet, range, sample, includeBoundary, DeviceAdapter()); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfPoints(), 8), "Wrong result for ExtractStructured worklet"); VTKM_TEST_ASSERT(test_equal(outCellSet.GetNumberOfCells(), 1), "Wrong result for ExtractStructured worklet"); } void operator()() const { TestUniform2D(); TestUniform3D(); TestUniform3D1(); TestRectilinear2D(); TestRectilinear3D(); } }; int UnitTestExtractStructured(int, char* []) { return vtkm::cont::testing::Testing::Run( TestingExtractStructured<VTKM_DEFAULT_DEVICE_ADAPTER_TAG>()); }
40.417722
92
0.681073
[ "3d" ]
b896050bed8efa75140adc01384801090feb28b9
5,396
cpp
C++
java/src/main/native/jni_util.cpp
farruhnet/AmazonDeepEngine
f64044d1e467333d0c9bb0643f0edf75328c503b
[ "Apache-2.0" ]
3,924
2016-05-10T22:40:39.000Z
2017-05-02T17:54:20.000Z
java/src/main/native/jni_util.cpp
saminfante/amazon-dsstne
f64044d1e467333d0c9bb0643f0edf75328c503b
[ "Apache-2.0" ]
88
2016-05-11T05:11:45.000Z
2017-04-24T02:34:20.000Z
java/src/main/native/jni_util.cpp
saminfante/amazon-dsstne
f64044d1e467333d0c9bb0643f0edf75328c503b
[ "Apache-2.0" ]
633
2016-05-10T23:07:33.000Z
2017-05-02T11:33:50.000Z
/* * Copyright 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. * */ #include <cstdio> #include <map> #include <iostream> #include <string> #include <sstream> #include "jni_util.h" namespace { const std::string CONSTRUCTOR_METHOD_NAME = "<init>"; } // namespace namespace dsstne { namespace jni { /* exceptions */ const std::string RuntimeException = "java/lang/RuntimeException"; const std::string NullPointerException = "java/lang/NullPointerException"; const std::string IllegalStateException = "java/lang/IllegalStateException"; const std::string IllegalArgumentException = "java/lang/IllegalArgumentException"; const std::string ClassNotFoundException = "java/lang/ClassNotFoundException"; const std::string NoSuchMethodException = "java/lang/NoSuchMethodException"; const std::string FileNotFoundException = "java/io/FileNotFoundException"; const std::string UnsupportedOperationException = "java/lang/UnsupportedOperationException"; /* collections */ const std::string ArrayList = "java/util/ArrayList"; /* java types */ const std::string String = "java/lang/String"; /* methods */ const std::string NO_ARGS_CONSTRUCTOR = "()V"; void deleteReferences(JNIEnv *env, References &refs) { for (auto &entry : refs.classGlobalRefs) { env->DeleteGlobalRef(entry.second); } refs.classGlobalRefs.clear(); } jclass References::getClassGlobalRef(const std::string &className) const { return classGlobalRefs.at(className); } bool References::containsClassGlobalRef(const std::string &className) const { return classGlobalRefs.find(className) != classGlobalRefs.end(); } void References::putClassGlobalRef(const std::string &className, jclass classRef) { classGlobalRefs[className] = classRef; } void throwJavaException(JNIEnv* env, const std::string &exceptionType, const char *fmt, ...) { jclass exc = env->FindClass(exceptionType.c_str()); va_list args; va_start(args, fmt); static const size_t MAX_MSG_LEN = 1024; char buffer[MAX_MSG_LEN]; if (vsnprintf(buffer, MAX_MSG_LEN, fmt, args) >= 0) { env->ThrowNew(exc, buffer); } else { env->ThrowNew(exc, ""); } va_end(args); } /** * Finds the provided class by name and adds a global reference to it to References. Subsequent findMethodId * calls on the same class do not have to be added as a global reference since the global reference * to the class keeps the class from being unloaded and hence also the method/field references. * Once done with the class reference, the global reference must be explicitly deleted to prevent * memory leaks. */ jclass findClassGlobalRef(JNIEnv *env, References &refs, const std::string &className) { if (refs.containsClassGlobalRef(className)) { return refs.getClassGlobalRef(className); } // this returns a local ref, need to create a global ref from this jclass classLocalRef = env->FindClass(className.c_str()); jthrowable exc = env->ExceptionOccurred(); if (exc) { env->ExceptionDescribe(); exit(1); } if (classLocalRef == NULL) { throwJavaException(env, jni::ClassNotFoundException, "%s", className); } jclass classGlobalRef = (jclass) env->NewGlobalRef(classLocalRef); refs.putClassGlobalRef(className, classGlobalRef); env->DeleteLocalRef(classLocalRef); return classGlobalRef; } jmethodID findMethodId(JNIEnv *env, References &refs, const std::string &className, const std::string &methodName, const std::string &methodDescriptor) { jclass clazz = findClassGlobalRef(env, refs, className); jmethodID methodId = env->GetMethodID(clazz, methodName.c_str(), methodDescriptor.c_str()); jthrowable exc = env->ExceptionOccurred(); if (exc) { std::cerr << "Error finding method " << className << "#" << methodName << methodDescriptor << std::endl; env->ExceptionDescribe(); exit(1); } if (methodId == NULL) { throwJavaException(env, jni::NoSuchMethodException, "%s#%s%s", className, methodName, methodDescriptor); } return methodId; } jmethodID findConstructorId(JNIEnv *env, References &refs, const std::string &className, const std::string &methodDescriptor) { return findMethodId(env, refs, className, CONSTRUCTOR_METHOD_NAME, methodDescriptor); } jobject newObject(JNIEnv *env, const References &refs, const std::string &className, jmethodID jConstructor, ...) { jclass clazz = refs.getClassGlobalRef(className); va_list args; va_start(args, jConstructor); jobject obj = env->NewObjectV(clazz, jConstructor, args); va_end(args); jthrowable exc = env->ExceptionOccurred(); if (exc) { env->ExceptionDescribe(); exit(1); } if (obj == NULL) { throwJavaException(env, jni::RuntimeException, "Unable to create new object: %s#%s", className, CONSTRUCTOR_METHOD_NAME); } return obj; } } // namespace jni } // namsspace dsstne
32.70303
115
0.722758
[ "object" ]
b89aee7648df6c064731fab4593cae2020db83f7
4,115
cc
C++
src/graphics/render/QuadRender.cc
eddiehoyle/sevengine
4f5bd2b16b1179784c831ef8a0d57ccecee0a92e
[ "MIT" ]
1
2019-08-21T05:06:04.000Z
2019-08-21T05:06:04.000Z
src/graphics/render/QuadRender.cc
eddiehoyle/sevengine
4f5bd2b16b1179784c831ef8a0d57ccecee0a92e
[ "MIT" ]
null
null
null
src/graphics/render/QuadRender.cc
eddiehoyle/sevengine
4f5bd2b16b1179784c831ef8a0d57ccecee0a92e
[ "MIT" ]
null
null
null
// // Created by Eddie Hoyle on 28/01/17. // #include <iostream> #include "QuadRender.hh" void print( const Vertex& vertex ) { std::cerr << "Vertex(x=" << vertex.x << ", y=" << vertex.y << ", s=" << vertex.s << ", t=" << vertex.t << ")" << std::endl; } Quad::Quad( float width, float height ) { GLubyte r, g, b, a; r = 255; g = 255; b = 255; a = 255; bl.set( 0.0f, 0.0f, 0.0f, 0.0f, r, g, b, a ); br.set( width, 0.0f, 1, 0.0f, r, g, b, a ); tl.set( 0.0f, height, 0.0f, 1, r, g, b, a ); tr.set( width, height, 1, 1, r, g, b, a ); } void Quad::setMatrix( const glm::mat4& matrix ) { glm::vec4 posA( bl.x, bl.y, 0.0, 1.0 ); glm::vec4 posB( br.x, br.y, 0.0, 1.0 ); glm::vec4 posC( tl.x, tl.y, 0.0, 1.0 ); glm::vec4 posD( tr.x, tr.y, 0.0, 1.0 ); posA = matrix * posA; posB = matrix * posB; posC = matrix * posC; posD = matrix * posD; bl.x = posA.x; bl.y = posA.y; br.x = posB.x; br.y = posB.y; tl.x = posC.x; tl.y = posC.y; tr.x = posD.x; tr.y = posD.y; } void Quad::setUV( float sa, float sb, float ta, float tb ) { bl.s = sa; bl.t = ta; // bl.t = GLfloat( 1.0 ) - ta; // Invert Y br.s = sb; br.t = ta; // br.t = GLfloat( 1.0 ) - ta; // Invert Y tl.s = sa; tl.t = tb; // tl.t = GLfloat( 1.0 ) - tb; // Invert Y tr.s = sb; tr.t = tb; // tr.t = GLfloat( 1.0 ) - tb; // Invert Y } void Quad::setColor( GLubyte r, GLubyte g, GLubyte b, GLubyte a ) { bl.r = r; bl.g = g; bl.b = b; bl.a = a; br.r = r; br.g = g; br.b = b; br.a = a; tl.r = r; tl.g = g; tl.b = b; tl.a = a; tr.r = r; tr.g = g; tr.b = b; tr.a = a; } // ---------------------------------------------------------------------- QuadBuffer::QuadBuffer() : m_data(), m_elements(), m_vbo( 0 ), m_vao( 0 ) { } void QuadBuffer::add( const std::vector< Quad >& quads ) { std::vector< Quad >::const_iterator iter; for ( iter = quads.begin(); iter != quads.end(); iter++ ) { add( *iter ); } } void QuadBuffer::add( const Quad &quad ) { // Vertex array for this quad Vertex vertices[4] = { quad.bl, quad.tl, quad.br, quad.tr, }; // Element array for this quad GLuint index = ( GLuint )m_data.size(); GLuint elements[6] = { index, index + 1, index + 2, index + 2, index + 3, index + 1, }; // Copy these arrays into vertex and element vectors std::copy( vertices, vertices + 4, std::back_inserter( m_data ) ); std::copy( elements, elements + 6, std::back_inserter( m_elements ) ); } void QuadBuffer::bind() { glGenBuffers( 1, &m_vbo ); glGenBuffers( 1, &m_vao ); glBindBuffer( GL_ARRAY_BUFFER, m_vbo ); glBufferData( GL_ARRAY_BUFFER, m_data.size() * sizeof( Vertex ), &m_data[0], GL_STATIC_DRAW ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_vao ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_elements.size() * sizeof( GLuint ), &m_elements[0], GL_STATIC_DRAW ); } void QuadBuffer::clear() { glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); glDeleteBuffers( 1, &m_vbo ); glDeleteBuffers( 1, &m_vao ); m_data.clear(); m_elements.clear(); } const Vertices& QuadBuffer::getData() const { return m_data; } const Elements& QuadBuffer::getElements() const { return m_elements; } // ---------------------------------------------------------------------- // QuadRender::QuadRender() : m_buffer() { } QuadRender::QuadRender( const QuadBuffer& buffer ) : m_buffer( buffer ) { } void QuadRender::bind() { m_buffer.bind(); } void QuadRender::draw() { // Enable alpha glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); // Draw const GLsizei numElements = ( GLsizei )m_buffer.getElements().size(); glDrawElements( GL_TRIANGLES, numElements, GL_UNSIGNED_INT, 0 ); } void QuadRender::release() { // TODO }
20.994898
114
0.524423
[ "vector" ]
b89da7a93d521b06b0dcf7333e7806e120e394de
10,627
cpp
C++
examples/kafka-serdes-avro-console-producer.cpp
jhansonhpe/libserdes
0c30d483f3217fe2c4dc3eaafd295b87a081ed49
[ "Apache-2.0" ]
null
null
null
examples/kafka-serdes-avro-console-producer.cpp
jhansonhpe/libserdes
0c30d483f3217fe2c4dc3eaafd295b87a081ed49
[ "Apache-2.0" ]
null
null
null
examples/kafka-serdes-avro-console-producer.cpp
jhansonhpe/libserdes
0c30d483f3217fe2c4dc3eaafd295b87a081ed49
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2015 Confluent Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Example Kafka producer to show case integration with libserdes C++ API */ #include <iostream> #include <sstream> #include <string> #include <cstdlib> #include <cstring> #include <signal.h> #include <getopt.h> /* Typical include path is <libserdes/serdescpp.h> */ #include "../src-cpp/serdescpp-avro.h" #include <librdkafka/rdkafkacpp.h> #include <avro/Encoder.hh> #include <avro/Decoder.hh> #include <avro/Generic.hh> #include <avro/Specific.hh> #include <avro/Exception.hh> static bool run = true; static int verbosity = 2; #define FATAL(reason...) do { \ std::cerr << "% FATAL: " << reason << std::endl; \ exit(1); \ } while (0) class MyDeliveryReportCb : public RdKafka::DeliveryReportCb { public: void dr_cb (RdKafka::Message &msg) { switch (msg.err()) { case RdKafka::ERR_NO_ERROR: if (verbosity > 2) std::cerr << "% Message produced (offset " << msg.offset() << ")" << std::endl; break; default: std::cerr << "% Message delivery failed: " << msg.errstr() << std::endl; } } }; /** * Convert JSON to Avro Datum. * * Returns 0 on success or -1 on failure. */ static int json2avro (Serdes::Schema *schema, const std::string &json, avro::GenericDatum **datump) { avro::ValidSchema *avro_schema = schema->object(); /* Input stream from json string */ std::istringstream iss(json); auto json_is = avro::istreamInputStream(iss); /* JSON decoder */ avro::DecoderPtr json_decoder = avro::jsonDecoder(*avro_schema); avro::GenericDatum *datum = new avro::GenericDatum(*avro_schema); try { /* Decode JSON to Avro datum */ json_decoder->init(*json_is); avro::decode(*json_decoder, *datum); } catch (const avro::Exception &e) { std::cerr << "% JSON to Avro transformation failed: " << e.what() << std::endl; return -1; } *datump = datum; return 0; } static __attribute__((noreturn)) void usage (const std::string me) { std::cerr << "Usage: " << me << " [options]\n" "Produces Avro encoded messages to Kafka from JSON objects " "read from stdin (one per line)\n" "\n" "Options:\n" " -b <brokers..> Kafka broker(s)\n" " -t <topic> Kafka topic to produce to\n" " -p <partition> Kafka partition (defaults to partitioner)\n" " -r <schreg-urls> Schema registry URL\n" " -s <schema-name> Schema/subject name\n" " -S <schema-def> Schema definition (JSON)\n" " -X kafka.topic.<n>=<v> Set RdKafka topic configuration\n" " -X kafka.<n>=<v> Set RdKafka global configuration\n" " -X <n>=<v> Set Serdes configuration\n" " -v Increase verbosity\n" " -q Decrease verbosity\n" "\n" "\n" "Examples:\n" " # Register schema and produce messages:\n" " " << me << " -b mybroker -t mytopic -s my_schema -S \"$(cat schema.json)\"\n" "\n" " # Use existing schema:\n" " " << me << " -b mybroker -t mytopic -s my_schema\n" "\n"; exit(1); } static void sig_term (int sig) { run = false; } int main (int argc, char **argv) { std::string errstr; std::string schema_name; std::string schema_def; std::string topic; int partition = -1; /* Controlled termination */ struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = sig_term; sigaction(SIGINT, &sa, NULL); sigaction(SIGTERM, &sa, NULL); /* Create serdes configuration object. * Configuration passed through -X prop=val will be set on this object, * which is later passed to the serdes handle creator. */ Serdes::Conf *sconf = Serdes::Conf::create(); /* Default URL */ if (sconf->set("schema.registry.url", "http://localhost:8081", errstr)) FATAL("Conf failed: " << errstr); /* Default framing CP1 */ if (sconf->set("serializer.framing", "cp1", errstr)) FATAL("Conf failed: " << errstr); /* Create rdkafka configuration object. * Configured passed through -X kafka.prop=val will be set on this object. */ RdKafka::Conf *kconf = RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL); /* Create rdkafka default topic configuration object. * Configuration passed through -X kafka.topic.prop=val will be set .. */ RdKafka::Conf *tconf = RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC); /* Command line argument parsing */ int opt; while ((opt = getopt(argc, argv, "b:t:p:g:r:s:S:X:vq")) != -1) { switch (opt) { case 'b': if (kconf->set("bootstrap.servers", optarg, errstr) != RdKafka::Conf::CONF_OK) FATAL(errstr); break; case 't': topic = optarg; break; case 'p': partition = std::atoi(optarg); break; case 'r': if (sconf->set("schema.registry.url", optarg, errstr) != SERDES_ERR_OK) FATAL("Failed to set registry.url: " << errstr); break; case 's': schema_name = optarg; break; case 'S': schema_def = optarg; break; case 'X': { char *t = strchr(optarg, '='); if (!t) FATAL("Expected -X property=value"); *t = '\0'; std::string name = optarg; std::string val = t+1; if (!strncmp(name.c_str(), "kafka.topic.", 12)) { RdKafka::Conf::ConfResult kres; kres = tconf->set(name.substr(12), val, errstr); if (kres == RdKafka::Conf::CONF_INVALID) FATAL(errstr); else if (kres == RdKafka::Conf::CONF_OK) break; /* Unknown property, fall through. */ } if (!strncmp(name.c_str(), "kafka.", 6)) { RdKafka::Conf::ConfResult kres; kres = kconf->set(name.substr(6), val, errstr); if (kres == RdKafka::Conf::CONF_INVALID) FATAL(errstr); else if (kres == RdKafka::Conf::CONF_OK) break; /* Unknown property, fall through. */ } /* Serdes config */ Serdes::ErrorCode err = sconf->set(name, val, errstr); if (err == SERDES_ERR_OK) break; FATAL(errstr); } break; case 'v': verbosity++; break; case 'q': verbosity--; break; default: std::cerr << "% Unknown option -" << (char)opt << std::endl; usage(argv[0]); } } if (schema_name.empty()) { std::cerr << "% Missing argument -s <schema-name>" << std::endl; usage(argv[0]); } /* Create Avro Serdes handle */ Serdes::Avro *serdes = Serdes::Avro::create(sconf, errstr); if (!serdes) FATAL("Failed to create Serdes handle: " << errstr); /** * Set up schema (either by getting existing or adding/updating) */ int schema_id = -1; Serdes::Schema *schema; /* If schema name is an integer treat it as schema id. */ if (!schema_name.empty() && schema_name.find_first_not_of("0123456789") == std::string::npos) { schema_id = atoi(schema_name.c_str()); schema_name.clear(); } if (schema_def.empty()) { /* Query schema registry */ std::cout << "% Query schema: by name \"" << schema_name << "\" or id " << schema_id << std::endl; if (!schema_name.empty()) schema = Serdes::Schema::get(serdes, schema_name, errstr); else if (schema_id != -1) schema = Serdes::Schema::get(serdes, schema_id, errstr); else FATAL("Expected schema -s <id> or -s <name>"); if (!schema) FATAL("Failed to get schema: " << errstr); std::cout << "% Schema \"" << schema->name() << "\" id " << schema->id() << ": " << schema->definition() << std::endl; } else { /* Register new schema */ std::cout << "% Register new schema: " << schema_name << ": " << schema_def << std::endl; schema = Serdes::Schema::add(serdes, schema_name, schema_def, errstr); if (!schema) FATAL("Failed to register schema " << schema_name << ": " << errstr); std::cout << "% Registered schema " << schema->name() << " with id " << schema->id() << std::endl; } if (topic.empty()) exit(0); /* Set up a delivery report callback to track delivery status on a * per message basis */ MyDeliveryReportCb dr_cb; if (kconf->set("dr_cb", &dr_cb, errstr) != RdKafka::Conf::CONF_OK) FATAL(errstr); /* Create Kafka producer */ RdKafka::Producer *producer = RdKafka::Producer::create(kconf, errstr); if (!producer) FATAL(errstr); delete kconf; /* Create topic object */ RdKafka::Topic *ktopic = RdKafka::Topic::create(producer, topic, tconf, errstr); if (!ktopic) FATAL(errstr); delete tconf; /* * Read JSON from stdin, convert to Avro datum, serialize and produce */ for (std::string line; run && std::getline(std::cin, line);) { avro::GenericDatum *datum = NULL; std::vector<char> out; /* Convert JSON to Avro object */ if (json2avro(schema, line, &datum) == -1) continue; /* Serialize Avro */ if (serdes->serialize(schema, datum, out, errstr) == -1) { std::cerr << "% Avro serialization failed: " << errstr << std::endl; delete datum; continue; } delete datum; /* Produce to Kafka */ RdKafka::ErrorCode kerr = producer->produce(ktopic, partition, &out, NULL, NULL); if (kerr != RdKafka::ERR_NO_ERROR) { std::cerr << "% Failed to produce message: " << RdKafka::err2str(kerr) << std::endl; break; } } /* Wait for all messages to be delivered */ while (producer->outq_len() > 0) producer->poll(100); delete producer; delete serdes; return 0; }
26.5675
86
0.570057
[ "object", "vector" ]
b8a1f59985434d911eaad62a7ac831df7d8ced48
1,468
cpp
C++
source/Library.Shared/VectorHelper.cpp
planetpratik/GamePort
d33ea826a8d849bf90fef39df2f05145b9fb4d9c
[ "MIT" ]
1
2020-12-30T16:14:02.000Z
2020-12-30T16:14:02.000Z
source/Library.Shared/VectorHelper.cpp
planetpratik/GamePort
d33ea826a8d849bf90fef39df2f05145b9fb4d9c
[ "MIT" ]
null
null
null
source/Library.Shared/VectorHelper.cpp
planetpratik/GamePort
d33ea826a8d849bf90fef39df2f05145b9fb4d9c
[ "MIT" ]
null
null
null
#include "pch.h" #include "VectorHelper.h" using namespace std; using namespace DirectX; namespace DX { const XMFLOAT2 Vector2Helper::Zero = XMFLOAT2(0.0f, 0.0f); const XMFLOAT2 Vector2Helper::One = XMFLOAT2(1.0f, 1.0f); string Vector2Helper::ToString(const XMFLOAT2& vector) { stringstream stream; stream << "{" << vector.x << ", " << vector.y << "}"; return stream.str(); } const XMFLOAT3 Vector3Helper::Zero = XMFLOAT3(0.0f, 0.0f, 0.0f); const XMFLOAT3 Vector3Helper::One = XMFLOAT3(1.0f, 1.0f, 1.0f); const XMFLOAT3 Vector3Helper::Forward = XMFLOAT3(0.0f, 0.0f, -1.0f); const XMFLOAT3 Vector3Helper::Backward = XMFLOAT3(0.0f, 0.0f, 1.0f); const XMFLOAT3 Vector3Helper::Up = XMFLOAT3(0.0f, 1.0f, 0.0f); const XMFLOAT3 Vector3Helper::Down = XMFLOAT3(0.0f, -1.0f, 0.0f); const XMFLOAT3 Vector3Helper::Right = XMFLOAT3(1.0f, 0.0f, 0.0f); const XMFLOAT3 Vector3Helper::Left = XMFLOAT3(-1.0f, 0.0f, 0.0f); string Vector3Helper::ToString(const XMFLOAT3& vector) { stringstream stream; stream << "{" << vector.x << ", " << vector.y << ", " << vector.z << "}"; return stream.str(); } const XMFLOAT4 Vector4Helper::Zero = XMFLOAT4(0.0f, 0.0f, 0.0f, 0.0f); const XMFLOAT4 Vector4Helper::One = XMFLOAT4(1.0f, 1.0f, 1.0f, 1.0f); string Vector4Helper::ToString(const XMFLOAT4& vector) { stringstream stream; stream << "{" << vector.x << ", " << vector.y << ", " << vector.z << ", " << vector.w << "}"; return stream.str(); } }
29.36
95
0.657357
[ "vector" ]
b8a2ef1356d641b4693438a7fec699cb54010b50
2,851
cc
C++
test/unit/bloom.cc
max101101/tarantool
65bb2fb811fefdce952c1111fb11eda337250aac
[ "BSD-2-Clause" ]
1
2019-01-02T02:16:22.000Z
2019-01-02T02:16:22.000Z
test/unit/bloom.cc
stek29/tarantool
cd9cc4c5057581970db4f8107c2a86ff0b24f4e2
[ "BSD-2-Clause" ]
null
null
null
test/unit/bloom.cc
stek29/tarantool
cd9cc4c5057581970db4f8107c2a86ff0b24f4e2
[ "BSD-2-Clause" ]
1
2020-04-06T18:37:57.000Z
2020-04-06T18:37:57.000Z
#include "salad/bloom.h" #include <unordered_set> #include <vector> #include <iostream> using namespace std; uint32_t h(uint32_t i) { return i * 2654435761; } void simple_test() { cout << "*** " << __func__ << " ***" << endl; struct quota q; quota_init(&q, 100500); srand(time(0)); uint32_t error_count = 0; uint32_t fp_rate_too_big = 0; for (double p = 0.001; p < 0.5; p *= 1.3) { uint64_t tests = 0; uint64_t false_positive = 0; for (uint32_t count = 1000; count <= 10000; count *= 2) { struct bloom bloom; bloom_create(&bloom, count, p, &q); unordered_set<uint32_t> check; for (uint32_t i = 0; i < count; i++) { uint32_t val = rand() % (count * 10); check.insert(val); bloom_add(&bloom, h(val)); } for (uint32_t i = 0; i < count * 10; i++) { bool has = check.find(i) != check.end(); bool bloom_possible = bloom_maybe_has(&bloom, h(i)); tests++; if (has && !bloom_possible) error_count++; if (!has && bloom_possible) false_positive++; } bloom_destroy(&bloom, &q); } double fp_rate = (double)false_positive / tests; if (fp_rate > p + 0.001) fp_rate_too_big++; } cout << "error_count = " << error_count << endl; cout << "fp_rate_too_big = " << fp_rate_too_big << endl; cout << "memory after destruction = " << quota_used(&q) << endl << endl; } void store_load_test() { cout << "*** " << __func__ << " ***" << endl; struct quota q; quota_init(&q, 100500); srand(time(0)); uint32_t error_count = 0; uint32_t fp_rate_too_big = 0; for (double p = 0.01; p < 0.5; p *= 1.5) { uint64_t tests = 0; uint64_t false_positive = 0; for (uint32_t count = 300; count <= 3000; count *= 10) { struct bloom bloom; bloom_create(&bloom, count, p, &q); unordered_set<uint32_t> check; for (uint32_t i = 0; i < count; i++) { uint32_t val = rand() % (count * 10); check.insert(val); bloom_add(&bloom, h(val)); } struct bloom test = bloom; char *buf = (char *)malloc(bloom_store_size(&bloom)); bloom_store(&bloom, buf); bloom_destroy(&bloom, &q); memset(&bloom, '#', sizeof(bloom)); bloom_load_table(&test, buf, &q); free(buf); for (uint32_t i = 0; i < count * 10; i++) { bool has = check.find(i) != check.end(); bool bloom_possible = bloom_maybe_has(&test, h(i)); tests++; if (has && !bloom_possible) error_count++; if (!has && bloom_possible) false_positive++; } bloom_destroy(&test, &q); } double fp_rate = (double)false_positive / tests; double excess = fp_rate / p; if (fp_rate > p + 0.001) fp_rate_too_big++; } cout << "error_count = " << error_count << endl; cout << "fp_rate_too_big = " << fp_rate_too_big << endl; cout << "memory after destruction = " << quota_used(&q) << endl << endl; } int main(void) { simple_test(); store_load_test(); }
25.684685
73
0.605402
[ "vector" ]
b8a6c11e55af31cf236fbc6d290dd81117992c03
1,871
cpp
C++
foundation/cpp/1_basics_of_programming/4_2d_arrays/2.cpp
vikaskbm/pepcoding
fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1
[ "MIT" ]
2
2021-03-16T08:56:46.000Z
2021-03-17T05:37:21.000Z
foundation/cpp/1_basics_of_programming/4_2d_arrays/2.cpp
vikaskbm/pepcoding
fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1
[ "MIT" ]
null
null
null
foundation/cpp/1_basics_of_programming/4_2d_arrays/2.cpp
vikaskbm/pepcoding
fb39b6dd62f4e5b76f75e12f2b222e2adb4854c1
[ "MIT" ]
null
null
null
// Matrix Multiplication // 1. You are given a number n1, representing the number of rows of 1st matrix. // 2. You are given a number m1, representing the number of columns of 1st matrix. // 3. You are given n1*m1 numbers, representing elements of 2d array a1. // 4. You are given a number n2, representing the number of rows of 2nd matrix. // 5. You are given a number m2, representing the number of columns of 2nd matrix. // 6. You are given n2*m2 numbers, representing elements of 2d array a2. // 7. If the two arrays representing two matrices of dimensions n1 * m1 and n2 * m2 can be multiplied, display the contents of prd array as specified in output Format. // 8. If the two arrays can't be multiplied, print "Invalid input". // n1=2 // m1=3 // 10 // 0 // 0 // 0 // 20 // 0 // n2=3 // m2=4 // 1 // 0 // 1 // 0 // 0 // 1 // 1 // 2 // 1 // 1 // 0 // 0 // 10 0 10 0 // 0 20 20 40 #include<iostream> #include<vector> using namespace std; void matrix_multiplication(vector<vector<int>> a,int n1,int m1, vector<vector<int>> b,int n2,int m2) { vector<vector<int>> c(n1, vector<int> (m2, 0)); for(int i=0; i<n1; i++) for(int j=0; j<m2; j++) for(int k=0; k<n2; k++) c[i][j] += a[i][k] * b[k][j]; for(int i=0; i<n1; i++){ for(int j=0; j<m2; j++) cout<<c[i][j] << " "; cout<<endl; } } int main() { int n1, n2, m1, m2; cin>>n1>>m1; vector<vector<int>> a(n1, vector<int>(m1,0)); for(int i=0; i<n1; i++) for(int j=0; j<m1; j++) cin>>a[i][j]; cin>>n2>>m2; vector<vector<int>> b(n2, vector<int>(m2,0)); for(int i=0; i<n2; i++) for(int j=0; j<m2; j++) cin>>b[i][j]; if(n2 != m1){ cout<<"Invalid input" << endl; } else{ matrix_multiplication(a, n1, m1, b, n2, m2); } }
23.098765
167
0.556387
[ "vector" ]
b8a8d52a37e2503f6322b46f1d01426a43b23174
3,511
cpp
C++
src/CGnuPlotCircle.cpp
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
null
null
null
src/CGnuPlotCircle.cpp
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
null
null
null
src/CGnuPlotCircle.cpp
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
1
2019-04-01T13:08:45.000Z
2019-04-01T13:08:45.000Z
#include <CGnuPlotCircle.h> #include <CGnuPlotRenderer.h> #include <CGnuPlotGroup.h> CGnuPlotCircle:: CGnuPlotCircle(CGnuPlotGroup *group) : CGnuPlotGroupAnnotation(group) { } CGnuPlotCircle * CGnuPlotCircle:: setData(const CGnuPlotCircle *circle) { (void) CGnuPlotGroupAnnotation::setData(circle); p_ = circle->p_; r_ = circle->r_; arcStart_ = circle->arcStart_; arcEnd_ = circle->arcEnd_; fs_ = circle->fs_; lw_ = circle->lw_; return this; } void CGnuPlotCircle:: initClip() { clip_ = ! p_.isScreen(); } void CGnuPlotCircle:: draw(CGnuPlotRenderer *renderer) const { bool highlighted = (isHighlighted() || isSelected()); if (isClip()) renderer->setClip(group_->getClip()); else renderer->resetClip(); center_ = this->getCenter().getPoint2D(renderer); // TODO: always round xr_ = this->getRadius().getXDistance(renderer); yr_ = this->getRadius().getYDistance(renderer); double a1 = arcStart_.getValue(0); double a2 = arcEnd_ .getValue(360); if (this->getFillColor().isRGB()) { CRGBA fc = this->getFillColor().color(); if (highlighted) { fc = fc.getLightRGBA(); } if (arcStart_.isValid() || arcEnd_.isValid()) renderer->fillPieSlice(center_, 0, xr_, a1, a2, fc); else renderer->fillClippedEllipse(center_, xr_, yr_, 0, fc); } c_ = this->getStrokeColor().getValue(CRGBA(0,0,0)); CRGBA c = c_; double lw = this->getLineWidth().getValue(1); if (highlighted) { c = CRGBA(1,0,0); lw = 2; } if (arcStart_.isValid() || arcEnd_.isValid()) renderer->drawPieSlice(center_, 0, xr_, a1, a2, true, c, lw, dash_); else renderer->drawClippedEllipse(center_, xr_, yr_, 0, c, lw, dash_); bbox_ = CBBox2D(center_.x - xr_, center_.y - yr_, center_.x + xr_, center_.y + yr_); } bool CGnuPlotCircle:: inside(const CGnuPlotMouseEvent &mouseEvent) const { const CPoint2D &p = mouseEvent.window(); double x = p.x - center_.x; double y = p.y - center_.y; double x2 = x*x; double y2 = y*y; double xr2 = xr_*xr_; double yr2 = yr_*yr_; double f = x2/xr2 + y2/yr2 - 2; if (f > 0) return false; if (arcStart_.isValid() || arcEnd_.isValid()) { // check angle double a = CAngle::Rad2Deg(atan2(y, x)); while (a < 0) a += 360.0; double angle1 = arcStart_.getValue( 0); while (angle1 < 0) angle1 += 360.0; double angle2 = arcEnd_ .getValue(360); while (angle2 < 0) angle2 += 360.0; if (angle1 > angle2) { // crosses zero if (a >= 0 && a <= angle2) return true; if (a <= 360 && a >= angle1) return true; } else { if (a >= angle1 && a <= angle2) return true; } return false; } else return true; } CGnuPlotTipData CGnuPlotCircle:: tip() const { CGnuPlotTipData tip; tip.setXStr(CStrUtil::strprintf("%g, %g", center_.x, center_.y)); tip.setYStr(CStrUtil::strprintf("%g, %g", xr_, yr_)); tip.setBorderColor(c_); tip.setXColor(c_); tip.setBBox(bbox_); return tip; } void CGnuPlotCircle:: setBBox(const CBBox2D &bbox) { p_ = bbox.getCenter(); r_ = bbox.getWidth ()/2; } void CGnuPlotCircle:: print(std::ostream &os) const { os << " circle"; os << " center " << p_; os << " size " << r_; os << " " << CStrUniqueMatch::valueToString<CGnuPlotTypes::DrawLayer>(layer_); // clip //os << " lw " << lw_.getValue(1.0); // dashtype solid fc bgnd " os << " fillstyle " << fs_; //os << " lt " << lt_.getValue(-1); }
19.836158
86
0.615779
[ "solid" ]
b8a8f65080a7a461f5d1bd5767d8d53f100582d8
5,785
cpp
C++
libraries/networking/src/ThreadedAssignment.cpp
annabrewer/hifi
ba7ed321355253a4a3bb3af8175e1be5ed5f7769
[ "Apache-2.0" ]
1
2019-07-08T06:54:01.000Z
2019-07-08T06:54:01.000Z
libraries/networking/src/ThreadedAssignment.cpp
VRcentral/VRcentral
d6064b46cfd26af4090ba799db55941c7de21b90
[ "Apache-2.0" ]
null
null
null
libraries/networking/src/ThreadedAssignment.cpp
VRcentral/VRcentral
d6064b46cfd26af4090ba799db55941c7de21b90
[ "Apache-2.0" ]
null
null
null
// // ThreadedAssignment.cpp // libraries/shared/src // // Created by Stephen Birarda on 12/3/2013. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "ThreadedAssignment.h" #include <QtCore/QCoreApplication> #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> #include <QtCore/QThread> #include <QtCore/QTimer> #include <LogHandler.h> #include <shared/QtHelpers.h> #include <platform/Platform.h> #include "NetworkLogging.h" ThreadedAssignment::ThreadedAssignment(ReceivedMessage& message) : Assignment(message), _isFinished(false), _domainServerTimer(this), _statsTimer(this) { static const int STATS_TIMEOUT_MS = 1000; _statsTimer.setInterval(STATS_TIMEOUT_MS); // 1s, Qt::CoarseTimer acceptable connect(&_statsTimer, &QTimer::timeout, this, &ThreadedAssignment::sendStatsPacket); connect(&_domainServerTimer, &QTimer::timeout, this, &ThreadedAssignment::checkInWithDomainServerOrExit); _domainServerTimer.setInterval(DOMAIN_SERVER_CHECK_IN_MSECS); // 1s, Qt::CoarseTimer acceptable // if the NL tells us we got a DS response, clear our member variable of queued check-ins auto nodeList = DependencyManager::get<NodeList>(); connect(nodeList.data(), &NodeList::receivedDomainServerList, this, &ThreadedAssignment::clearQueuedCheckIns); platform::create(); if (!platform::enumeratePlatform()) { qCDebug(networking) << "Failed to enumerate platform."; } } ThreadedAssignment::~ThreadedAssignment() { stop(); platform::destroy(); } void ThreadedAssignment::setFinished(bool isFinished) { if (_isFinished != isFinished) { _isFinished = isFinished; if (_isFinished) { qCDebug(networking) << "ThreadedAssignment::setFinished(true) called - finishing up."; auto nodeList = DependencyManager::get<NodeList>(); auto& packetReceiver = nodeList->getPacketReceiver(); // we should de-register immediately for any of our packets packetReceiver.unregisterListener(this); // we should also tell the packet receiver to drop packets while we're cleaning up packetReceiver.setShouldDropPackets(true); // send a disconnect packet to the domain nodeList->getDomainHandler().disconnect("Finished"); // stop our owned timers _domainServerTimer.stop(); _statsTimer.stop(); // call our virtual aboutToFinish method - this gives the ThreadedAssignment subclass a chance to cleanup aboutToFinish(); emit finished(); } } } void ThreadedAssignment::commonInit(const QString& targetName, NodeType_t nodeType) { // change the logging target name while the assignment is running LogHandler::getInstance().setTargetName(targetName); auto nodeList = DependencyManager::get<NodeList>(); nodeList->setOwnerType(nodeType); // send a domain-server check in immediately and start the timer to fire them every DOMAIN_SERVER_CHECK_IN_MSECS checkInWithDomainServerOrExit(); _domainServerTimer.start(); // start sending stats packet once we connect to the domain connect(&nodeList->getDomainHandler(), &DomainHandler::connectedToDomain, &_statsTimer, static_cast<void (QTimer::*)()>(&QTimer::start)); // stop sending stats if we disconnect connect(&nodeList->getDomainHandler(), &DomainHandler::disconnectedFromDomain, &_statsTimer, &QTimer::stop); } void ThreadedAssignment::addPacketStatsAndSendStatsPacket(QJsonObject statsObject) { auto nodeList = DependencyManager::get<NodeList>(); #ifdef DEBUG_EVENT_QUEUE statsObject["nodelist_event_queue_size"] = ::hifi::qt::getEventQueueSize(nodeList->thread()); #endif QJsonObject ioStats; ioStats["inbound_kbps"] = nodeList->getInboundKbps(); ioStats["inbound_pps"] = nodeList->getInboundPPS(); ioStats["outbound_kbps"] = nodeList->getOutboundKbps(); ioStats["outbound_pps"] = nodeList->getOutboundPPS(); statsObject["io_stats"] = ioStats; QJsonObject assignmentStats; assignmentStats["numQueuedCheckIns"] = _numQueuedCheckIns; statsObject["assignmentStats"] = assignmentStats; nodeList->sendStatsToDomainServer(statsObject); } void ThreadedAssignment::sendStatsPacket() { QJsonObject statsObject; addPacketStatsAndSendStatsPacket(statsObject); } void ThreadedAssignment::checkInWithDomainServerOrExit() { // verify that the number of queued check-ins is not >= our max // the number of queued check-ins is cleared anytime we get a response from the domain-server if (_numQueuedCheckIns >= MAX_SILENT_DOMAIN_SERVER_CHECK_INS) { qCDebug(networking) << "At least" << MAX_SILENT_DOMAIN_SERVER_CHECK_INS << "have been queued without a response from domain-server" << "Stopping the current assignment"; stop(); } else { auto nodeList = DependencyManager::get<NodeList>(); // Call sendDomainServerCheckIn directly instead of putting it on // the event queue. Under high load, the event queue can back up // longer than the total timeout period and cause a restart nodeList->sendDomainServerCheckIn(); // increase the number of queued check ins _numQueuedCheckIns++; if (_numQueuedCheckIns > 1) { qCDebug(networking) << "Number of queued checkins = " << _numQueuedCheckIns; } } } void ThreadedAssignment::domainSettingsRequestFailed() { qCDebug(networking) << "Failed to retreive settings object from domain-server. Bailing on assignment."; stop(); }
36.15625
139
0.709594
[ "object" ]
b8a9499ca56fb38f810b782d07e35d3a9afedb38
28,541
cpp
C++
window_inventory.cpp
darkoppressor/huberts-island-adventure-mouse-o-war
9ff8d9e2c2b388bf762a0e463238794fb0233df8
[ "MIT" ]
null
null
null
window_inventory.cpp
darkoppressor/huberts-island-adventure-mouse-o-war
9ff8d9e2c2b388bf762a0e463238794fb0233df8
[ "MIT" ]
null
null
null
window_inventory.cpp
darkoppressor/huberts-island-adventure-mouse-o-war
9ff8d9e2c2b388bf762a0e463238794fb0233df8
[ "MIT" ]
null
null
null
/* Copyright (c) 2012-2013 Cheese and Bacon Games, LLC */ /* See the file docs/COPYING.txt for copying permission. */ #include "window_inventory.h" #include "world.h" #include "render.h" #include "collision.h" #include "quit.h" #include "button_events.h" #include "holidays.h" using namespace std; Window_Inventory::Window_Inventory(short get_x,short get_y,short get_w,short get_h,string get_title){ background_image=NULL; x=get_x; y=get_y; w=get_w; h=get_h; title=get_title; on=false; moving=false; mouse_offset_x=0; mouse_offset_y=0; //Slots: for(short slot_x=0;slot_x<10;slot_x++){ for(short slot_y=0;slot_y<10;slot_y++){ slots[slot_x][slot_y].x=3+36*slot_x; slots[slot_x][slot_y].y=39+36*slot_y; slots[slot_x][slot_y].slot=slot_x+slot_y*10; } } slot_w=32; slot_h=32; INVENTORY_MAX_SIZE=100; //Create the close button. create_button(w-23,5,"","X",&button_event_close_window,0,0,BUTTON_VISIBLE); } void Window_Inventory::toggle_on(){ on=!on; //If the window was just turned off, stop its movement and drop any dragged item. if(!on){ moving=false; //Whenever a window is closed, we unpause the game. player.toggle_pause(false); drop_dragged_item(); } //If the window was just turned on. else{ if(buttons.size()>1){ player.current_button=1; } else{ player.current_button=0; } window_manager.allow_button_sound=false; //Whenever a window is opened, we pause the game. player.toggle_pause(true); } } void Window_Inventory::turn_off(){ on=false; //The window was just turned off, so stop its movement and drop any dragged item. moving=false; //Whenever a window is closed, we unpause the game. player.toggle_pause(false); drop_dragged_item(); } void Window_Inventory::handle_input_states(){ if(on){ int mouse_x,mouse_y; main_window.get_mouse_state(&mouse_x,&mouse_y); //If the window is moving, center it on the mouse's current position - the offsets. if(moving){ if(player.mouse_allowed()){ x=mouse_x-mouse_offset_x; y=mouse_y-mouse_offset_y; if(x<0){ x=0; } if(y<0){ y=0; } if(x+w>main_window.SCREEN_WIDTH){ x=main_window.SCREEN_WIDTH-w; } if(y+h>main_window.SCREEN_HEIGHT){ y=main_window.SCREEN_HEIGHT-h; } } } else if(!moving){ //Check to see if the mouse is hovering over any of this window's buttons. for(int i=0;i<buttons.size();i++){ //For each button, reset its moused over state before anything else. //Remember whether or not the button was moused over before this reset. bool already_moused_over=buttons[i].reset_moused_over(); //If the mouse is hovering over this button. if(buttons[i].is_moused_over(mouse_x,mouse_y,x,y,i)){ //The button is now being moused over. buttons[i].mouse_over(already_moused_over); //Setup the button's tooltip. if(buttons[i].has_tooltip()){ tooltip.setup(buttons[i].return_tooltip_text(),mouse_x,mouse_y); } if(buttons[i].enabled){ player.current_button=i; } } } //Determine which slot the mouse is hovering over, if any. moused_slot m_slot=determine_moused_slot(mouse_x,mouse_y); short slot_hover=m_slot.slot; //If the mouse is currently hovering over a slot. if(slot_hover!=-1){ for(int i=0;i<player.inventory.size();i++){ if(player.inventory[i].slot==slot_hover){ msg=player.inventory[i].name; tooltip.setup(msg,mouse_x,mouse_y); } } } } } } void Window_Inventory::handle_input_events(){ if(on){ int mouse_x,mouse_y; main_window.get_mouse_state(&mouse_x,&mouse_y); switch(event.type){ case SDL_QUIT: quit_game(); break; case SDL_MOUSEBUTTONDOWN: if(event.button.button==SDL_BUTTON_LEFT){ bool button_clicked=false; //Look through all of the buttons. for(int i=0;i<buttons.size();i++){ //If this button is moused over, //it has been clicked down on. if(buttons[i].is_moused_over(mouse_x,mouse_y,x,y,-2)){ buttons[i].mouse_button_down(); //A button has just been clicked, so we keep that in mind. button_clicked=true; } } //If no buttons were just clicked and the title bar of the window is clicked. if(!button_clicked && collision_check(mouse_x,mouse_y,2,2,x,y,w,30)){ //Begin moving the window. moving=true; mouse_offset_x=mouse_x-x; mouse_offset_y=mouse_y-y; } //Begin dragging an item. else if(!button_clicked && player.dragged_item.size()==0 && collision_check(mouse_x,mouse_y,2,2,x,y,w,h)){ //Determine which slot was clicked, if any. moused_slot m_slot=determine_moused_slot(mouse_x,mouse_y); short slot_clicked=m_slot.slot; //If a slot was clicked. if(slot_clicked!=-1){ for(int i=0;i<player.inventory.size();i++){ if(player.inventory[i].slot==slot_clicked){ //Set the dragged item to this item. player.dragged_item.push_back(dragged_inventory_item()); player.dragged_item[0].type=player.inventory[i].type; player.dragged_item[0].slot=player.inventory[i].slot; player.dragged_item[0].name=player.inventory[i].name; player.dragged_item[0].offset_x=m_slot.offset_x; player.dragged_item[0].offset_y=m_slot.offset_y; //Set this item to slot -1, meaning it is being dragged and is not to be displayed in any inventory window slot. player.inventory[i].slot=-1; //Play the inventory grab sound. play_positional_sound(sound_system.inventory_grab); } } } } } break; case SDL_MOUSEBUTTONUP: if(event.button.button==SDL_BUTTON_LEFT){ //Stop moving the inventory window. moving=false; //Look through all of the buttons. for(int i=0;i<buttons.size();i++){ //If this button is moused over, //the mouse button has been released over it. if(buttons[i].is_moused_over(mouse_x,mouse_y,x,y,-2)){ buttons[i].mouse_button_up(this); buttons[i].reset_clicked(); } //Otherwise, the mouse was not released over this button. else{ buttons[i].reset_clicked(); } } //If we were dragging an item. if(player.dragged_item.size()>0){ //Determine which slot is being hovered over, if any. moused_slot m_slot=determine_moused_slot(mouse_x,mouse_y); short slot_hover=m_slot.slot; //If a slot is hovered over. if(slot_hover!=-1){ bool slot_occupied=false; for(int i=0;i<player.inventory.size();i++){ if(player.inventory[i].slot==slot_hover){ slot_occupied=true; break; } } //If the slot is empty. if(!slot_occupied){ //Find the dragged item (the item with a slot of -1). for(int i=0;i<player.inventory.size();i++){ //Ok, we've found the dragged item in the inventory. if(player.inventory[i].slot==-1){ //Set this item's slot to the hovered slot. player.inventory[i].slot=slot_hover; //Clear the dragged item vector. player.dragged_item.clear(); //Play the inventory drop sound. play_positional_sound(sound_system.inventory_drop); //Increment the items moved stat. player.stat_items_moved++; break; } } } //If the slot is occupied, trade items. else{ //Find the item currently occupying this slot. for(int i=0;i<player.inventory.size();i++){ //Ok, we've found the occupying item in the inventory. if(player.inventory[i].slot==slot_hover){ //Set this item's slot to the dragged item's old slot. player.inventory[i].slot=player.dragged_item[0].slot; break; } } //Find the dragged item (the item with a slot of -1). for(int i=0;i<player.inventory.size();i++){ //Ok, we've found the dragged item in the inventory. if(player.inventory[i].slot==-1){ //Set this item's slot to the hovered slot. player.inventory[i].slot=slot_hover; //Clear the dragged item vector. player.dragged_item.clear(); //Play the inventory trade sound. play_positional_sound(sound_system.inventory_trade); //Increment the items moved stat. player.stat_items_moved++; break; } } } } //If no slot is hovered over. else{ //Find the dragged item (the item with a slot of -1). for(int i=0;i<player.inventory.size();i++){ //Ok, we've found the dragged item in the inventory. if(player.inventory[i].slot==-1){ //Set the item's slot back to its original slot. player.inventory[i].slot=player.dragged_item[0].slot; //Clear the dragged item vector. player.dragged_item.clear(); //Play the inventory drop sound. play_positional_sound(sound_system.inventory_drop); break; } } } } } break; } } } void Window_Inventory::display_inventory_item(short type,short slot){ //If slot==-1, the item is not currently in any inventory window slot, and is instead being dragged. if(slot!=-1){ short slot_x,slot_y; slot_x=x; slot_y=y; if(slot>=0 && slot<=9){ slot_y+=39; } else if(slot>=10 && slot<=19){ slot_y+=39+36; slot-=10; } else if(slot>=20 && slot<=29){ slot_y+=39+36*2; slot-=20; } else if(slot>=30 && slot<=39){ slot_y+=39+36*3; slot-=30; } else if(slot>=40 && slot<=49){ slot_y+=39+36*4; slot-=40; } else if(slot>=50 && slot<=59){ slot_y+=39+36*5; slot-=50; } else if(slot>=60 && slot<=69){ slot_y+=39+36*6; slot-=60; } else if(slot>=70 && slot<=79){ slot_y+=39+36*7; slot-=70; } else if(slot>=80 && slot<=89){ slot_y+=39+36*8; slot-=80; } else if(slot>=90 && slot<=99){ slot_y+=39+36*9; slot-=90; } slot_x+=3+(36*slot); if(type==ITEM_SWIMMING_GEAR){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_swimming_gear[0]); } else if(type==ITEM_KEY_RED){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_red[0]); } else if(type==ITEM_KEY_BLUE){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_blue[0]); } else if(type==ITEM_KEY_GREEN){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_green[0]); } else if(type==ITEM_KEY_YELLOW){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_yellow[0]); } else if(type==ITEM_KEY_ORANGE){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_orange[0]); } else if(type==ITEM_KEY_PURPLE){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_purple[0]); } else if(type==ITEM_TOWEL){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_towel[0]); } else if(type==ITEM_KEY_GRAY){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_gray[0]); } else if(type==ITEM_KEY_BROWN){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_brown[0]); } else if(type==ITEM_KEY_BLACK){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_black[0]); } else if(type==ITEM_KEY_PINK){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_pink[0]); } else if(type==ITEM_KEY_CYAN){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_key_cyan[0]); } else if(type==ITEM_SINK){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_sink[0]); } else if(type==ITEM_SUIT_DEADLY_WATER){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_suit_deadly_water[0]); } else if(type==ITEM_SUIT_SHARP){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_suit_sharp[0]); } else if(type==ITEM_SUIT_BANANA){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_suit_banana[0]); } else if(type==ITEM_SHOT_HOMING){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_shot_homing[0]); } else if(type==ITEM_TRANSLATOR){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_translator[0]); } else if(type==ITEM_J_WING){ render_sprite(slot_x,slot_y,image.sprite_sheet_items,&sprites_item_j_wing[0]); } } } void Window_Inventory::display_dragged_item(){ //If there is a dragged item. if(player.dragged_item.size()>0){ int mouse_x,mouse_y; main_window.get_mouse_state(&mouse_x,&mouse_y); if(player.dragged_item[0].type==ITEM_SWIMMING_GEAR){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_swimming_gear[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_swimming_gear[0]); } else if(player.dragged_item[0].type==ITEM_KEY_RED){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_red[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_red[0]); } else if(player.dragged_item[0].type==ITEM_KEY_BLUE){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_blue[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_blue[0]); } else if(player.dragged_item[0].type==ITEM_KEY_GREEN){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_green[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_green[0]); } else if(player.dragged_item[0].type==ITEM_KEY_YELLOW){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_yellow[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_yellow[0]); } else if(player.dragged_item[0].type==ITEM_KEY_ORANGE){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_orange[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_orange[0]); } else if(player.dragged_item[0].type==ITEM_KEY_PURPLE){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_purple[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_purple[0]); } else if(player.dragged_item[0].type==ITEM_TOWEL){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_towel[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_towel[0]); } else if(player.dragged_item[0].type==ITEM_KEY_GRAY){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_gray[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_gray[0]); } else if(player.dragged_item[0].type==ITEM_KEY_BROWN){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_brown[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_brown[0]); } else if(player.dragged_item[0].type==ITEM_KEY_BLACK){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_black[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_black[0]); } else if(player.dragged_item[0].type==ITEM_KEY_PINK){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_pink[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_pink[0]); } else if(player.dragged_item[0].type==ITEM_KEY_CYAN){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_key_cyan[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_key_cyan[0]); } else if(player.dragged_item[0].type==ITEM_SINK){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_sink[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_sink[0]); } else if(player.dragged_item[0].type==ITEM_SUIT_DEADLY_WATER){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_suit_deadly_water[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_suit_deadly_water[0]); } else if(player.dragged_item[0].type==ITEM_SUIT_SHARP){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_suit_sharp[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_suit_sharp[0]); } else if(player.dragged_item[0].type==ITEM_SUIT_BANANA){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_suit_banana[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_suit_banana[0]); } else if(player.dragged_item[0].type==ITEM_SHOT_HOMING){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_shot_homing[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_shot_homing[0]); } else if(player.dragged_item[0].type==ITEM_TRANSLATOR){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_translator[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_translator[0]); } else if(player.dragged_item[0].type==ITEM_J_WING){ render_sprite(mouse_x-player.dragged_item[0].offset_x+2,mouse_y-player.dragged_item[0].offset_y+2,image.sprite_sheet_items,&sprites_item_j_wing[0],1.0,1.0,1.0,0.0,COLOR_BLACK); render_sprite(mouse_x-player.dragged_item[0].offset_x,mouse_y-player.dragged_item[0].offset_y,image.sprite_sheet_items,&sprites_item_j_wing[0]); } } } void Window_Inventory::drop_dragged_item(){ //If there is a dragged item. if(player.dragged_item.size()>0){ //Find the dragged item (the item with a slot of -1). for(int i=0;i<player.inventory.size();i++){ //Ok, we've found the dragged item in the inventory. if(player.inventory[i].slot==-1){ //Set the item's slot back to its original slot. player.inventory[i].slot=player.dragged_item[0].slot; //Clear the dragged item vector. player.dragged_item.clear(); //Play the inventory drop sound. play_positional_sound(sound_system.inventory_drop); break; } } } } moused_slot Window_Inventory::determine_moused_slot(int mouse_x,int mouse_y){ moused_slot m_slot; m_slot.slot=-1; m_slot.offset_x=0; m_slot.offset_y=0; for(short slot_x=0;slot_x<10;slot_x++){ for(short slot_y=0;slot_y<10;slot_y++){ if(collision_check(mouse_x,mouse_y,2,2,x+slots[slot_x][slot_y].x,y+slots[slot_x][slot_y].y,slot_w,slot_h)){ m_slot.slot=slots[slot_x][slot_y].slot; m_slot.offset_x=mouse_x-slots[slot_x][slot_y].x-x; m_slot.offset_y=mouse_y-slots[slot_x][slot_y].y-y; return m_slot; } } } //If no slot is being moused over. return m_slot; } void Window_Inventory::render(){ if(on){ //Render the border. render_rectangle(x,y,w,h,1.0,return_gui_color(holiday,0)); //Render the inventory slots. for(int int_x=0;int_x<10;int_x++){ for(int int_y=0;int_y<10;int_y++){ render_rectangle(x+3+int_x*36,y+39+int_y*36,32,32,1.0,return_gui_color(holiday,1)); } } //Render the title bar. render_rectangle(x+10,y+10,w-20,20,1.0,return_gui_color(holiday,2)); //Display the window's title. font.show(x+(w-(title.length()*12))/2+2,y+12+2,title,COLOR_BLACK,1.0); font.show(x+(w-(title.length()*12))/2,y+12,title,return_gui_color(holiday,3),1.0); //Show items. for(int i=0;i<player.inventory.size();i++){ display_inventory_item(player.inventory[i].type,player.inventory[i].slot); } //Render the buttons. for(int i=0;i<buttons.size();i++){ buttons[i].render(x,y,i); } //Show the dragged item, if there is one. display_dragged_item(); } }
47.175207
199
0.569497
[ "render", "vector" ]
b8afcfe0cb537493da05285cb44dde67fa32a5fb
10,314
cpp
C++
ohm/VoxelBlock.cpp
data61/ohm
1bd81bb3e8a5a400d8af91e39464c640c47d56af
[ "Zlib" ]
45
2020-06-09T23:26:47.000Z
2022-03-16T12:16:33.000Z
ohm/VoxelBlock.cpp
data61/ohm
1bd81bb3e8a5a400d8af91e39464c640c47d56af
[ "Zlib" ]
1
2022-01-10T05:50:36.000Z
2022-01-24T02:50:01.000Z
ohm/VoxelBlock.cpp
data61/ohm
1bd81bb3e8a5a400d8af91e39464c640c47d56af
[ "Zlib" ]
5
2021-02-25T15:08:46.000Z
2022-03-30T13:08:03.000Z
// Copyright (c) 2019 // Commonwealth Scientific and Industrial Research Organisation (CSIRO) // ABN 41 687 119 230 // // Author: Kazys Stepanas #include "VoxelBlock.h" #include "MapLayer.h" #include "VoxelBlockCompressionQueue.h" #include "private/OccupancyMapDetail.h" #include <zlib.h> #include <algorithm> #include <cstring> namespace ohm { namespace { const unsigned kDefaultBufferSize = 1024u; unsigned g_minimum_buffer_size = kDefaultBufferSize; int g_zlib_compression_level = Z_BEST_SPEED; int g_zlib_gzip_flag = 0; // Use 16 to enable GZip. const int kWindowBits = 14; const int kZLibMemLevel = 8; const int kCompressionStrategy = Z_DEFAULT_STRATEGY; const int kGZipCompressionFlag = 16; const unsigned kReleaseDelayMs = 500; /// When reserving compressed buffer space, device the uncompressed size by this factor. const unsigned kBufferReservationQutient = 10; } // namespace void VoxelBlock::getCompressionControls(CompressionControls *controls) { controls->minimum_buffer_size = g_minimum_buffer_size; switch (g_zlib_compression_level) { default: case Z_DEFAULT_COMPRESSION: controls->compression_level = kCompressBalanced; break; case Z_BEST_SPEED: controls->compression_level = kCompressFast; break; case Z_BEST_COMPRESSION: controls->compression_level = kCompressMax; break; } if (g_zlib_gzip_flag) { controls->compression_type = kCompressGZip; } else { controls->compression_type = kCompressDeflate; } } void VoxelBlock::setCompressionControls(const CompressionControls &controls) { g_minimum_buffer_size = (controls.minimum_buffer_size > 0) ? controls.minimum_buffer_size : g_minimum_buffer_size; switch (controls.compression_level) { default: case kCompressFast: g_zlib_compression_level = Z_BEST_SPEED; break; case kCompressBalanced: g_zlib_compression_level = Z_DEFAULT_COMPRESSION; break; case kCompressMax: g_zlib_compression_level = Z_BEST_COMPRESSION; break; } g_zlib_gzip_flag = (controls.compression_type == kCompressGZip) ? kGZipCompressionFlag : 0; } VoxelBlock::VoxelBlock(const OccupancyMapDetail *map, const MapLayer &layer) : map_(map) , layer_index_(layer.layerIndex()) , uncompressed_byte_size_(layer.layerByteSize(map->region_voxel_dimensions)) { initUncompressed(voxel_bytes_, layer); flags_ |= kFUncompressed; // Try add to compression process if the map uses compression. if ((map->flags & MapFlag::kCompressed) == MapFlag::kCompressed) { VoxelBlockCompressionQueue::instance().push(this); } } VoxelBlock::~VoxelBlock() = default; void VoxelBlock::destroy() { // Don't use scoped lock as we will delete this which would make releasing the lock invalid. access_guard_.lock(); if (flags_ & kFManagedForCompression) { // Currently queue. Mark for death. The compression queue will destroy it. flags_ |= kFMarkedForDeath; access_guard_.unlock(); } else { // Not managed for compression. Delete now. // fprintf(stderr, "0x%" PRIXPTR ", VoxelBlock::destroy()\n", (uintptr_t)this); delete this; } } void VoxelBlock::retain() { std::unique_lock<Mutex> guard(access_guard_); ++reference_count_; flags_ |= kFLocked; // Ensure block is lock to prevent compression. // Ensure uncompressed data are available. if (!(flags_ & kFUncompressed)) { std::vector<uint8_t> working_buffer; uncompressUnguarded(working_buffer); voxel_bytes_.swap(working_buffer); flags_ |= kFUncompressed; } } void VoxelBlock::release() { std::unique_lock<Mutex> guard(access_guard_); if (reference_count_ > 0) { --reference_count_; if (reference_count_ == 0) { // Unlock to allow compression. flags_ &= ~kFLocked; } } } #if 0 void VoxelBlock::compressInto(std::vector<uint8_t> &compression_buffer) { std::unique_lock<Mutex> guard(access_guard_); // Handle uninitialised buffer. We may not have initialised the buffer yet, but this call requires data to be // compressed such as when used for serialisation to disk. if (voxel_bytes_.empty()) { initUncompressed(voxel_bytes_, map_->layout.layer(layer_index_)); flags_ |= kFUncompressed; } compressUnguarded(compression_buffer); } #endif // 0 size_t VoxelBlock::compress() { std::vector<uint8_t> compression_buffer; return compressWithTemporaryBuffer(compression_buffer); } size_t VoxelBlock::compressWithTemporaryBuffer(std::vector<uint8_t> &compression_buffer) { std::unique_lock<Mutex> guard(access_guard_); if (!reference_count_ && !(flags_ & kFLocked)) { // Handle uninitialised buffer. We may not have initialised the buffer yet, but this call requires data to be // compressed such as when used for serialisation to disk. if (voxel_bytes_.empty()) { initUncompressed(voxel_bytes_, map_->layout.layer(layer_index_)); flags_ |= kFUncompressed; } compressUnguarded(compression_buffer); setCompressedBytesUnguarded(compression_buffer); return compression_buffer.size(); } return 0; } void VoxelBlock::updateLayerIndex(unsigned layer_index) { std::unique_lock<Mutex> guard(access_guard_); layer_index_ = layer_index; } bool VoxelBlock::supportsCompression() const { return (map_->flags & MapFlag::kCompressed) == MapFlag::kCompressed; } bool VoxelBlock::compressUnguarded(std::vector<uint8_t> &compression_buffer) { if (flags_ & kFUncompressed) { int ret = Z_OK; z_stream stream; memset(&stream, 0u, sizeof(stream)); // NOLINTNEXTLINE(hicpp-signed-bitwise) deflateInit2(&stream, g_zlib_compression_level, Z_DEFLATED, kWindowBits | g_zlib_gzip_flag, kZLibMemLevel, kCompressionStrategy); stream.next_in = static_cast<Bytef *>(voxel_bytes_.data()); stream.avail_in = unsigned(voxel_bytes_.size()); compression_buffer.reserve( std::max(voxel_bytes_.size() / kBufferReservationQutient, static_cast<size_t>(g_minimum_buffer_size))); compression_buffer.resize(compression_buffer.capacity()); stream.avail_out = unsigned(compression_buffer.size()); stream.next_out = compression_buffer.data(); int flush_flag = Z_NO_FLUSH; do { ret = deflate(&stream, flush_flag); switch (ret) { case Z_OK: // Done with input data. Make sure we change to flushing. if (stream.avail_in == 0) { flush_flag = Z_FINISH; } // Check for insufficient output data before Z_STREAM_END. if (stream.avail_out == 0) { // Output buffer too small. const size_t bytes_so_far = compression_buffer.size(); compression_buffer.resize(2 * bytes_so_far); stream.avail_out = unsigned(compression_buffer.size() - bytes_so_far); stream.next_out = compression_buffer.data() + bytes_so_far; } break; case Z_STREAM_END: break; default: // Failed. deflateEnd(&stream); return false; } } while (stream.avail_in || ret != Z_STREAM_END); // Ensure flush. if (flush_flag != Z_FINISH) { deflate(&stream, Z_FINISH); } ret = deflateEnd(&stream); if (ret != Z_OK) { return false; } // Resize compressed buffer. compression_buffer.resize(compression_buffer.size() - stream.avail_out); } else { // Already compressed. Copy buffer. compression_buffer.resize(voxel_bytes_.size()); if (!voxel_bytes_.empty()) { memcpy(compression_buffer.data(), voxel_bytes_.data(), sizeof(*voxel_bytes_.data()) * voxel_bytes_.size()); } } return true; } bool VoxelBlock::uncompressUnguarded(std::vector<uint8_t> &expanded_buffer) { if (voxel_bytes_.empty()) { initUncompressed(voxel_bytes_, map_->layout.layer(layer_index_)); flags_ |= kFUncompressed; } if (flags_ & kFUncompressed) { // Simply copy existing bytes. expanded_buffer.resize(voxel_bytes_.size()); if (!voxel_bytes_.empty()) { memcpy(expanded_buffer.data(), voxel_bytes_.data(), sizeof(*voxel_bytes_.data()) * voxel_bytes_.size()); } return true; } expanded_buffer.resize(uncompressed_byte_size_); int ret = Z_OK; z_stream stream; memset(&stream, 0u, sizeof(stream)); inflateInit2(&stream, kWindowBits | g_zlib_gzip_flag); // NOLINT(hicpp-signed-bitwise) stream.avail_in = unsigned(voxel_bytes_.size()); stream.next_in = voxel_bytes_.data(); stream.avail_out = unsigned(expanded_buffer.size()); stream.next_out = static_cast<unsigned char *>(expanded_buffer.data()); int flush_flag = Z_NO_FLUSH; do { ret = inflate(&stream, flush_flag); switch (ret) { case Z_OK: // Check for insufficient output data on flush or before finishing input data. This is an error an error condition // as we know how large it should be. if (stream.avail_out == 0 && (flush_flag == Z_FINISH || stream.avail_in)) { // Failed. inflateEnd(&stream); return false; } // Transition to flush if there is no more input data. if (stream.avail_in == 0) { flush_flag = Z_FINISH; } break; case Z_STREAM_END: break; default: // Failed. inflateEnd(&stream); return false; } } while (stream.avail_in || ret != Z_STREAM_END); // Ensure flush. if (flush_flag != Z_FINISH) { inflate(&stream, Z_FINISH); } // Resize compressed buffer. expanded_buffer.resize(expanded_buffer.size() - stream.avail_out); inflateEnd(&stream); return true; } void VoxelBlock::initUncompressed(std::vector<uint8_t> &expanded_buffer, const MapLayer &layer) { expanded_buffer.resize(uncompressedByteSize()); layer.clear(expanded_buffer.data(), map_->region_voxel_dimensions); } void VoxelBlock::setCompressedBytesUnguarded(const std::vector<uint8_t> &compressed_voxels) { voxel_bytes_.resize(compressed_voxels.size()); if (!compressed_voxels.empty()) { memcpy(voxel_bytes_.data(), compressed_voxels.data(), sizeof(*compressed_voxels.data()) * compressed_voxels.size()); } voxel_bytes_.shrink_to_fit(); compressed_byte_size_ = voxel_bytes_.size(); // Clear uncompressed flag. flags_ &= ~(kFUncompressed); } } // namespace ohm
26.651163
120
0.699922
[ "vector" ]
b8b0d71020f5d08c39d5a3ab65c93c0349f872a3
2,676
hpp
C++
Extensions/ZilchShaders/ShaderIntrinsicTypes.hpp
jayrulez/ZeroCore
5da0e2537bc520c3b7ad461e676482382dd5a3e8
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
Extensions/ZilchShaders/ShaderIntrinsicTypes.hpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
null
null
null
Extensions/ZilchShaders/ShaderIntrinsicTypes.hpp
jodavis42/PhysicsSandbox
3119caaa77721041440cdc1b3cf96d4bd9e2d98b
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2015, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { class ZilchShaderIRType; } namespace Zilch { //------------------------------------------------------------------------ShaderIntrinsics /// Helper class that contains a bunch of intrinsic functions for spir-v (generated in the cpp). class ShaderIntrinsics { ZilchDeclareType(ShaderIntrinsics, TypeCopyMode::ReferenceType); }; //------------------------------------------------------------------------GeometryStreamUserData // Component data for input/output geometry stream types. Used for reflection purposes. struct GeometryStreamUserData { ZilchDeclareType(GeometryStreamUserData, TypeCopyMode::ReferenceType); public: GeometryStreamUserData() {} void Set(spv::ExecutionMode executionMode); // Is this stream an input or output? bool mInput; // What is the size of this stream (how many elements). Deduced from the execution mode. int mSize; // What execution mode does this stream use? (e.g. triangles, lines) spv::ExecutionMode mExecutionMode; }; //------------------------------------------------------------------------GeometryFragmentUserData // Component data added to a geometry fragment type. Needed to get the input/output stream // types which are only detected when walking the main function. struct GeometryFragmentUserData { ZilchDeclareType(GeometryFragmentUserData, TypeCopyMode::ReferenceType); GeometryFragmentUserData(); Zero::ZilchShaderIRType* GetInputVertexType(); Zero::ZilchShaderIRType* GetOutputVertexType(); Zero::ZilchShaderIRType* mInputStreamType; Zero::ZilchShaderIRType* mOutputStreamType; }; //------------------------------------------------------------------------ComputeFragmentUserData /// User data for a compute shader to know what data was parsed from the [Compute] attribute. struct ComputeFragmentUserData { ZilchDeclareType(ComputeFragmentUserData, TypeCopyMode::ReferenceType); ComputeFragmentUserData(); int mLocalSizeX; int mLocalSizeY; int mLocalSizeZ; }; //------------------------------------------------------------------------UnsignedInt /// This is a hack type used for binding instructions that require a unsigned int /// while dealing with zilch not actually having any unsigned types. class UnsignedInt { ZilchDeclareType(UnsignedInt, TypeCopyMode::ValueType); unsigned int mValue; }; }//namespace Zilch
33.45
99
0.606129
[ "geometry" ]
b8bb26acea8fe256f5fc64151b8c5cce2eb4120e
11,052
cpp
C++
s01e10_main.cpp
Michal-Fularz/PSIO_project_2021
49ee9fc65b4b9b64b4ec09da42bcb5593b789416
[ "MIT" ]
null
null
null
s01e10_main.cpp
Michal-Fularz/PSIO_project_2021
49ee9fc65b4b9b64b4ec09da42bcb5593b789416
[ "MIT" ]
null
null
null
s01e10_main.cpp
Michal-Fularz/PSIO_project_2021
49ee9fc65b4b9b64b4ec09da42bcb5593b789416
[ "MIT" ]
null
null
null
#define GL_SILENCE_DEPRECATION #include <iostream> #include <fstream> #include <sstream> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/OpenGL.hpp> #include <GL/glu.h> // Windows/Linux #include "planet.h" void draw_cube(double size) { double half_cube_size = size / 2.0; // bottom glBegin(GL_POLYGON); glVertex3d(-half_cube_size, half_cube_size, -half_cube_size); glVertex3d(half_cube_size, half_cube_size, -half_cube_size); glVertex3d(half_cube_size, -half_cube_size, -half_cube_size); glVertex3d(-half_cube_size, -half_cube_size, -half_cube_size); glEnd(); // top glColor3d(1.0, 0.0, 0.0); glBegin(GL_POLYGON); glVertex3d(-half_cube_size, half_cube_size, half_cube_size); glVertex3d(half_cube_size, half_cube_size, half_cube_size); glVertex3d(half_cube_size, -half_cube_size, half_cube_size); glVertex3d(-half_cube_size, -half_cube_size, half_cube_size); glEnd(); // left glColor3d(0.0, 1.0, 0.0); glBegin(GL_POLYGON); glVertex3d(-half_cube_size, -half_cube_size, half_cube_size); glVertex3d(-half_cube_size, half_cube_size, half_cube_size); glVertex3d(-half_cube_size, half_cube_size, -half_cube_size); glVertex3d(-half_cube_size, -half_cube_size, -half_cube_size); glEnd(); // right glColor3d(0.0, 0.0, 1.0); glBegin(GL_POLYGON); glVertex3d(half_cube_size, -half_cube_size, half_cube_size); glVertex3d(half_cube_size, half_cube_size, half_cube_size); glVertex3d(half_cube_size, half_cube_size, -half_cube_size); glVertex3d(half_cube_size, -half_cube_size, -half_cube_size); glEnd(); // front glColor3d(1.0, 1.0, 0.0); glBegin(GL_POLYGON); glVertex3d(-half_cube_size, -half_cube_size, half_cube_size); glVertex3d(half_cube_size, -half_cube_size, half_cube_size); glVertex3d(half_cube_size, -half_cube_size, -half_cube_size); glVertex3d(-half_cube_size, -half_cube_size, -half_cube_size); glEnd(); // back glColor3d(0.0, 1.0, 1.0); glBegin(GL_POLYGON); glVertex3d(-half_cube_size, half_cube_size, half_cube_size); glVertex3d(half_cube_size, half_cube_size, half_cube_size); glVertex3d(half_cube_size, half_cube_size, -half_cube_size); glVertex3d(-half_cube_size, half_cube_size, -half_cube_size); glEnd(); } void set_viewport(int width, int height) { const float ar = (float)width / (float)height; glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0); gluLookAt(0, -5, 5, 0, 0, 0, 0, 0, 1); // glMatrixMode(GL_MODELVIEW); // glLoadIdentity(); } void ex_1() { // create the window sf::Window window(sf::VideoMode(1024, 768), "SFML OpenGL Template", sf::Style::Default, sf::ContextSettings(32)); window.setVerticalSyncEnabled(true); // activate the window window.setActive(true); // set viewport according to current window size set_viewport(window.getSize().x, window.getSize().y); glClearColor(0, 0, 0, 1); glEnable(GL_DEPTH_TEST); glEnable(GL_SMOOTH); glShadeModel(GL_SMOOTH); // setup lights GLfloat light_position[] = { 2.0, 0.0, 2.0, 1.0 }; GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 }; GLfloat light_diffuse[] = { 0.8, 0.8, 0.8, 1.0 }; GLfloat light_specular[] = { 0.0, 0.0, 0.0, 1.0 }; glLightfv( GL_LIGHT0, GL_POSITION, light_position); glLightfv( GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv( GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv( GL_LIGHT0, GL_SPECULAR, light_specular); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); GLfloat global_ambient[] = {0.3, 0.3, 0.3, 0.1}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); glEnable(GL_NORMALIZE) ; // load resources, initialize the OpenGL states, ... // run the main loop bool running = true; sf::Clock clk; float camera_x = 0.0; float camera_z = 0.0; float camera_zoom = 0.0; while (running) { // EVENTS // handle events sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { // end the program running = false; } else if (event.type == sf::Event::Resized) { // adjust the viewport when the window is resized set_viewport(event.size.width, event.size.height); } else if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::W) { camera_z += 0.2; } else if (event.key.code == sf::Keyboard::S) { camera_z -= 0.2; } if (event.key.code == sf::Keyboard::A) { camera_x += 0.2; } else if (event.key.code == sf::Keyboard::D) { camera_x -= 0.2; } } else if (event.type == sf::Event::MouseWheelScrolled) { camera_zoom += event.mouseWheelScroll.delta; } } // LOGIC float rot = clk.getElapsedTime().asSeconds() * 90; // DISPLAY // clear the buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColorMaterial (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) ; glEnable (GL_COLOR_MATERIAL); // draw stuff glPushMatrix(); { std::cout << camera_zoom << std::endl; glScalef(1.0 + camera_zoom/100.0, 1.0 + camera_zoom/100.0, 1.0 + camera_zoom/100.0); glTranslatef(camera_x, 0.0, camera_z); glPushMatrix(); { glRotated(rot/10, 0.0, 0.0, 1.0); glTranslated(3.0, 3.0, 0.0); glScaled(0.5, 0.5, 0.5); glPushMatrix(); { // TODO // test functions below (glTranslated, glRotated, glColor3d) // what happens when you change their arguments? // does their order change the result? glTranslated(1.0, 0.0, 0.0); //glRotated(0, 1.0, 0.0, 0.0); //glRotated(rot, 0.0, 1.0, 0.0); glRotated(rot, 0.0, 0.0, 1.0); glScaled(0.5, 1.0, 0.25); draw_cube(1.0); } glPopMatrix(); glPushMatrix(); { glRotated(rot/3, 0.0, 0.0, 1.0); glTranslated(-2.0, 0.0, 0.0); glRotated(rot/2, 0.0, 1.0, 0.0); draw_cube(0.5); } glPopMatrix(); glPushMatrix(); { glRotated(rot/3, 1.0, 0.0, 0.0); draw_cube(0.3); } glPopMatrix(); } glPopMatrix(); glPushMatrix(); { draw_cube(2.0); } glPopMatrix(); } glPopMatrix(); // end the current frame (internally swaps the front and back buffers) window.display(); } } void ex_2() { sf::Window window(sf::VideoMode(1024, 768), "SFML OpenGL Template", sf::Style::Default, sf::ContextSettings(32)); window.setVerticalSyncEnabled(true); window.setActive(true); // set viewport according to current window size set_viewport(window.getSize().x, window.getSize().y); glClearColor(0, 0, 0, 1); glEnable(GL_DEPTH_TEST); glEnable(GL_SMOOTH); glShadeModel(GL_SMOOTH); // setup lights GLfloat light_position[] = { 2.0, 0.0, 2.0, 1.0 }; GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 }; GLfloat light_diffuse[] = { 0.8, 0.8, 0.8, 1.0 }; GLfloat light_specular[] = { 0.0, 0.0, 0.0, 1.0 }; glLightfv( GL_LIGHT0, GL_POSITION, light_position); glLightfv( GL_LIGHT0, GL_AMBIENT, light_ambient); glLightfv( GL_LIGHT0, GL_DIFFUSE, light_diffuse); glLightfv( GL_LIGHT0, GL_SPECULAR, light_specular); glEnable( GL_LIGHTING ); glEnable( GL_LIGHT0 ); GLfloat global_ambient[] = {0.3, 0.3, 0.3, 0.1}; glLightModelfv(GL_LIGHT_MODEL_AMBIENT, global_ambient); glEnable(GL_NORMALIZE) ; // load resources, initialize the OpenGL states, ... std::vector<Planet> objects; // objects.push_back(Planet(2.0, 0.0, 5.0, 0.0)); //double diameter = 1.0, double distance = 0.0, double spin_period = 0.0, double rotation_period = 0.0 // load planets std::fstream solar_system_file("./../s01e10/solar_system.txt"); if (!solar_system_file.is_open()) { std::cerr << "Could not open file" << std::endl; return; } std::string line; while (std::getline(solar_system_file, line)) { if (!line.empty() && line[0] != '#') { std::stringstream line_str(line); std::string name; double distance; double diameter; double spin_period; double orbit_period; double gravity; int number_of_moons; double r; double g; double b; line_str >> name >> distance >> diameter >> spin_period >> orbit_period >> gravity >> number_of_moons >> r >> g >> b; std::cout << name << " " << diameter << std::endl; objects.push_back(Planet(diameter, distance, spin_period, orbit_period)); objects.back().set_color(r/255.0, g/255.0, b/255.0); } } // run the main loop bool running = true; sf::Clock clk; while (running) { double delta_t = clk.getElapsedTime().asSeconds(); clk.restart(); // handle events sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { // end the program running = false; } else if (event.type == sf::Event::Resized) { // adjust the viewport when the window is resized set_viewport(event.size.width, event.size.height); } else if (event.type == sf::Event::MouseWheelScrolled) { std::cerr << event.mouseWheelScroll.delta <<std::endl; } } // clear the buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColorMaterial (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) ; glEnable (GL_COLOR_MATERIAL); // draw stuff glPushMatrix(); glScaled(1.0/1500, 1.0/1500, 1.0/1500); for (auto &p : objects) { p.step(delta_t); p.draw(); } glPopMatrix(); // end the current frame (internally swaps the front and back buffers) window.display(); } } int main() { std::cout << "Hello s01e09!" << std::endl; //ex_1(); ex_2(); return 0; }
30.530387
156
0.572023
[ "vector" ]
b8be23dd01a2b54df027e287b5fdad25135b42e1
1,387
cpp
C++
SPOJ/MARBLES.cpp
tapaswenipathak/Competitive-Programming
97bba0f2ccdf587df93244a027050489f0905480
[ "MIT" ]
2
2019-04-20T18:03:20.000Z
2019-08-17T21:20:47.000Z
CodeChef/MARBLES.cpp
tapaswenipathak/Competitive-Programming
97bba0f2ccdf587df93244a027050489f0905480
[ "MIT" ]
null
null
null
CodeChef/MARBLES.cpp
tapaswenipathak/Competitive-Programming
97bba0f2ccdf587df93244a027050489f0905480
[ "MIT" ]
1
2019-04-20T18:03:26.000Z
2019-04-20T18:03:26.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <cctype> // Input macros #define s(n) scanf("%d",&n) #define sc(n) scanf("%c",&n) #define sl(n) scanf("%lld",&n) #define sf(n) scanf("%lf",&n) #define ss(n) scanf("%s",n) #define st(n,m) scanf("%d %d",&n,&m) #define stl(n,m) scanf("%lld %lld",&n,&m) //Output Macros #define p(n) printf("%d",n) #define pl(n) printf("%lld",n) // Useful constants #define INF (int)1e9 #define EPS 1e-9 // Useful container manipulation / traversal macros #define forall(i,a,b) for(int i=a;i<b;++i) #define foreach(i,a,b) for(int i=a;i<=b;++i) using namespace std; int main() { int T; long long int n, k, res = 1, minval = 0; s(T); while (T--){ n = 0, k = 0, res = 1, minval = 0; stl(n,k); if (n == k){ printf("1\n"); continue; } n -= 1; minval = min((n - k + 1), (k - 1)); foreach(i,1,minval){ res *= n--; res /= i; } pl(res); printf("\n"); } return 0; }
24.333333
60
0.413843
[ "vector" ]
b8be39e0bb20dd0db8b9172f0a78f9d09eccefe0
4,551
cpp
C++
be/src/storage/rowset/segment_rewriter.cpp
hiliuxg/starrocks
04640294c794291e31c132bc6217cc62e71be17c
[ "Zlib", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
be/src/storage/rowset/segment_rewriter.cpp
hiliuxg/starrocks
04640294c794291e31c132bc6217cc62e71be17c
[ "Zlib", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
be/src/storage/rowset/segment_rewriter.cpp
hiliuxg/starrocks
04640294c794291e31c132bc6217cc62e71be17c
[ "Zlib", "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
// Copyright (c) 2021 Beijing Dingshi Zongheng Technology Co., Ltd. All rights reserved. #include "segment_rewriter.h" #include "fs/fs.h" #include "gen_cpp/segment.pb.h" #include "storage/chunk_helper.h" #include "storage/rowset/segment.h" #include "storage/rowset/segment_writer.h" #include "util/filesystem_util.h" #include "util/slice.h" namespace starrocks { SegmentRewriter::SegmentRewriter() {} SegmentRewriter::~SegmentRewriter() {} Status SegmentRewriter::rewrite(const std::string& src_path, const std::string& dest_path, const TabletSchema& tschema, std::vector<uint32_t>& column_ids, std::vector<std::unique_ptr<vectorized::Column>>& columns, size_t segment_id, const FooterPointerPB& partial_rowset_footer) { ASSIGN_OR_RETURN(auto fs, FileSystem::CreateSharedFromString(dest_path)); WritableFileOptions wopts{.sync_on_close = true, .mode = FileSystem::CREATE_OR_OPEN_WITH_TRUNCATE}; ASSIGN_OR_RETURN(auto wfile, fs->new_writable_file(wopts, dest_path)); ASSIGN_OR_RETURN(auto rfile, fs->new_random_access_file(src_path)); SegmentFooterPB footer; RETURN_IF_ERROR(Segment::parse_segment_footer(rfile.get(), &footer, nullptr, &partial_rowset_footer)); // keep the partial rowset footer in dest file // because be may be crash during update rowset meta uint64_t remaining = partial_rowset_footer.position() + partial_rowset_footer.size(); std::string read_buffer; raw::stl_string_resize_uninitialized(&read_buffer, 4096); uint64_t offset = 0; while (remaining > 0) { if (remaining < 4096) { raw::stl_string_resize_uninitialized(&read_buffer, remaining); } RETURN_IF_ERROR(rfile->read_at_fully(offset, read_buffer.data(), read_buffer.size())); RETURN_IF_ERROR(wfile->append(read_buffer)); offset += read_buffer.size(); remaining -= read_buffer.size(); } SegmentWriterOptions opts; opts.storage_format_version = config::storage_format_version; SegmentWriter writer(std::move(wfile), segment_id, &tschema, opts); RETURN_IF_ERROR(writer.init(column_ids, false, &footer)); auto schema = vectorized::ChunkHelper::convert_schema_to_format_v2(tschema, column_ids); auto chunk = vectorized::ChunkHelper::new_chunk(schema, columns[0]->size()); for (int i = 0; i < columns.size(); ++i) { chunk->get_column_by_index(i).reset(columns[i].release()); } uint64_t index_size = 0; uint64_t segment_file_size; RETURN_IF_ERROR(writer.append_chunk(*chunk)); RETURN_IF_ERROR(writer.finalize_columns(&index_size)); RETURN_IF_ERROR(writer.finalize_footer(&segment_file_size)); return Status::OK(); } Status SegmentRewriter::rewrite(const std::string& src_path, const TabletSchema& tschema, std::vector<uint32_t>& column_ids, std::vector<std::unique_ptr<vectorized::Column>>& columns, size_t segment_id, const FooterPointerPB& partial_rowset_footer) { ASSIGN_OR_RETURN(auto fs, FileSystem::CreateSharedFromString(src_path)); ASSIGN_OR_RETURN(auto read_file, fs->new_random_access_file(src_path)); SegmentFooterPB footer; RETURN_IF_ERROR(Segment::parse_segment_footer(read_file.get(), &footer, nullptr, &partial_rowset_footer)); int64_t trunc_len = partial_rowset_footer.position() + partial_rowset_footer.size(); RETURN_IF_ERROR(FileSystemUtil::resize_file(src_path, trunc_len)); WritableFileOptions fopts{.sync_on_close = true, .mode = FileSystem::MUST_EXIST}; ASSIGN_OR_RETURN(auto wfile, fs->new_writable_file(fopts, src_path)); SegmentWriterOptions opts; opts.storage_format_version = config::storage_format_version; SegmentWriter writer(std::move(wfile), segment_id, &tschema, opts); RETURN_IF_ERROR(writer.init(column_ids, false, &footer)); auto schema = vectorized::ChunkHelper::convert_schema_to_format_v2(tschema, column_ids); auto chunk = vectorized::ChunkHelper::new_chunk(schema, columns[0]->size()); for (int i = 0; i < columns.size(); ++i) { chunk->get_column_by_index(i).reset(columns[i].release()); } uint64_t index_size = 0; uint64_t segment_file_size; RETURN_IF_ERROR(writer.append_chunk(*chunk)); RETURN_IF_ERROR(writer.finalize_columns(&index_size)); RETURN_IF_ERROR(writer.finalize_footer(&segment_file_size)); return Status::OK(); } } // namespace starrocks
44.184466
119
0.712151
[ "vector" ]
b8bff766f21821a2d8bda261c1a3a8518d5e9728
3,694
cpp
C++
src/main.cpp
macneib/Discovery-Server
c499531422e671527f8676e3efba30015993b5d3
[ "Apache-2.0" ]
null
null
null
src/main.cpp
macneib/Discovery-Server
c499531422e671527f8676e3efba30015993b5d3
[ "Apache-2.0" ]
null
null
null
src/main.cpp
macneib/Discovery-Server
c499531422e671527f8676e3efba30015993b5d3
[ "Apache-2.0" ]
1
2021-06-02T11:16:26.000Z
2021-06-02T11:16:26.000Z
#include "log/DSLog.h" #include "version/config.h" #include <fastrtps/Domain.h> #include "DSManager.h" using namespace eprosima; using namespace fastrtps; using namespace rtps; using namespace discovery_server; std::pair<std::set<std::string>, std::string> validationCommandLineParser(int argc, char * argv[]); int main(int argc, char * argv[]) { // Initialize loging #if defined LOG_LEVEL_INFO Log::SetVerbosity(Log::Kind::Info); #elif defined LOG_LEVEL_WARN Log::SetVerbosity(Log::Kind::Warning); #elif defined LOG_LEVEL_ERROR Log::SetVerbosity(Log::Kind::Error); #endif Log::SetCategoryFilter( std::regex("(RTPS_PDPSERVER_TRIM)|(RTPS_PARTICIPANT)|(DISCOVERY_SERVER)" "|(SERVER_PDP_THREAD)|(CLIENT_PDP_THREAD)")); int return_code = 0; if (!(argc > 1)) { std::cout << "Usage: discovery-server [CONFIG_XML|SNAPSHOT_XML+ [-out output_filename]]" << std::endl; } else if (argc == 2) { std::string path_to_config = argv[1]; { DSManager manager(path_to_config); // Follow the config file instructions manager.runEvents(std::cin, std::cout); // maybe it's not a standalone test and validation should be procrastinated if (manager.shouldValidate()) { // Check the snapshots taken if (!manager.validateAllSnapshots()) { LOG_ERROR("Discovery Server error: several snapshots show info leakage"); return_code = -1; // report CTest the test fail } else { std::cout << manager.successMessage() << std::endl; } } } } else { auto arguments = validationCommandLineParser(argc, argv); DSManager manager(arguments.first, arguments.second); // Check the snapshots read if(manager.shouldValidate()) { if(!manager.validateAllSnapshots()) { LOG_ERROR("Discovery Server error: several snapshots show info leakage"); return_code = -1; // report CTest the test fail } else { std::cout << manager.successMessage() << std::endl; } } } Log::Flush(); Domain::stopAll(); return return_code; } // C++11 template deduction cannot directly map std::tolower in std::transform char toLower(const char & c) { return std::tolower(c); } std::pair<std::set<std::string>,std::string> validationCommandLineParser(int argc, char * argv[]) { using namespace std; // handle -out output_file_name scenario bool next_is_filename = false; string outfilename; string outflag("-out"); set<string> files; for(int i = 1; i < argc; ++i) { const char * argtext = argv[i]; // former argument was -out flag if(next_is_filename) { next_is_filename = false; outfilename = argtext; } else { // check if its a flag or a file string::size_type len = string::traits_type::length(argtext); string file(len, ' '); transform(argtext, argtext + len, file.begin(), toLower); if(outflag == file) { next_is_filename = true; } else { // kept the file files.emplace(argtext, len); } } } return std::make_pair(std::move(files),std::move(outfilename)); }
26.963504
110
0.55333
[ "transform" ]
b8c3556e0feb5ba4731d0d92f0e6465d1d45e758
4,775
cpp
C++
Modules/SceneSerializationBase/test/mitkVectorPropertySerializerTest.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
1
2020-08-13T03:06:41.000Z
2020-08-13T03:06:41.000Z
Modules/SceneSerializationBase/test/mitkVectorPropertySerializerTest.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/SceneSerializationBase/test/mitkVectorPropertySerializerTest.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkTestFixture.h" #include "mitkTestingMacros.h" #include "mitkBasePropertySerializer.h" #include "mitkVectorProperty.h" #include <mitkLexicalCast.h> #include <limits> #include <cmath> #include "mitkEqual.h" /** \brief Test for VectorPropertySerializer. Creates simple std::vector instances, puts them into a VectorProperty of appropriate type, then asks a serializer to serialize them into XML. Test expects that there is a deserializer somewhere in the system (i.e. registered with the ITK object factory. The test further expects that this deserializer is able to create a VectorProperty from XML and that this VectorProperty equals the input of serialization. */ class mitkVectorPropertySerializerTestSuite : public mitk::TestFixture { CPPUNIT_TEST_SUITE(mitkVectorPropertySerializerTestSuite); MITK_TEST(TestSerialize<int>); MITK_TEST(TestSerialize<double>); MITK_TEST(TestSerializeIntTypedef); MITK_TEST(TestSerializeDoubleTypedef); CPPUNIT_TEST_SUITE_END(); public: void setUp() override {} void tearDown() override {} template <typename DATATYPE> typename mitk::VectorProperty<DATATYPE>::Pointer MakeExampleProperty() { typename mitk::VectorProperty<DATATYPE>::Pointer vectorProperty = mitk::VectorProperty<DATATYPE>::New(); std::vector<DATATYPE> data; data.push_back(static_cast<DATATYPE>(-918273674.6172838)); data.push_back(0); data.push_back(static_cast<DATATYPE>(+6172838.918273674)); data.push_back(sqrt(2)); if (std::numeric_limits<DATATYPE>::has_infinity) { data.push_back(std::numeric_limits<DATATYPE>::infinity()); data.push_back(-std::numeric_limits<DATATYPE>::infinity()); } // do NOT test NaN: cannot be == to itself, so cannot be tested like the others // NaN is covered in a different test (FloatToStringTest at the time of writing this) // data.push_back( std::numeric_limits<DATATYPE>::quiet_NaN() ); vectorProperty->SetValue(data); return vectorProperty; } mitk::BaseProperty::Pointer TestSerialize(mitk::BaseProperty *property) { std::string serializername = std::string(property->GetNameOfClass()) + "Serializer"; std::list<itk::LightObject::Pointer> allSerializers = itk::ObjectFactoryBase::CreateAllInstance(serializername.c_str()); CPPUNIT_ASSERT_EQUAL(size_t(1), allSerializers.size()); auto *serializer = dynamic_cast<mitk::BasePropertySerializer *>(allSerializers.begin()->GetPointer()); CPPUNIT_ASSERT(serializer != nullptr); if (!serializer) return nullptr; serializer->SetProperty(property); TiXmlElement *serialization(nullptr); try { serialization = serializer->Serialize(); } catch (...) { } CPPUNIT_ASSERT(serialization != nullptr); if (!serialization) return nullptr; mitk::BaseProperty::Pointer restoredProperty = serializer->Deserialize(serialization); CPPUNIT_ASSERT(restoredProperty.IsNotNull()); return restoredProperty; } template <typename DATATYPE> void TestSerialize() { auto property = MakeExampleProperty<DATATYPE>(); mitk::BaseProperty::Pointer restored_property = TestSerialize(property); typename mitk::VectorProperty<DATATYPE>::Pointer restored_vector_property = dynamic_cast<mitk::VectorProperty<DATATYPE> *>(restored_property.GetPointer()); CPPUNIT_ASSERT(restored_vector_property.IsNotNull()); auto orig_vector = property->GetValue(); auto restored_vector = restored_vector_property->GetValue(); CPPUNIT_ASSERT_EQUAL(orig_vector.size(), restored_vector.size()); for (unsigned int i = 0; i < orig_vector.size(); ++i) { // compare using Equal, i.e. with tolerance of mitk::eps CPPUNIT_ASSERT_MESSAGE(std::string("Verifying element ") + boost::lexical_cast<std::string>(i), mitk::Equal(orig_vector[i], restored_vector[i])); } } void TestSerializeIntTypedef() { mitk::IntVectorProperty::Pointer intVectorProperty = MakeExampleProperty<int>().GetPointer(); TestSerialize(intVectorProperty.GetPointer()); } void TestSerializeDoubleTypedef() { mitk::DoubleVectorProperty::Pointer doubleVectorProperty = MakeExampleProperty<double>().GetPointer(); TestSerialize(doubleVectorProperty.GetPointer()); } }; // class MITK_TEST_SUITE_REGISTRATION(mitkVectorPropertySerializer)
33.626761
108
0.710576
[ "object", "vector" ]
fefd521eb34b246161ec3b8eb942ad7c7c554baa
10,523
cpp
C++
umd/core/runtime/Emulator.cpp
CSL-KU/nvdla-sw
a39365fe87b442a3a18eab42cafcdb08b417750f
[ "Apache-2.0" ]
1
2020-07-30T08:01:14.000Z
2020-07-30T08:01:14.000Z
umd/core/runtime/Emulator.cpp
CSL-KU/nvdla-sw
a39365fe87b442a3a18eab42cafcdb08b417750f
[ "Apache-2.0" ]
null
null
null
umd/core/runtime/Emulator.cpp
CSL-KU/nvdla-sw
a39365fe87b442a3a18eab42cafcdb08b417750f
[ "Apache-2.0" ]
2
2019-02-12T00:29:27.000Z
2020-10-23T16:56:03.000Z
/* * Copyright (c) 2017-2018, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <queue> #include "half.h" #include "priv/Emulator.h" #include "priv/Check.h" #include "ErrorMacros.h" using namespace half_float; namespace nvdla { namespace priv { Emulator::Emulator() : m_thread(), m_threadActive(false), m_signalShutdown(false) { } Emulator::~Emulator() { } bool Emulator::ping() { return m_threadActive; } NvDlaError Emulator::submit(NvU8* task_mem, bool blocking) { m_taskQueue.push(task_mem); if (blocking) { // wait until queue becomes empty while (!m_taskQueue.empty()) { NvDlaThreadYield(); } } return NvDlaSuccess; } NvDlaError Emulator::start() { NvDlaError e = NvDlaSuccess; PROPAGATE_ERROR_FAIL(NvDlaThreadCreate(threadFunction, this, &m_thread), "Failed to create thread"); return NvDlaSuccess; fail: return e; } void Emulator::threadFunction(void* arg) { Emulator* engine = static_cast<Emulator*>(arg); engine->run(); } bool Emulator::stop() { bool ok = true; if (m_thread) { m_signalShutdown = true; NvDlaThreadJoin(m_thread); m_thread = NULL; } return ok; } bool Emulator::run() { bool ok = true; m_threadActive = true; /* EMUInterface* emu_if = new EMUInterfaceA(); NvDlaDebugPrintf("Emulator starting\n"); while (true) { if (!m_taskQueue.empty()) { NvU8* task_mem = m_taskQueue.front(); NvDlaDebugPrintf("Work Found!\n"); EMUTaskDescAccessor task_desc = emu_if->taskDescAccessor(task_mem); NvU32 numAddresses = *task_desc.numAddresses(); std::vector<NvU8*> mappedAddressList; mappedAddressList.resize(numAddresses); // Replace all mem handles with mapped addresses for (NvU32 ii=0; ii<numAddresses; ii++) { void* base = *((void **)task_desc.addressList(ii).hMem()); NvU32 offset = *task_desc.addressList(ii).offset(); if (base == 0) { mappedAddressList[ii] = NULL; } else { mappedAddressList[ii] = (NvU8*)base + offset; } } // Process the task processTask(task_mem, mappedAddressList); NvDlaDebugPrintf("Work Done\n"); m_taskQueue.pop(); continue; } if (m_signalShutdown) { NvDlaDebugPrintf("Shutdown signal received, exiting\n"); break; } if (m_taskQueue.empty()) { NvDlaSleepMS(500); } } // Cleanup while (!m_taskQueue.empty()) { m_taskQueue.pop(); } delete emu_if; */ m_threadActive = false; m_signalShutdown = false; return ok; } bool Emulator::processTask(NvU8* task_mem, std::vector<NvU8*> addressList) { EMUInterface* emu_if = new EMUInterfaceA(); EMUTaskDescAccessor task_desc = emu_if->taskDescAccessor(task_mem); NVDLA_UNUSED(task_desc); // 0 - network descriptor EMUNetworkDescAccessor network_desc = emu_if->networkDescAccessor(addressList[0]); EMUOperationContainerAccessor operation_container_0 = emu_if->operationContainerAccessor(addressList[*network_desc.operationDescIndex()]); EMUOperationBufferContainerAccessor operation_buffer_container_0 = emu_if->operationBufferContainerAccessor(addressList[*network_desc.operationBufferDescIndex()]); EMUCommonOpDescAccessor common_op_desc_0 = operation_container_0.softmaxOpDescAccessor(0).commonOpDescAccessor(); if (*common_op_desc_0.op_type() == 0 /* POWER */) { EMUPowerOpDescAccessor power_op_desc = operation_container_0.powerOpDescAccessor(0); EMUPowerBufferDescsAccessor power_op_buffer_descs = operation_buffer_container_0.powerBufferDescsAccessor(0); executePower(power_op_desc, power_op_buffer_descs, addressList); } else if (*common_op_desc_0.op_type() == 1 /* SOFTMAX */) { EMUSoftmaxOpDescAccessor softmax_op_desc = operation_container_0.softmaxOpDescAccessor(0); EMUSoftmaxBufferDescsAccessor softmax_op_buffer_descs = operation_buffer_container_0.softmaxBufferDescsAccessor(0); executeSoftmax(softmax_op_desc, softmax_op_buffer_descs, addressList); } else { NvDlaDebugPrintf("Unknown op type %u\n", *common_op_desc_0.op_type()); } delete emu_if; return true; } NvDlaError Emulator::getAddrOffset(EMUBufferDescAccessor in, NvU32 w, NvU32 h, NvU32 c, NvU32* offset) { NvDlaError e = NvDlaSuccess; if ((*in.format()) == 2/*NVDLA_FF16_F_FORMAT*/) { NvU8 bpe = 2; NvU32 x = 16; NvU32 xStride = x * bpe; NvU32 cquotient = c / x; NvU32 cremainder = c % x; *offset = (cquotient * (*in.surfStride())) + (h * (*in.lineStride())) + (w * xStride) + (cremainder * bpe); } else { ORIGINATE_ERROR_FAIL(NvDlaError_BadParameter); } return NvDlaSuccess; fail: return e; } bool Emulator::executePower(EMUPowerOpDescAccessor opDesc, EMUPowerBufferDescsAccessor bufDescs, std::vector<NvU8*> addressList) { EMUBufferDescAccessor src = bufDescs.srcDataAccessor(); EMUBufferDescAccessor dst = bufDescs.dstDataAccessor(); if ( debugOps() ) { NvDlaDebugPrintf("Processing power [power=%f scale=%f shift=%f]\n", *opDesc.power(), *opDesc.scale(), *opDesc.shift()); NvDlaDebugPrintf("src format %u\n", *src.format()); NvDlaDebugPrintf("\taddress[%u] 0x%llx (%ux%ux%u) %uB\n", *src.addressIndex(), addressList[*src.addressIndex()], *src.width(), *src.height(), *src.channel(), *src.size()); NvDlaDebugPrintf("\tline_stride %uB surface_stride %uB\n", *src.lineStride(), *src.surfStride()); NvDlaDebugPrintf("dst format %u\n", *dst.format()); NvDlaDebugPrintf("\taddress[%u] 0x%llx (%ux%ux%u) %uB\n", *dst.addressIndex(), addressList[*dst.addressIndex()], *dst.width(), *dst.height(), *dst.channel(), *dst.size()); NvDlaDebugPrintf("\tline_stride %uB surface_stride %uB\n", *dst.lineStride(), *dst.surfStride()); } NvU8* pSrc = addressList[*src.addressIndex()]; NvU8* pDst = addressList[*dst.addressIndex()]; // Execute for (NvU32 channel=0; channel<*src.channel(); channel++) { for (NvU32 height=0; height<*src.height(); height++) { for (NvU32 width=0; width<*src.width(); width++) { NvU32 srcoffset = 0; NvU32 dstoffset = 0; if (getAddrOffset(src, width, height, channel, &srcoffset) != NvDlaSuccess) return false; if (getAddrOffset(dst, width, height, channel, &dstoffset) != NvDlaSuccess) return false; half_float::half* srchalfp = reinterpret_cast<half_float::half*>(pSrc + srcoffset); half_float::half* dsthalfp = reinterpret_cast<half_float::half*>(pDst + dstoffset); NvF32 x = float(*srchalfp); NvF32 y = powf((*opDesc.shift() + (*opDesc.scale() * x)), *opDesc.power()); *dsthalfp = half(y); } } } return true; } bool Emulator::executeSoftmax(EMUSoftmaxOpDescAccessor opDesc, EMUSoftmaxBufferDescsAccessor bufDescs, std::vector<NvU8*> addressList) { EMUBufferDescAccessor src = bufDescs.srcDataAccessor(); EMUBufferDescAccessor dst = bufDescs.dstDataAccessor(); if ( debugOps() ) { NvDlaDebugPrintf("Processing softmax [axis=%u]\n", *opDesc.axis()); NvDlaDebugPrintf("src format %u\n", *src.format()); NvDlaDebugPrintf("\taddress[%u] 0x%llx (%ux%ux%u) %uB\n", *src.addressIndex(), addressList[*src.addressIndex()], *src.width(), *src.height(), *src.channel(), *src.size()); NvDlaDebugPrintf("\tline_stride %uB surface_stride %uB\n", *src.lineStride(), *src.surfStride()); NvDlaDebugPrintf("dst format %u\n", *dst.format()); NvDlaDebugPrintf("\taddress[%u] 0x%llx (%ux%ux%u) %uB\n", *dst.addressIndex(), addressList[*dst.addressIndex()], *dst.width(), *dst.height(), *dst.channel(), *dst.size()); NvDlaDebugPrintf("\tline_stride %uB surface_stride %uB\n", *dst.lineStride(), *dst.surfStride()); } half* pSrc = reinterpret_cast<half*>(addressList[*src.addressIndex()]); half* pDst = reinterpret_cast<half*>(addressList[*dst.addressIndex()]); NvF32 maxval = -INFINITY; for (NvU32 ii=0; ii<*src.channel(); ii++) { if (float(pSrc[ii]) > maxval) { maxval = float(pSrc[ii]); } } NvF32 sumexp = 0.0f; for (NvU32 ii=0; ii<*src.channel(); ii++) { sumexp += expf(float(pSrc[ii])-maxval); } for (NvU32 ii=0; ii<*src.channel(); ii++) { pDst[ii] = expf(float(pSrc[ii])-maxval) / sumexp; } return true; } } // nvdla::priv } // nvdla
32.082317
179
0.643543
[ "vector" ]
3a0129e942f059687921609f6509b06d65bd9f01
6,282
cc
C++
src/Topology.cc
Alexey-Ershov/runos
dfbf8f74d7f45d25f0d4fad743b51f572ec272c9
[ "Apache-2.0" ]
9
2019-04-04T18:03:36.000Z
2019-05-03T23:48:59.000Z
src/Topology.cc
Alexey-Ershov/runos
dfbf8f74d7f45d25f0d4fad743b51f572ec272c9
[ "Apache-2.0" ]
16
2019-04-04T12:22:19.000Z
2019-04-09T19:04:42.000Z
src/Topology.cc
Alexey-Ershov/runos
dfbf8f74d7f45d25f0d4fad743b51f572ec272c9
[ "Apache-2.0" ]
2
2019-10-11T14:17:26.000Z
2022-03-15T10:06:08.000Z
/* * Copyright 2015 Applied Research Center for Computer Networks * * 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 "Topology.hh" #include <unordered_map> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/dijkstra_shortest_paths_no_color_map.hpp> #include <boost/lexical_cast.hpp> #include <boost/assert.hpp> #include "Common.hh" REGISTER_APPLICATION(Topology, {"link-discovery", "rest-listener", ""}) using namespace boost; using namespace topology; class Link : public AppObject { switch_and_port source; switch_and_port target; int weight; uint64_t obj_id; public: Link(switch_and_port _source, switch_and_port _target, int _weight, uint64_t _id): source(_source), target(_target), weight(_weight), obj_id(_id) {} json11::Json to_json() const override; json11::Json to_floodlight_json() const; uint64_t id() const override; friend class Topology; }; uint64_t Link::id() const { return obj_id; } Link* Topology::getLink(switch_and_port from, switch_and_port to) { for (Link* it : topo) { if ((it->source == from && it->target == to) || (it->source == to && it->target == from)) return it; } return nullptr; } json11::Json Link::to_json() const { json11::Json src = json11::Json::object { {"src_id", boost::lexical_cast<std::string>(source.dpid)}, {"src_port", (int)source.port} }; json11::Json dst = json11::Json::object { {"dst_id", boost::lexical_cast<std::string>(target.dpid)}, {"dst_port", (int)target.port} }; return json11::Json::object { {"ID", id_str()}, {"connect", json11::Json::array { src, dst } }, {"bandwidth", weight} }; } json11::Json Link::to_floodlight_json() const { return json11::Json::object { {"src-switch", boost::lexical_cast<std::string>(source.dpid)}, {"src-port", (int)source.port}, {"dst-switch", boost::lexical_cast<std::string>(target.dpid)}, {"dst-port", (int)target.port}, {"type", "internal"}, {"direction", "bidirectional"} }; } typedef TopologyGraph::vertex_descriptor vertex_descriptor; struct TopologyImpl { QReadWriteLock graph_mutex; TopologyGraph graph; std::unordered_map<uint64_t, vertex_descriptor> vertex_map; vertex_descriptor vertex(uint64_t dpid) { auto it = vertex_map.find(dpid); if (it != vertex_map.end()) { auto v = it->second; BOOST_ASSERT(get(dpid_t(), graph, v) == dpid); return v; } else { auto v = vertex_map[dpid] = add_vertex(graph); put(dpid_t(), graph, v, dpid); return v; } } }; void Topology::init(Loader *loader, const Config &config) { QObject* ld = ILinkDiscovery::get(loader); QObject::connect(ld, SIGNAL(linkDiscovered(switch_and_port, switch_and_port)), this, SLOT(linkDiscovered(switch_and_port, switch_and_port))); QObject::connect(ld, SIGNAL(linkBroken(switch_and_port, switch_and_port)), this, SLOT(linkBroken(switch_and_port, switch_and_port))); RestListener::get(loader)->registerRestHandler(this); acceptPath(Method::GET, "links"); } Topology::Topology() { m = new TopologyImpl; } Topology::~Topology() { delete m; } void Topology::linkDiscovered(switch_and_port from, switch_and_port to) { QWriteLocker locker(&m->graph_mutex); if (from.dpid == to.dpid) { LOG(WARNING) << "Ignoring loopback link on " << from.dpid; return; } /* TODO: calculate metric */ auto u = m->vertex(from.dpid); auto v = m->vertex(to.dpid); add_edge(u, v, link_property{from, to, 1}, m->graph); Link* link = new Link(from, to, 5, rand()%1000 + 2000); topo.push_back(link); addEvent(Event::Add, link); } void Topology::linkBroken(switch_and_port from, switch_and_port to) { QWriteLocker locker(&m->graph_mutex); remove_edge(m->vertex(from.dpid), m->vertex(to.dpid), m->graph); Link* link = getLink(from, to); addEvent(Event::Delete, link); topo.erase(std::remove(topo.begin(), topo.end(), link), topo.end()); } data_link_route Topology::computeRoute(uint64_t from_dpid, uint64_t to_dpid) { DVLOG(5) << "Computing route between " << from_dpid << " and " << to_dpid; QReadLocker locker(&m->graph_mutex); const auto& graph = m->graph; vector_property_map<vertex_descriptor> p; vertex_descriptor v = m->vertex(from_dpid); dijkstra_shortest_paths_no_color_map(graph, m->vertex(to_dpid), weight_map( boost::get(&link_property::weight, graph) ) .predecessor_map( p ) ); data_link_route ret; BOOST_ASSERT( v != TopologyGraph::null_vertex() ); for (; v != p[v]; v = p[v]) { BOOST_ASSERT(edge(v, p[v], graph).second); link_property link = graph[edge(v, p[v], graph).first]; if (link.source.dpid == boost::get(dpid_t(), graph, v)) { BOOST_ASSERT(link.target.dpid == boost::get(dpid_t(), graph, p[v])); ret.push_back(link.source); ret.push_back(link.target); } else { BOOST_ASSERT(link.target.dpid == boost::get(dpid_t(), graph, v)); BOOST_ASSERT(link.source.dpid == boost::get(dpid_t(), graph, p[v])); ret.push_back(link.target); ret.push_back(link.source); } } return ret; } void Topology::apply(std::function<void(const TopologyGraph&)> f) const { QReadLocker locker(&m->graph_mutex); f(m->graph); } json11::Json Topology::handleGET(std::vector<std::string> params, std::string body) { if (params[0] == "links") return json11::Json(topo).dump(); return "{}"; }
29.083333
97
0.640401
[ "object", "vector" ]
3a08e0b7e6b4bf23ecb48cdd514a933fa3b4fc06
2,419
hpp
C++
Sources/Editor/Scenes/AssetsEditorScene.hpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
47
2015-03-29T09:44:25.000Z
2020-11-30T10:05:56.000Z
Sources/Editor/Scenes/AssetsEditorScene.hpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
313
2015-01-01T18:16:30.000Z
2015-11-30T07:54:07.000Z
Sources/Editor/Scenes/AssetsEditorScene.hpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
9
2015-06-07T13:21:54.000Z
2020-08-25T09:50:07.000Z
#pragma once #include <Core/AScene.hh> #include <Core/Engine.hh> #include <memory> #include <FileUtils/AssetFiles/Folder.hpp> #include <set> #include "IMenuInheritrance.hpp" namespace AGE { namespace FileUtils { class RawFile; } namespace AE { struct CookConfig; } class AssetsEditorScene : public IMenuInheritance { public: static const std::string Name; AssetsEditorScene(AGE::Engine *engine); virtual ~AssetsEditorScene(void); virtual bool _userStart(); virtual bool _userUpdateBegin(float time); virtual bool _userUpdateEnd(float time); static FileUtils::Folder &getRawList() { return _raw; } static FileUtils::Folder &getCookedList() { return _cook; } static std::vector<const char *> &getCookedMeshsList() { return _cookedMeshFiles; } static std::vector<const char *> &getCookedMeshsListFullPath() { return _cookedMeshsFullPath; } static std::vector<const char *> &getCookedPhysicsList() { return _cookedPhysicsFiles; } static std::vector<const char *> &getCookedPhysicsListFullPath() { return _cookedPhysicsFullPath; } static std::vector<const char *> &getCookedMaterialList() { return _cookedMaterialFiles; } static std::vector<const char *> &getCookedMaterialListFullPath() { return _cookedMaterialFullPath; } static std::vector<const char *> &getCookedTextureList() { return _cookedTextureFiles; } static std::vector<const char *> &getCookedTextureListFullPath() { return _cookedTextureFullPath; } virtual void updateMenu(); private: static FileUtils::Folder _raw; static FileUtils::Folder _cook; struct AssetsEditorFileDescriptor { AssetsEditorFileDescriptor(const std::string &_fp, const std::string &_fn) : fullPath(_fp), fileName(_fn) {} std::string fullPath; std::string fileName; }; static std::vector<AssetsEditorFileDescriptor> _cookedFiles; static std::vector<const char *> _cookedMeshsFullPath; static std::vector<const char *> _cookedMeshFiles; static std::vector<const char *> _cookedPhysicsFullPath; static std::vector<const char *> _cookedPhysicsFiles; static std::vector<const char *> _cookedMaterialFullPath; static std::vector<const char *> _cookedMaterialFiles; static std::vector<const char *> _cookedTextureFullPath; static std::vector<const char *> _cookedTextureFiles; std::shared_ptr<FileUtils::RawFile> _selectedRaw; std::set<std::shared_ptr<AE::CookConfig>> _configs; }; }
32.253333
103
0.751137
[ "vector" ]
3a096088075f4c8d19af25676624886d876b8ff5
36
cpp
C++
compiler-native/test/test_parallel.cpp
SleepyToDeath/NetQRE
0176a31afa45faa4877974a4a0575a4e60534090
[ "MIT" ]
2
2021-03-30T15:25:44.000Z
2021-05-14T07:22:25.000Z
compiler-native/test/test_parallel.cpp
SleepyToDeath/NetQRE
0176a31afa45faa4877974a4a0575a4e60534090
[ "MIT" ]
null
null
null
compiler-native/test/test_parallel.cpp
SleepyToDeath/NetQRE
0176a31afa45faa4877974a4a0575a4e60534090
[ "MIT" ]
null
null
null
#include <vector> #include <vector>
12
17
0.722222
[ "vector" ]
3a096b9e18740db1b6422ebe1fb179a8730fa4a7
3,139
cc
C++
polardb/src/model/DescribeDBClusterAccessWhitelistResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
polardb/src/model/DescribeDBClusterAccessWhitelistResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
polardb/src/model/DescribeDBClusterAccessWhitelistResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * 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. */ #include <alibabacloud/polardb/model/DescribeDBClusterAccessWhitelistResult.h> #include <json/json.h> using namespace AlibabaCloud::Polardb; using namespace AlibabaCloud::Polardb::Model; DescribeDBClusterAccessWhitelistResult::DescribeDBClusterAccessWhitelistResult() : ServiceResult() {} DescribeDBClusterAccessWhitelistResult::DescribeDBClusterAccessWhitelistResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDBClusterAccessWhitelistResult::~DescribeDBClusterAccessWhitelistResult() {} void DescribeDBClusterAccessWhitelistResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allItemsNode = value["Items"]["DBClusterIPArray"]; for (auto valueItemsDBClusterIPArray : allItemsNode) { DBClusterIPArray itemsObject; if(!valueItemsDBClusterIPArray["DBClusterIPArrayName"].isNull()) itemsObject.dBClusterIPArrayName = valueItemsDBClusterIPArray["DBClusterIPArrayName"].asString(); if(!valueItemsDBClusterIPArray["DBClusterIPArrayAttribute"].isNull()) itemsObject.dBClusterIPArrayAttribute = valueItemsDBClusterIPArray["DBClusterIPArrayAttribute"].asString(); if(!valueItemsDBClusterIPArray["SecurityIps"].isNull()) itemsObject.securityIps = valueItemsDBClusterIPArray["SecurityIps"].asString(); items_.push_back(itemsObject); } auto allDBClusterSecurityGroupsNode = value["DBClusterSecurityGroups"]["DBClusterSecurityGroup"]; for (auto valueDBClusterSecurityGroupsDBClusterSecurityGroup : allDBClusterSecurityGroupsNode) { DBClusterSecurityGroup dBClusterSecurityGroupsObject; if(!valueDBClusterSecurityGroupsDBClusterSecurityGroup["SecurityGroupId"].isNull()) dBClusterSecurityGroupsObject.securityGroupId = valueDBClusterSecurityGroupsDBClusterSecurityGroup["SecurityGroupId"].asString(); if(!valueDBClusterSecurityGroupsDBClusterSecurityGroup["SecurityGroupName"].isNull()) dBClusterSecurityGroupsObject.securityGroupName = valueDBClusterSecurityGroupsDBClusterSecurityGroup["SecurityGroupName"].asString(); dBClusterSecurityGroups_.push_back(dBClusterSecurityGroupsObject); } } std::vector<DescribeDBClusterAccessWhitelistResult::DBClusterIPArray> DescribeDBClusterAccessWhitelistResult::getItems()const { return items_; } std::vector<DescribeDBClusterAccessWhitelistResult::DBClusterSecurityGroup> DescribeDBClusterAccessWhitelistResult::getDBClusterSecurityGroups()const { return dBClusterSecurityGroups_; }
40.766234
149
0.818732
[ "vector", "model" ]
3a0a77ff950a4ee2b5978bfb2c0ae833778081bb
12,248
hpp
C++
libraries/chain/include/graphene/chain/crosschain_trx_object.hpp
hbchain/hbcore
649c67d91cf950e0fc4102a6e0ea82e5f7abd17f
[ "MIT" ]
2
2020-07-22T02:08:49.000Z
2020-12-04T08:20:40.000Z
libraries/chain/include/graphene/chain/crosschain_trx_object.hpp
hbchain/hbcore
649c67d91cf950e0fc4102a6e0ea82e5f7abd17f
[ "MIT" ]
null
null
null
libraries/chain/include/graphene/chain/crosschain_trx_object.hpp
hbchain/hbcore
649c67d91cf950e0fc4102a6e0ea82e5f7abd17f
[ "MIT" ]
1
2020-12-01T07:50:29.000Z
2020-12-01T07:50:29.000Z
#pragma once #include <graphene/chain/protocol/asset.hpp> #include <graphene/db/object.hpp> #include <graphene/db/generic_index.hpp> #include <boost/multi_index/composite_key.hpp> #include <graphene/crosschain/crosschain.hpp> #include <map> namespace graphene { namespace chain { using namespace graphene::db; using namespace graphene::crosschain; enum eth_multi_account_trx_state { sol_create_need_guard_sign = 0, sol_create_guard_signed = 1, sol_multi_account_ethchain_create = 2, sol_create_comlete = 3 }; class eth_multi_account_trx_object; class eth_multi_account_trx_object :public graphene::db::abstract_object<eth_multi_account_trx_object> { public: static const uint8_t space_id = protocol_ids; static const uint8_t type_id = eth_multi_account_trx_object_type; std::string symbol; transaction_id_type multi_account_pre_trx_id; transaction_id_type multi_account_create_trx_id; signed_transaction object_transaction; std::string hot_addresses; std::string cold_addresses; std::string hot_sol_trx_id; std::string cold_sol_trx_id; bool cold_trx_success=false; bool hot_trx_success=false; eth_multi_account_trx_state state; uint64_t op_type; }; struct by_mulaccount_trx_id; struct by_eth_hot_multi; struct by_eth_cold_multi; struct by_eth_hot_multi_trx_id; struct by_eth_cold_multi_trx_id; struct by_eth_mulacc_tx_state; struct by_eth_mulacc_tx_op; struct by_pre_trx_id; using eth_multi_account_trx_index_type = multi_index_container < eth_multi_account_trx_object, indexed_by < ordered_unique< tag<by_id>, member<object, object_id_type, &object::id> >, ordered_non_unique< tag<by_eth_mulacc_tx_state>, member<eth_multi_account_trx_object, eth_multi_account_trx_state, &eth_multi_account_trx_object::state> >, ordered_non_unique< tag<by_eth_mulacc_tx_op>, member<eth_multi_account_trx_object, uint64_t, &eth_multi_account_trx_object::op_type> >, ordered_non_unique< tag<by_eth_hot_multi>, member<eth_multi_account_trx_object, std::string, &eth_multi_account_trx_object::hot_addresses> >, ordered_non_unique< tag<by_eth_cold_multi>, member<eth_multi_account_trx_object, std::string, &eth_multi_account_trx_object::cold_addresses> >, ordered_non_unique< tag<by_eth_hot_multi_trx_id>, member<eth_multi_account_trx_object, std::string, &eth_multi_account_trx_object::hot_sol_trx_id> >, ordered_non_unique< tag<by_eth_cold_multi_trx_id>, member<eth_multi_account_trx_object, std::string, &eth_multi_account_trx_object::cold_sol_trx_id> >, ordered_non_unique<tag<by_pre_trx_id>, member<eth_multi_account_trx_object, transaction_id_type, &eth_multi_account_trx_object::multi_account_pre_trx_id> >, ordered_unique< tag<by_mulaccount_trx_id>, member<eth_multi_account_trx_object, transaction_id_type, &eth_multi_account_trx_object::multi_account_create_trx_id> > > >; using eth_multi_account_trx_index = generic_index<eth_multi_account_trx_object, eth_multi_account_trx_index_type>; enum transaction_stata { withdraw_without_sign_trx_uncreate = 0, withdraw_without_sign_trx_create = 1, withdraw_sign_trx = 2, withdraw_combine_trx_create = 3, withdraw_transaction_confirm = 4, withdraw_transaction_fail = 5, withdraw_canceled =6, withdraw_eth_guard_need_sign = 7, withdraw_eth_guard_sign = 8 }; enum acquired_trx_state { acquired_trx_uncreate = 0, acquired_trx_create = 1, acquired_trx_comfirmed = 2, acquired_trx_deposit_failure = -1 }; class crosschain_transaction_history_count_object; class crosschain_transaction_history_count_object :public graphene::db::abstract_object<crosschain_transaction_history_count_object> { public: static const uint8_t space_id = protocol_ids; static const uint8_t type_id = crosschain_transaction_history_count_object_type; std::string asset_symbol; uint32_t local_count; }; struct by_history_count_id; struct by_history_asset_symbol; using transaction_history_count_multi_index_type = multi_index_container < crosschain_transaction_history_count_object, indexed_by < ordered_unique< tag<by_history_count_id>, member<object, object_id_type, &object::id> >, ordered_unique< tag<by_history_asset_symbol>, member<crosschain_transaction_history_count_object, std::string, &crosschain_transaction_history_count_object::asset_symbol> > > >; using transaction_history_count_index = generic_index<crosschain_transaction_history_count_object, transaction_history_count_multi_index_type>; class acquired_crosschain_trx_object; class acquired_crosschain_trx_object :public graphene::db::abstract_object<acquired_crosschain_trx_object> { public: static const uint8_t space_id = protocol_ids; static const uint8_t type_id = acquired_crosschain_object_type; hd_trx handle_trx; std::string handle_trx_id; acquired_trx_state acquired_transaction_state; acquired_crosschain_trx_object() {} }; struct by_acquired_trx_id; struct by_acquired_trx_state; using acquired_crosschain_multi_index_type = multi_index_container < acquired_crosschain_trx_object, indexed_by < ordered_unique< tag<by_id>, member<object, object_id_type, &object::id> >, ordered_non_unique< tag<by_acquired_trx_state>, member<acquired_crosschain_trx_object, acquired_trx_state, &acquired_crosschain_trx_object::acquired_transaction_state> >, ordered_unique< tag<by_acquired_trx_id>, member<acquired_crosschain_trx_object, std::string, &acquired_crosschain_trx_object::handle_trx_id> > > > ; using acquired_crosschain_index = generic_index<acquired_crosschain_trx_object, acquired_crosschain_multi_index_type>; class crosschain_trx_object; class crosschain_trx_object : public graphene::db::abstract_object<crosschain_trx_object> { public: static const uint8_t space_id = protocol_ids; static const uint8_t type_id = crosschain_trx_object_type; transaction_id_type relate_transaction_id; transaction_id_type transaction_id; vector<transaction_id_type> all_related_origin_transaction_ids; signed_transaction real_transaction; string without_link_account; uint64_t op_type; transaction_stata trx_state; string crosschain_trx_id; asset crosschain_fee ; uint32_t block_num; string symbol; crosschain_trx_object() {} }; struct by_relate_trx_id; struct by_transaction_id; struct by_type; struct by_transaction_stata; struct by_trx_relate_type_stata; struct by_trx_type_state; struct by_original_id_optype; struct by_withdraw_link_account; struct by_symbol_block_num_state; struct by_account_symbol_block_num_state; struct by_block_num_state; struct by_account_block_num_state; using crosschain_multi_index_type = multi_index_container < crosschain_trx_object, indexed_by < ordered_unique< tag<by_id>, member<object, object_id_type, &object::id> >, ordered_non_unique< tag<by_type>, member<crosschain_trx_object, uint64_t, &crosschain_trx_object::op_type> >, ordered_non_unique< tag<by_transaction_stata>, member<crosschain_trx_object, transaction_stata, &crosschain_trx_object::trx_state> >, ordered_non_unique< tag<by_relate_trx_id>, member<crosschain_trx_object, transaction_id_type, &crosschain_trx_object::relate_transaction_id> >, ordered_unique< tag<by_transaction_id>, member<crosschain_trx_object, transaction_id_type, &crosschain_trx_object::transaction_id> >, ordered_non_unique< tag<by_trx_relate_type_stata>, composite_key< crosschain_trx_object, member<crosschain_trx_object, transaction_id_type, &crosschain_trx_object::relate_transaction_id>, member<crosschain_trx_object, transaction_stata, &crosschain_trx_object::trx_state> >//, /*composite_key_compare< std::less< transaction_id_type >, std::less<transaction_stata> >*/ >, ordered_non_unique< tag<by_withdraw_link_account>, composite_key< crosschain_trx_object, member<crosschain_trx_object, string, &crosschain_trx_object::without_link_account> > >, ordered_non_unique< tag<by_original_id_optype>, composite_key< crosschain_trx_object, member<crosschain_trx_object, string, &crosschain_trx_object::crosschain_trx_id>, member<crosschain_trx_object, uint64_t, &crosschain_trx_object::op_type> > >, ordered_unique< tag<by_symbol_block_num_state>, composite_key< crosschain_trx_object, member<crosschain_trx_object, string, &crosschain_trx_object::symbol>, member<crosschain_trx_object, transaction_stata, &crosschain_trx_object::trx_state>, member<crosschain_trx_object, uint32_t, &crosschain_trx_object::block_num>, member<crosschain_trx_object, transaction_id_type, &crosschain_trx_object::transaction_id> > >, ordered_unique< tag<by_account_symbol_block_num_state>, composite_key< crosschain_trx_object, member<crosschain_trx_object, string, &crosschain_trx_object::without_link_account>, member<crosschain_trx_object, string, &crosschain_trx_object::symbol>, member<crosschain_trx_object, transaction_stata, &crosschain_trx_object::trx_state>, member<crosschain_trx_object, uint32_t, &crosschain_trx_object::block_num>, member<crosschain_trx_object, transaction_id_type, &crosschain_trx_object::transaction_id> > >, ordered_unique< tag<by_block_num_state>, composite_key< crosschain_trx_object, member<crosschain_trx_object, transaction_stata, &crosschain_trx_object::trx_state>, member<crosschain_trx_object, uint32_t, &crosschain_trx_object::block_num>, member<crosschain_trx_object, transaction_id_type, &crosschain_trx_object::transaction_id> > >, ordered_unique< tag<by_account_block_num_state>, composite_key< crosschain_trx_object, member<crosschain_trx_object, string, &crosschain_trx_object::without_link_account>, member<crosschain_trx_object, transaction_stata, &crosschain_trx_object::trx_state>, member<crosschain_trx_object, uint32_t, &crosschain_trx_object::block_num>, member<crosschain_trx_object, transaction_id_type, &crosschain_trx_object::transaction_id> > >, ordered_non_unique< tag<by_trx_type_state>, composite_key< crosschain_trx_object, member<crosschain_trx_object, transaction_id_type, &crosschain_trx_object::transaction_id>, member<crosschain_trx_object, transaction_stata, &crosschain_trx_object::trx_state> >, composite_key_compare< std::less< transaction_id_type >, std::less<transaction_stata> > > > > ; using crosschain_trx_index = generic_index<crosschain_trx_object, crosschain_multi_index_type>; } } FC_REFLECT_ENUM(graphene::chain::eth_multi_account_trx_state,(sol_create_need_guard_sign)(sol_create_guard_signed)(sol_multi_account_ethchain_create)(sol_create_comlete)) FC_REFLECT_ENUM(graphene::chain::transaction_stata, (withdraw_without_sign_trx_uncreate) (withdraw_without_sign_trx_create) (withdraw_sign_trx) (withdraw_combine_trx_create) (withdraw_transaction_confirm) (withdraw_transaction_fail) (withdraw_canceled) (withdraw_eth_guard_need_sign) (withdraw_eth_guard_sign) ) FC_REFLECT_DERIVED(graphene::chain::crosschain_trx_object,(graphene::db::object), (relate_transaction_id) (transaction_id) (real_transaction) (crosschain_trx_id) (crosschain_fee) (without_link_account) (all_related_origin_transaction_ids) (op_type) (block_num) (symbol) (trx_state) ) FC_REFLECT_ENUM(graphene::chain::acquired_trx_state, (acquired_trx_uncreate) (acquired_trx_create) (acquired_trx_comfirmed) (acquired_trx_deposit_failure)) FC_REFLECT_DERIVED(graphene::chain::acquired_crosschain_trx_object, (graphene::db::object), (handle_trx) (handle_trx_id) (acquired_transaction_state)) FC_REFLECT_DERIVED(graphene::chain::eth_multi_account_trx_object, (graphene::db::object), (multi_account_pre_trx_id) (hot_sol_trx_id)(cold_sol_trx_id)(hot_addresses)(cold_addresses)(cold_trx_success)(symbol)(hot_trx_success)(multi_account_create_trx_id)(object_transaction)(state)(op_type)) FC_REFLECT_DERIVED(graphene::chain::crosschain_transaction_history_count_object, (graphene::db::object), (asset_symbol) (local_count) )
38.275
173
0.806254
[ "object", "vector" ]
3a0ba9f9ce3ae0d58e402e71dd7bcc3760c6d283
464
cpp
C++
sortVector.cpp
jpvarbed/practiceproblems
88770343139efcb478bd734346535df4f166e632
[ "MIT" ]
null
null
null
sortVector.cpp
jpvarbed/practiceproblems
88770343139efcb478bd734346535df4f166e632
[ "MIT" ]
null
null
null
sortVector.cpp
jpvarbed/practiceproblems
88770343139efcb478bd734346535df4f166e632
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> using namespace std; void print(const vector<auto> &v) { for (auto const& e : v) { cout << e << "\t"; } cout << endl; } int main() { vector<int> a{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; vector<int> b{ 20, 18, 16, 14, 12, 10, 8, 6, 4, 2}; vector<int> c{ 19, 17, 15, 13, 11, 9, 7, 5, 3, 1}; sort(a.begin(), a.end()); sort(b.begin(), b.end()); sort(c.begin(), c.end()); print(a); return 0; }
17.846154
55
0.534483
[ "vector" ]
3a0c3f0b7542c529105580f8a4280be67376725d
3,319
cpp
C++
ModelViewer/ViewModels/RootPageViewModel.cpp
peted70/dx-gltf-viewer
d18c8ea888f653baa26dbbabaad194a6e2e60899
[ "MIT" ]
2
2020-02-23T13:56:45.000Z
2020-05-04T21:46:16.000Z
ModelViewer/ViewModels/RootPageViewModel.cpp
peted70/dx-gltf-viewer
d18c8ea888f653baa26dbbabaad194a6e2e60899
[ "MIT" ]
1
2018-01-18T17:04:16.000Z
2018-01-18T17:04:16.000Z
ModelViewer/ViewModels/RootPageViewModel.cpp
peted70/dx-gltf-viewer
d18c8ea888f653baa26dbbabaad194a6e2e60899
[ "MIT" ]
null
null
null
#include "pch.h" #include "RootPageViewModel.h" #include "DelegateCommand.h" #include "SceneManager.h" #include "Utility.h" #include <experimental/resumable> #include <pplawait.h> using namespace ViewModels; using namespace Windows::Storage::Pickers; RootPageViewModel::RootPageViewModel() { LoadFileCommand = ref new DelegateCommand(ref new ExecuteDelegate(this, &RootPageViewModel::ExecuteLoadCommand), nullptr); } class LoadingWrapper { public: LoadingWrapper(function<void()> ctor, function<void()> dtor) : _dtor(dtor) { Schedule(ctor); } future<void> Schedule(function<void()> fn) { auto disp = Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher; co_await disp->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([fn]() { fn(); })); } ~LoadingWrapper() { Schedule(_dtor); } private: function<void()> _dtor; }; future<shared_ptr<GraphNode>> RootPageViewModel::LoadFileAsync() { auto fop = ref new FileOpenPicker(); fop->FileTypeFilter->Append(".glb"); // The code flow supports gltf files but unless we copy all of the loose files over // to a location that the native C++ environment can open them from then we will just // get access denied. //fop->FileTypeFilter->Append(".gltf"); auto file = co_await fop->PickSingleFileAsync(); if (file == nullptr) co_return nullptr; // RAII-style for ensuring that the progress gets cleared robustly auto loader = make_unique<LoadingWrapper>([this]() { Loading = true; }, [this]() { Loading = false; }); Utility::Out(L"filename = %s", file->Path->Data()); Filename = file->Path; // Since we don't have access to open a file in native code I'll take a copy of the file here // and access it from the application's temp folder. Another option might be to implement a streambuf // which streams data from a Winrt stream but since this is just a sample that seems quite high effort. // A knock-on effect from this is that GLTF files won't load (only GLB) since the files referenced by the // GLTF file i.e. .bin, .jpg, etc. won't have also been copied across.. // auto tempFolder = Windows::Storage::ApplicationData::Current->TemporaryFolder; auto tempFile = co_await file->CopyAsync(tempFolder, file->Name, NameCollisionOption::GenerateUniqueName); Utility::Out(L"temp file path = %s", tempFile->Path->Data()); auto ret = co_await ModelFactory::Instance().CreateFromFileAsync(tempFile->Path); co_return ret; } future<void> RootPageViewModel::Load() { Utility::Out(L"At Start of Load"); auto node = co_await LoadFileAsync(); if (node == nullptr) co_return; Utility::Out(L"Loaded"); // Add the GraphNode to the scene auto current = SceneManager::Instance().Current(); SceneManager::Instance().AddNode(node); } void RootPageViewModel::ExecuteLoadCommand(Object^ param) { Load(); } bool RootPageViewModel::Loading::get() { return _loading; } void RootPageViewModel::Loading::set(bool val) { if (_loading == val) return; _loading = val; OnPropertyChanged(getCallerName(__FUNCTION__)); } String^ RootPageViewModel::Filename::get() { return _filename; } void RootPageViewModel::Filename::set(String^ val) { if (_filename == val) return; _filename = val; OnPropertyChanged(getCallerName(__FUNCTION__)); }
27.658333
123
0.729738
[ "object" ]
3a0ce34fabb9c7248a1e129447643dd5b30b03a9
746
cc
C++
search-insert-position.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
search-insert-position.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
search-insert-position.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> #include <random> #include <set> #include <map> #include <algorithm> using namespace std; class Solution { public: int searchInsert(int A[], int n, int target) { int i = 0; for (; i < n; ++i) { if (target <= A[i]) break; } return i; } }; void test(int A[], int n, int target) { Solution sol; cout << sol.searchInsert(A, n, target) << endl; } int main(int argc, char *argv[]) { { int A[] = {1,3,5,6}; int n = sizeof(A)/sizeof(A[0]); test(A, n, 5); test(A, n, 2); test(A, n, 7); test(A, n, 0); } return 0; }
16.577778
54
0.457105
[ "vector" ]
3a0f5693e0e0b1e0b7e0614b07ef0a27c478bcfa
289,755
cpp
C++
GameServer/ProcHelperMsg.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/ProcHelperMsg.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
GameServer/ProcHelperMsg.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
1
2022-01-17T09:34:39.000Z
2022-01-17T09:34:39.000Z
#include <boost/format.hpp> #include <boost/foreach.hpp> #include "stdhdrs.h" #include "Log.h" #include "Exp.h" #include "Server.h" #include "CmdMsg.h" #include "doFunc.h" #include "WarCastle.h" #include "DBManager.h" #include "../ShareLib/DBCmd.h" #include "DratanCastle.h" #include "Party_recall_manager.h" #include "GuildBattleManager.h" #include "../ShareLib/packetType/ptype_old_do_item.h" #include "../ShareLib/packetType/ptype_syndicate.h" #include "../ShareLib/packetType/ptype_old_do_changejob.h" #include "../ShareLib/packetType/ptype_old_do_monstercombo.h" #include "../ShareLib/packetType/ptype_server_to_server_kick.h" #include "../ShareLib/packetType/ptype_old_do_friend.h" #include "../ShareLib/packetType/ptype_old_do_guild.h" #include "../ShareLib/packetType/ptype_guild_battle.h" #include "DescManager.h" #ifdef PREMIUM_CHAR #include "../ShareLib/packetType/ptype_premium_char.h" #endif #include "../ShareLib/Config.h" void ProcHelperWhisperReq(CNetMsg::SP& msg, int seq, int server, int subno, int zone); void ProcHelperWhisperRep(CNetMsg::SP& msg, int seq, int server, int subno, int zone); void ProcHelperWhisperNotfound(CNetMsg::SP& msg, int seq, int server, int subno, int zone); void ProcHelperWarNoticeTime(CNetMsg::SP& msg); void ProcHelperWarNoticeTimeRemain(CNetMsg::SP& msg); void ProcHelperWarNoticeStart(CNetMsg::SP& msg); void ProcHelperWarJoinAttackGuild(CNetMsg::SP& msg); void ProcHelperWarJoinDefenseGuild(CNetMsg::SP& msg); void ProcHelperWarNoticeStartAttackCastle(CNetMsg::SP& msg); void ProcHelperWarNoticeRemainFieldTime(CNetMsg::SP& msg); void ProcHelperWarNoticeEnd(CNetMsg::SP& msg); void ProcHelperGuildStashHistoryRep(CNetMsg::SP& msg); void ProcHelperGuildStashViewRep(CNetMsg::SP& msg); void ProcHelperGuildStashTakeRep(CNetMsg::SP& msg); void ProcHelperGuildStashSaveTaxRep(CNetMsg::SP& msg); void ProcHelperPartyMemberChangeJob(CNetMsg::SP& msg); void ProcHelperPartyChat(CNetMsg::SP& msg); void ProcHelperPartyRecallPrompt(CNetMsg::SP& msg); void ProcHelperPartyRecallConfirm(CNetMsg::SP& msg); void ProcHelperPartyRecallProc(CNetMsg::SP& msg); void ProcHelperFameupRep(CNetMsg::SP& msg); void ProcHelperTeacherLoadRep(CNetMsg::SP& msg); void ProcHelperGuildCreateRep(CNetMsg::SP& msg); void ProcHelperGuildCreateNotify(CNetMsg::SP& msg); void ProcHelperGuildOnlineNotify(CNetMsg::SP& msg); void ProcHelperGuildMemberList(CNetMsg::SP& msg); void ProcHelperGuildLoadRep(CNetMsg::SP& msg); void ProcHelperGuildLevelUpRep(CNetMsg::SP& msg); void ProcHelperGuildLevelUpNotify(CNetMsg::SP& msg); void ProcHelperGuildBreakUpRep(CNetMsg::SP& msg); void ProcHelperGuildBreakUpNotify(CNetMsg::SP& msg); void ProcHelperGuildMemberAddNotify(CNetMsg::SP& msg); void ProcHelperGuildMemberAddRep(CNetMsg::SP& msg); void ProcHelperGuildMemberOutNotify(CNetMsg::SP& msg); void ProcHelperGuildMemberOutRep(CNetMsg::SP& msg); void ProcHelperGuildMemberKickRep(CNetMsg::SP& msg); void ProcHelperGuildMemberKickNotify(CNetMsg::SP& msg); void ProcHelperGuildChangeBossNotify(CNetMsg::SP& msg); void ProcHelperGuildChangeBossRep(CNetMsg::SP& msg); void ProcHelperGuildAppointOfficerRep(CNetMsg::SP& msg); void ProcHelperGuildAppointOfficerNotify(CNetMsg::SP& msg); void ProcHelperGuildChat(CNetMsg::SP& msg); void ProcHelperGuildFireOfficerRep(CNetMsg::SP& msg); void ProcHelperGuildFireOfficerNotify(CNetMsg::SP& msg); void ProcHelperGuildLoadNotify(CNetMsg::SP& msg); void ProcHelperGuildBattleRep(CNetMsg::SP& msg); void ProcHelperGuildBattleStart(CNetMsg::SP& msg); void ProcHelperGuildBattleStopRep(CNetMsg::SP& msg); void ProcHelperGuildBattleStatus(CNetMsg::SP& msg); void ProcHelperGuildBattlePeaceRep(CNetMsg::SP& msg); void ProcHelperEventMoonStoneLoad(CNetMsg::SP& msg); void ProcHelperEventMoonStoneUpdate(CNetMsg::SP& msg); void ProcHelperEventMoonStoneJackpot(CNetMsg::SP& msg); void ProcHelperGuildMarkTable(CNetMsg::SP& msg); void ProcHelper_FriendAddRep(CNetMsg::SP& msg); void ProcHelper_FriendDelRep(CNetMsg::SP& msg); void ProcHelper_FriendSetConditionRep(CNetMsg::SP& msg); void ProcHelper_BlockPCRep(CNetMsg::SP& msg); void ProcHelper_GiftRecvChar(CNetMsg::SP& msg); void ProcHelperPetCreateRep(CNetMsg::SP& msg); void ProcHelperPetDeleteRep(CNetMsg::SP& msg); void ProcHelperPetChangeName( CNetMsg::SP& msg ); /////////////////////// // pd4 helper rep : bw void ProcHelperPD4RankViewRep(CNetMsg::SP& msg); void ProcHelperPD4RewardViewRep(CNetMsg::SP& msg); void ProcHelperPD4RewardRep(CNetMsg::SP& msg); void ProcHelperNameChange(CNetMsg::SP& msg); void ProcHelperPartyInviteReq(CNetMsg::SP& msg); void ProcHelperPartyInviteRep(CNetMsg::SP& msg); void ProcHelperPartyAllowRep(CNetMsg::SP& msg); void ProcHelperPartyRejectRep(CNetMsg::SP& msg); void ProcHelperPartyQuitRep(CNetMsg::SP& msg); void ProcHelperPartyKickRep(CNetMsg::SP& msg); void ProcHelperPartyChangeBossRep(CNetMsg::SP& msg); void ProcHelperPartyChangeTypeRep(CNetMsg::SP& msg); void ProcHelperPartyEndPartyRep(CNetMsg::SP& msg); void ProcHelperPartyMatchRegMemberRep(CNetMsg::SP& msg); void ProcHelperPartyMatchRegPartyRep(CNetMsg::SP& msg); void ProcHelperPartyMatchDelRep(CNetMsg::SP& msg); void ProcHelperPartyMatchInviteRep(CNetMsg::SP& msg); void ProcHelperPartyMatchJoinRep(CNetMsg::SP& msg); void ProcHelperPartyMatchJoinAllowRep(CNetMsg::SP& msg); void ProcHelperPartyMatchJoinRejectRep(CNetMsg::SP& msg); void ProcHelperPartyMatchMemberChangeInfo(CNetMsg::SP& msg); void ProcHelperPartyInfoParty(CNetMsg::SP& msg); void ProchelperPartyInfoPartyMatchMember(CNetMsg::SP& msg); void ProchelperPartyInfoPartyMatchParty(CNetMsg::SP& msg); void ProcHelperPartyInfoEnd(CNetMsg::SP& msg); void ProcHelperGuildInclineEstablish( CNetMsg::SP& msg ); void ProcHelperGuildMemberAdjust( CNetMsg::SP& msg ); void ProcHelperGuildInfoNotice( CNetMsg::SP& msg ); void ProcHelperNewGuildMemberListRep( CNetMsg::SP& msg ); void ProcHelperNewGuilManageRep( CNetMsg::SP& msg ); void ProcHelperNewGuildNotifyRep( CNetMsg::SP& msg ); void ProcHelperNewGuildNotifyUpdateReP( CNetMsg::SP& msg ); void ProcHelperNewGuildNotifyTrans( CNetMsg::SP& msg ); void ProcHelperNewGuildNotifyTransRepMsg( CNetMsg::SP& msg ); void ProcHelperNewGuildSkillListRepMsg( CNetMsg::SP& msg ); void ProcHelperNewGuildLoadNTF( CNetMsg::SP& msg ); void ProcHelperNewGuildMemberList( CNetMsg::SP& msg ); void ProcHelperNewGuildInfoRepMsg( CNetMsg::SP& msg ); void ProcHelperNewGuildPointUpdateMsg( CNetMsg::SP& msg ); void ProcHelperNewGuildNotice( CNetMsg::SP& msg ); void ProcHelperNewGuildMemberPointSaveMsg( CNetMsg::SP& msg ); void ProcHelperNewGuildSkillLearnSendMember( CNetMsg::SP& msg ); void ProcHelperGuildContributeSet(CNetMsg::SP& msg); void ProcHelperGuildContributeSetAll(CNetMsg::SP& msg); void ProcHelperHalloween2007( CNetMsg::SP& msg ); void ProcHelperDVDRateChange(CNetMsg::SP& msg); void ProcHelperDVDNormalChangeNotice(CNetMsg::SP& msg); void ProcHelperComboGotoWaitRoomPrompt( CNetMsg::SP& msg ); void ProcHelperComboRecallToWaitRoomPrompt(CNetMsg::SP& msg); void ProcHelperAttackPet( CNetMsg::SP& msg ); #ifdef EXTREME_CUBE void ProcHelperCubeStateRep(CNetMsg::SP& msg); void ProcHelperCubeStatePersonalRep(CNetMsg::SP& msg); void ProcHelperGuildCubeNotice(CNetMsg::SP& msg); #ifdef EXTREME_CUBE_VER2 void ProcHelperCubeRewardPersonalRep(CNetMsg::SP& msg); void ProcHelperExtremeCubeError(CNetMsg::SP& msg); void ProcHelperCubeRewardGuildPointRep(CNetMsg::SP& msg); #endif // EXTREME_CUBE_VER2 #endif // EXTREME_CUBE void ProcHelperEventPhoenix( CNetMsg::SP& msg); void ProcHelperExpedErrorRep( CNetMsg::SP& msg); void ProcHelperExped_CreateRep( CNetMsg::SP& msg); void ProcHelperExped_InviteRep( CNetMsg::SP& msg); void ProcHelperExped_AllowRep( CNetMsg::SP& msg); void ProcHelperExped_RejectRep( CNetMsg::SP& msg); void ProcHelperExped_QuitRep( CNetMsg::SP& msg); void ProcHelperExped_KickRep( CNetMsg::SP& msg); void ProcHelperExped_ChangeTypeRep( CNetMsg::SP& msg); void ProcHelperExped_ChangeBossRep( CNetMsg::SP& msg); void ProcHelperExped_SetMBossRep( CNetMsg::SP& msg); void ProcHelperExped_ResetMBossRep( CNetMsg::SP& msg); void ProcHelperExped_EndExpedRep( CNetMsg::SP& msg); void ProcHelperExped_MoveGroupRep( CNetMsg::SP& msg); void ProcHelperRaidErrorRep(CNetMsg::SP& msg); void ProcHelperInzoneGetRoomnoRep(CNetMsg::SP& msg); void ProcHelperDeleteRaidCharacterRep(CNetMsg::SP& msg); void ProcHelperRaidInfoRep(CNetMsg::SP& msg); void ProcHelperNSCreateCard(CNetMsg::SP& msg); #if defined(EVENT_WORLDCUP_2010) || defined(EVENT_WORLDCUP_2010_TOTO) || defined(EVENT_WORLDCUP_2010_TOTO_STATUS) || defined(EVENT_WORLDCUP_2010_TOTO_GIFT) || defined(EVENT_WORLDCUP_2010_ATTENDANCE) void ProcHelperWorldcup2010(CNetMsg::SP& msg); #endif // defined(EVENT_WORLDCUP_2010) || defined(EVENT_WORLDCUP_2010_TOTO_STATUS) || defined(EVENT_WORLDCUP_2010_TOTO_GIFT) || defined(EVENT_WORLDCUP_2010_ATTENDANCE) void ProcHelperTeachRenewer(CNetMsg::SP& msg); void ProcHelperTeachRenewerTimeLimit(CNetMsg::SP& msg); void ProcHelperTeachRenewerGift(CNetMsg::SP& msg); void ProcHelperFaceOff(CNetMsg::SP& msg); #ifdef EVENT_CHAR_BIRTHDAY void ProcHelperCharBirthday(CNetMsg::SP& msg); #endif #ifdef DEV_GUILD_MARK void ProcHelperGuildMarkRegist(CNetMsg::SP& msg); void ProcHelperGuildMarkExpire(CNetMsg::SP& msg); #endif #ifdef WARCASTLE_STATE_CHANNEL_CYNC void ProcHelperCastleStateCync(CNetMsg::SP& msg); #endif #ifdef DEV_GUILD_STASH void ProcHelperGuildStashList(CNetMsg::SP& msg); void ProcHelperGuildStashKeep(CNetMsg::SP& msg); void ProcHelperGuildStashTake(CNetMsg::SP& msg); void ProcHelperGuildStashLog(CNetMsg::SP& msg); void ProcHelperGuildStashError(CNetMsg::SP& msg); void LogGuildStash(CItem* pItem, const LONGLONG count, const unsigned char type, CPC* pc); #endif // DEV_GUILD_STASH void ProcHelperStudentListRefresh(CNetMsg::SP& msg); void ProcHelperTeacherStudentLsitCync(CNetMsg::SP& msg); void ProcHelperTeacherInfoSet(CPC* pc, CNetMsg::SP& msg ); void ProcHelperGuildMasterKickRep(CNetMsg::SP& msg); void ProcHelperGuildMasterKickCancelRep(CNetMsg::SP& msg); void ProcHelperGuildMasterKickStatus(CNetMsg::SP& msg); void ProcHelperGuildMasaterKickReset(CNetMsg::SP& msg); void ProcHelperRvrUpdateCreateJewelPoint(CNetMsg::SP& msg); void ProcHelperRvrUpdateJoinCount(CNetMsg::SP& msg); void ProcHelperRvRUpdateKingInfo(CNetMsg::SP& msg); void ProcHelperRVRInfoUpdate(CNetMsg::SP& msg); void ProcHelperRvRKingDownGrade( CNetMsg::SP& msg ); void ProcHelperKickUser(CNetMsg::SP& msg); void ProcHelperKickUserAnswer(CNetMsg::SP& msg); void ProcHelperKickUserByCharIndexAnswer(CNetMsg::SP& msg); void ProcHelperKickUserByUserIndexAnswer(CNetMsg::SP& msg); void ProcHelperKickUserByUserIdAnswer(CNetMsg::SP& msg); void ProcHelperGuildBattleChallenge(CNetMsg::SP& msg); void ProcHelperGuildBattleReg(CNetMsg::SP& msg); void CServer::ProcessHelperMessage(CNetMsg::SP& msg) { msg->MoveFirst(); switch (msg->m_mtype) { case MSG_HELPER_COMMAND: { int subtype; RefMsg(msg) >> subtype; //LOG_INFO("DEBUG_FUNC : START : type : %d, subtype : %d", msg->m_mtype, subtype); switch (subtype) { case MSG_HELPER_PARTY_INFO_PARTY: ProcHelperPartyInfoParty(msg); break; case MSG_HELPER_PARTY_INFO_PARTY_MATCH_MEMBER: ProchelperPartyInfoPartyMatchMember(msg); break; case MSG_HELPER_PARTY_INFO_PARTY_MATCH_PARTY: ProchelperPartyInfoPartyMatchParty(msg); break; case MSG_HELPER_PARTY_INFO_END: ProcHelperPartyInfoEnd(msg); break; case MSG_HELPER_PARTY_MATCH_MEMBER_CHANGE_INFO: ProcHelperPartyMatchMemberChangeInfo(msg); break; case MSG_HELPER_PARTY_MATCH_REG_MEMBER_REP: ProcHelperPartyMatchRegMemberRep(msg); break; case MSG_HELPER_PARTY_MATCH_REG_PARTY_REP: ProcHelperPartyMatchRegPartyRep(msg); break; case MSG_HELPER_PARTY_MATCH_DEL_REP: ProcHelperPartyMatchDelRep(msg); break; case MSG_HELPER_PARTY_MATCH_INVITE_REP: ProcHelperPartyMatchInviteRep(msg); break; case MSG_HELPER_PARTY_MATCH_JOIN_REP: ProcHelperPartyMatchJoinRep(msg); break; case MSG_HELPER_PARTY_MATCH_JOIN_ALLOW_REP: ProcHelperPartyMatchJoinAllowRep(msg); break; case MSG_HELPER_PARTY_MATCH_JOIN_REJECT_REP: ProcHelperPartyMatchJoinRejectRep(msg); break; case MSG_HELPER_PARTY_CHANGE_BOSS_REP: ProcHelperPartyChangeBossRep(msg); break; case MSG_HELPER_PARTY_CHANGE_TYPE_REP: ProcHelperPartyChangeTypeRep(msg); break; case MSG_HELPER_PARTY_END_PARTY_REP: ProcHelperPartyEndPartyRep(msg); break; case MSG_HELPER_PARTY_KICK_REP: ProcHelperPartyKickRep(msg); break; case MSG_HELPER_PARTY_QUIT_REP: ProcHelperPartyQuitRep(msg); break; case MSG_HELPER_PARTY_REJECT_REP: ProcHelperPartyRejectRep(msg); break; case MSG_HELPER_PARTY_ALLOW_REP: ProcHelperPartyAllowRep(msg); break; case MSG_HELPER_PARTY_INVITE_REP: ProcHelperPartyInviteRep(msg); break; case MSG_HELPER_PARTY_INVITE_REQ: ProcHelperPartyInviteReq(msg); break; case MSG_HELPER_GUILD_CREATE_REP: ProcHelperGuildCreateRep(msg); break; case MSG_HELPER_GUILD_CREATE_NTF: ProcHelperGuildCreateNotify(msg); break; case MSG_HELPER_GUILD_ONLINE_NTF: ProcHelperGuildOnlineNotify(msg); break; case MSG_HELPER_GUILD_MEMBER_LIST: ProcHelperGuildMemberList(msg); break; case MSG_HELPER_GUILD_LOAD_REP: ProcHelperGuildLoadRep(msg); break; case MSG_HELPER_GUILD_LEVELUP_REP: ProcHelperGuildLevelUpRep(msg); break; case MSG_HELPER_GUILD_LEVELUP_NTF: ProcHelperGuildLevelUpNotify(msg); break; case MSG_HELPER_GUILD_BREAKUP_REP: ProcHelperGuildBreakUpRep(msg); break; case MSG_HELPER_GUILD_BREAKUP_NTF: ProcHelperGuildBreakUpNotify(msg); break; case MSG_HELPER_GUILD_MEMBER_ADD_NTF: // 길드 멤버 추가 알림 ProcHelperGuildMemberAddNotify(msg); break; case MSG_HELPER_GUILD_MEMBER_ADD_REP: ProcHelperGuildMemberAddRep(msg); break; case MSG_HELPER_GUILD_MEMBER_OUT_NTF: ProcHelperGuildMemberOutNotify(msg); break; case MSG_HELPER_GUILD_MEMBER_OUT_REP: ProcHelperGuildMemberOutRep(msg); break; case MSG_HELPER_GUILD_MEMBER_KICK_REP: ProcHelperGuildMemberKickRep(msg); break; case MSG_HELPER_GUILD_MEMBER_KICK_NTF: ProcHelperGuildMemberKickNotify(msg); break; case MSG_HELPER_GUILD_CHANGE_BOSS_REP: ProcHelperGuildChangeBossRep(msg); break; case MSG_HELPER_GUILD_CHANGE_BOSS_NTF: ProcHelperGuildChangeBossNotify(msg); break; case MSG_HELPER_GUILD_APPOINT_OFFICER_REP: ProcHelperGuildAppointOfficerRep(msg); break; case MSG_HELPER_GUILD_APPOINT_OFFICER_NTF: ProcHelperGuildAppointOfficerNotify(msg); break; case MSG_HELPER_GUILD_CHAT: ProcHelperGuildChat(msg); break; case MSG_HELPER_GUILD_FIRE_OFFICER_REP: ProcHelperGuildFireOfficerRep(msg); break; case MSG_HELPER_GUILD_FIRE_OFFICER_NTF: ProcHelperGuildFireOfficerNotify(msg); break; case MSG_HELPER_GUILD_LOAD_NTF: ProcHelperGuildLoadNotify(msg); break; case MSG_HELPER_GUILD_BATTLE_REP: ProcHelperGuildBattleRep(msg); break; case MSG_HELPER_GUILD_BATTLE_START: ProcHelperGuildBattleStart(msg); break; case MSG_HELPER_GUILD_BATTLE_STOP_REP: ProcHelperGuildBattleStopRep(msg); break; case MSG_HELPER_GUILD_BATTLE_STATUS: ProcHelperGuildBattleStatus(msg); break; case MSG_HELPER_GUILD_BATTLE_PEACE_REP: ProcHelperGuildBattlePeaceRep(msg); break; case MSG_HELPER_GUILD_MARK_TABLE: ProcHelperGuildMarkTable(msg); break; //0503 kwon case MSG_HELPER_EVENT_MOONSTONE_LOAD: case MSG_HELPER_EVENT_MOONSTONE_UPDATE_REP: ProcHelperEventMoonStoneLoad(msg); break; case MSG_HELPER_EVENT_MOONSTONE_JACKPOT_REP: ProcHelperEventMoonStoneJackpot(msg); break; case MSG_HELPER_FRIEND_SET_CONDITION_NOTIFY: ProcHelper_FriendSetConditionRep(msg); break; //////////////////////// // pd4 헬퍼 rep 처리 : bw case MSG_HELPER_PD4_RANK_VIEW_REP: ProcHelperPD4RankViewRep(msg); break; case MSG_HELPER_PD4_REWARD_VIEW_REP: ProcHelperPD4RewardViewRep(msg); break; case MSG_HELPER_PD4_REWARD_REP: ProcHelperPD4RewardRep(msg); break; case MSG_HELPER_NAME_CHANGE_REP: ProcHelperNameChange(msg); break; // 애완동물 case MSG_HELPER_PET_CREATE_REP: ProcHelperPetCreateRep(msg); break; case MSG_HELPER_PET_DELETE_REP: ProcHelperPetDeleteRep(msg); break; case MSG_HELPER_PET_NAME_CHANGE: ProcHelperPetChangeName( msg ); break; case MSG_HELPER_GUILD_STASH_HISTORY_REP: ProcHelperGuildStashHistoryRep(msg); break; case MSG_HELPER_GUILD_STASH_VIEW_REP: ProcHelperGuildStashViewRep(msg); break; case MSG_HELPER_GUILD_STASH_TAKE_REP: ProcHelperGuildStashTakeRep(msg); break; case MSG_HELPER_GUILD_STASH_SAVE_TAX_REP: ProcHelperGuildStashSaveTaxRep(msg); break; case MSG_HELPER_TEACHER_FAMEUP_REP: ProcHelperFameupRep(msg); break; case MSG_HELPER_TEACHER_LOAD_REP: ProcHelperTeacherLoadRep(msg); break; case MSG_HELPER_BLOCKPC_REP: ProcHelper_BlockPCRep(msg); break; case MSG_HELPER_GIFT_RECVCHARNAME_REP: ProcHelper_GiftRecvChar(msg); break; case MSG_HELPER_GUILD_INCLINE_ESTABLISH_REP: ProcHelperGuildInclineEstablish( msg ); break; case MSG_HELPER_GUILD_MEMBER_ADJUST_REP: ProcHelperGuildMemberAdjust( msg ); break; case MSG_HELPER_NEW_GUILD_INFO_NTF: ProcHelperGuildInfoNotice( msg ); break; case MSG_HELPER_NEW_GUILD_MEMBERLIST_REP: ProcHelperNewGuildMemberListRep( msg ); break; case MSG_HELPER_NEW_GUILD_MANAGE_REP: ProcHelperNewGuilManageRep( msg ); break; case MSG_HELPER_NEW_GUILD_NOTICE_REP: ProcHelperNewGuildNotifyRep( msg ); break; case MSG_HELPER_NEW_GUILD_NOTICE_UPDATE_REP: ProcHelperNewGuildNotifyUpdateReP( msg ); break; case MSG_HELPER_NEW_GUILD_NOTICE_TRANSMISSION_NTF: ProcHelperNewGuildNotifyTrans( msg ); break; case MSG_HELPER_NEW_GUILD_NOTICE_TRANSMISSION_REP: ProcHelperNewGuildNotifyTransRepMsg( msg ); break; case MSG_HELPER_NEW_GUILD_NOTICE_SKILLLIST_REP: ProcHelperNewGuildSkillListRepMsg( msg ); break; case MSG_HELPER_NEW_GUILD_LOAD_NTF: ProcHelperNewGuildLoadNTF( msg ); break; case MSG_HELPER_NEW_GUILD_MEMBER_LIST: ProcHelperNewGuildMemberList( msg ); break; case MSG_HELPER_NEW_GUILD_INFO_REP: ProcHelperNewGuildInfoRepMsg( msg ); break; case MSG_HELPER_UPDATE_GUILD_POINT: ProcHelperNewGuildPointUpdateMsg( msg ); break; case MSG_HELPER_GUILD_NOTICE: ProcHelperNewGuildNotice( msg ); break; case MSG_HELPER_SAVE_GUILD_MEMBER_POINT: ProcHelperNewGuildMemberPointSaveMsg( msg ); break; case MSG_HELPER_GUILD_CONTRIBUTE_SET_REP: ProcHelperGuildContributeSet(msg); break; case MSG_HELPER_GUILD_CONTRIBUTE_SETALL_REP: ProcHelperGuildContributeSetAll(msg); break; case MSG_HELPER_GUILD_SKILL_LEARN_SEND_MEMBER: ProcHelperNewGuildSkillLearnSendMember( msg ); break; case MSG_HELPER_HALLOWEEN_2007: ProcHelperHalloween2007( msg ); break; case MSG_HELPER_DVD_RATE_CHANGE: ProcHelperDVDRateChange( msg ); break; case MSG_HELPER_DVD_NORMAL_CHANGE_NOTICE: ProcHelperDVDNormalChangeNotice( msg ); break; case MSG_HELPER_APET : ProcHelperAttackPet(msg); break; #ifdef EXTREME_CUBE case MSG_HELPER_CUBESTATE_REP: ProcHelperCubeStateRep(msg); break; case MSG_HELPER_CUBESTATE_PERSONAL_REP: ProcHelperCubeStatePersonalRep(msg); break; #ifdef EXTREME_CUBE_VER2 case MSG_HELPER_CUBEREWARD_GUILDPOINT_REP: ProcHelperCubeRewardGuildPointRep(msg); break; case MSG_HELPER_CUBEREWARD_PERSONAL_REP: ProcHelperCubeRewardPersonalRep(msg); break; case MSG_HELPER_EXTREME_CUBE_ERROR: ProcHelperExtremeCubeError(msg); break; #endif // EXTREME_CUBE_VER2 #endif // EXTREME_CUBE case MSG_HELPER_EVENT_PHOENIX: ProcHelperEventPhoenix(msg); break; case MSG_HELPER_EXPED_ERROR: ProcHelperExpedErrorRep(msg); break; case MSG_HELPER_EXPED_CREATE_REP: ProcHelperExped_CreateRep(msg); break; case MSG_HELPER_EXPED_INVITE_REP: ProcHelperExped_InviteRep(msg); break; case MSG_HELPER_EXPED_ALLOW_REP: ProcHelperExped_AllowRep(msg); break; case MSG_HELPER_EXPED_REJECT_REP: ProcHelperExped_RejectRep(msg); break; case MSG_HELPER_EXPED_QUIT_REP: ProcHelperExped_QuitRep(msg); break; case MSG_HELPER_EXPED_KICK_REP: ProcHelperExped_KickRep(msg); break; case MSG_HELPER_EXPED_CHANGETYPE_REP: ProcHelperExped_ChangeTypeRep(msg); break; case MSG_HELPER_EXPED_CHANGEBOSS_REP: ProcHelperExped_ChangeBossRep(msg); break; case MSG_HELPER_EXPED_SETMBOSS_REP: ProcHelperExped_SetMBossRep(msg); break; case MSG_HELPER_EXPED_RESETMBOSS_REP: ProcHelperExped_ResetMBossRep(msg); break; case MSG_HELPER_EXPED_ENDEXPED_REP: ProcHelperExped_EndExpedRep(msg); break; case MSG_HELPER_EXPED_MOVEGROUP_REP: ProcHelperExped_MoveGroupRep(msg); break; case MSG_HELPER_RAID_ERROR: ProcHelperRaidErrorRep(msg); break; case MSG_HELPER_INZONE_GET_ROOMNO_REP: ProcHelperInzoneGetRoomnoRep(msg); break; case MSG_HELPER_DELETE_RAID_CHAR: ProcHelperDeleteRaidCharacterRep(msg); break; case MSG_HELPER_RAID_INFO: ProcHelperRaidInfoRep(msg); break; case MSG_HELPER_NS_CARD: ProcHelperNSCreateCard(msg); break; #if defined(EVENT_WORLDCUP_2010) || defined(EVENT_WORLDCUP_2010_TOTO) ||defined(EVENT_WORLDCUP_2010_TOTO_STATUS) || defined(EVENT_WORLDCUP_2010_TOTO_GIFT) || defined(EVENT_WORLDCUP_2010_ATTENDANCE) || defined(EVENT_WORLDCUP_2010_KOREA) case MSG_HELPER_EVENT_WORLDCUP2010: ProcHelperWorldcup2010(msg); break; #endif // defined(EVENT_WORLDCUP_2010) || defined(EVENT_WORLDCUP_2010_TOTO_STATUS) || defined(EVENT_WORLDCUP_2010_TOTO_GIFT) || defined(EVENT_WORLDCUP_2010_ATTENDANCE) || defined(EVENT_WORLDCUP_2010_KOREA) case MSG_HELPER_TEACHER_SYSTEM_RENEWER: ProcHelperTeachRenewer(msg); break; case MSG_HELPER_FACEOFF_REP: ProcHelperFaceOff(msg); break; #ifdef EVENT_CHAR_BIRTHDAY case MSG_HELPER_CHAR_BIRTHDAY: ProcHelperCharBirthday(msg); break; #endif #ifdef DEV_GUILD_MARK case MSG_HELPER_NEW_GUILD_MARK_REGIST: ProcHelperGuildMarkRegist(msg); break; case MSG_HELPER_NEW_GUILD_MARK_EXPIRE: ProcHelperGuildMarkExpire(msg); break; #endif #ifdef DEV_GUILD_STASH case MSG_HELPER_GUILD_STASH_LIST : ProcHelperGuildStashList(msg); break; case MSG_HELPER_GUILD_STASH_KEEP : ProcHelperGuildStashKeep(msg); break; case MSG_HELPER_GUILD_STASH_TAKE : ProcHelperGuildStashTake(msg); break; case MSG_HELPER_GUILD_STASH_LOG : ProcHelperGuildStashLog(msg); break; case MSG_HELPER_GUILD_STASH_ERROR : ProcHelperGuildStashError(msg); break; /*case MSG_HELPER_GUILD_STASH_LIST_MONEY: ProcHelperGuildStashList(msg); break;*/ #endif // DEV_GUILD_STASH case MSG_HELPER_TEACHER_STUDENT_LIST_CYNC_REP: ProcHelperTeacherStudentLsitCync(msg); break; case MSG_HELPER_GUILD_MASTER_KICK_REP: ProcHelperGuildMasterKickRep(msg); break; case MSG_HELPER_GUILD_MASTER_KICK_CANCEL_REP: ProcHelperGuildMasterKickCancelRep(msg); break; case MSG_HELPER_GUILD_MASTER_KICK_STATUS: ProcHelperGuildMasterKickStatus(msg); break; case MSG_HELPER_GUILD_MASTER_KICK_RESET: ProcHelperGuildMasaterKickReset(msg); break; case MSG_HELPER_SELECT_CHARACTER: { int userIndex; LONGLONG seq; int charIndex; RefMsg(msg) >> userIndex >> seq >> charIndex; CDescriptor* desc = DescManager::instance()->getDescByUserIndex(userIndex); if (desc == NULL) break; if (desc->m_seq_index != seq) break; CGuildMember* member = gserver->m_guildlist.findmember(charIndex); if (member) { if (member->guild() == NULL) member = NULL; } desc->request_start_game_flag_ = false; DBManager::instance()->PushSelectCharacter(desc, charIndex, member); } break; } //LOG_INFO("DEBUG_FUNC : END : type : %d, subtype : %d", msg->m_mtype, subtype); } break; case MSG_HELPER_REQ: { int seq, server, subno, zone; unsigned char subtype; RefMsg(msg) >> seq >> server >> subno >> zone >> subtype; if (server != -1 && (server != gserver->m_serverno || (subno != -1 && subno != gserver->m_subno))) return ; if (zone != -1) { CZone* pZone = gserver->FindZone(zone); if (pZone == NULL) return ; } //LOG_INFO("DEBUG_FUNC : START : type : %d, subtype : %d", msg->m_mtype, subtype); switch (subtype) { case MSG_HELPER_PARTY_MEMBER_CHANGE_JOB: ProcHelperPartyMemberChangeJob(msg); break; case MSG_HELPER_PARTY_CHAT: ProcHelperPartyChat(msg); break; case MSG_HELPER_PARTY_RECALL_PROMPT: ProcHelperPartyRecallPrompt(msg); break; case MSG_HELPER_PARTY_RECALL_CONFIRM: ProcHelperPartyRecallConfirm(msg); break; case MSG_HELPER_PARTY_RECALL_PROC: ProcHelperPartyRecallProc(msg); break; case MSG_HELPER_WAR_NOTICE_END: ProcHelperWarNoticeEnd(msg); break; case MSG_HELPER_WAR_NOTICE_REMAIN_FIELD_TIME: ProcHelperWarNoticeRemainFieldTime(msg); break; case MSG_HELPER_WAR_NOTICE_START_ATTACK_CASTLE: ProcHelperWarNoticeStartAttackCastle(msg); break; case MSG_HELPER_WAR_JOIN_ATTACK_GUILD: ProcHelperWarJoinAttackGuild(msg); break; case MSG_HELPER_WAR_JOIN_DEFENSE_GUILD: ProcHelperWarJoinDefenseGuild(msg); break; case MSG_HELPER_WAR_NOTICE_START: ProcHelperWarNoticeStart(msg); break; case MSG_HELPER_WAR_NOTICE_TIME_REMAIN: ProcHelperWarNoticeTimeRemain(msg); break; case MSG_HELPER_WAR_NOTICE_TIME: ProcHelperWarNoticeTime(msg); break; case MSG_HELPER_WHISPER_REQ: ProcHelperWhisperReq(msg, seq, server, subno, zone); break; case MSG_HELPER_COMBO_GOTO_COMBO_PROMPT: ProcHelperComboGotoWaitRoomPrompt(msg); break; case MSG_HELPER_COMBO_RECALL_TO_COMBO_PROMPT: ProcHelperComboRecallToWaitRoomPrompt(msg); break; #ifdef EXTREME_CUBE case MSG_HELPER_GUILDCUBETIME_NOTICE: ProcHelperGuildCubeNotice(msg); break; #endif // EXTREME_CUBE #ifdef WARCASTLE_STATE_CHANNEL_CYNC case MSG_HELPER_WARCASTLE_STATE_CYNC: ProcHelperCastleStateCync(msg); break; #endif case MSG_HELPER_TEACH_STUDENT_LIST_SYCN: ProcHelperStudentListRefresh(msg); break; } //LOG_INFO("DEBUG_FUNC : END : type : %d, subtype : %d", msg->m_mtype, subtype); } break; case MSG_HELPER_REP: { int seq, server, subno, zone; unsigned char subtype; RefMsg(msg) >> seq >> server >> subno >> zone >> subtype; if (server != -1 && (server != gserver->m_serverno || (subno != -1 && subno != gserver->m_subno))) return ; if (zone != -1) { CZone* pZone = gserver->FindZone(zone); if (pZone == NULL) return ; } //LOG_INFO("DEBUG_FUNC : START : type : %d, subtype : %d", msg->m_mtype, subtype); switch (subtype) { case MSG_HELPER_WHISPER_REP: ProcHelperWhisperRep(msg, seq, server, subno, zone); break; case MSG_HELPER_WHISPER_NOTFOUND: ProcHelperWhisperNotfound(msg, seq, server, subno, zone); break; } //LOG_INFO("DEBUG_FUNC : END : type : %d, subtype : %d", msg->m_mtype, subtype); } break; case MSG_HELPER_COMMAND_STRUCT: { pTypeServer* p = reinterpret_cast<pTypeServer*>(msg->m_buf); int subtype = p->subType; //LOG_INFO("DEBUG_FUNC : START : type : %d, subtype : %d", msg->m_mtype, subtype); switch(p->subType) { case MSG_HELPER_RVR_RVR_INFO: ProcHelperRVRInfoUpdate(msg); break; case MSG_HELPER_KING_INFO_UPDATE_ALL: ProcHelperRvRUpdateKingInfo(msg); break; case MSG_HELPER_DOWN_GRADE: ProcHelperRvRKingDownGrade(msg); break; case MSG_HELPER_FRIEND_MEMBER_ADD_REP: ProcHelper_FriendAddRep(msg); break; case MSG_HELPER_FRIEND_MEMBER_DEL_REP: ProcHelper_FriendDelRep(msg); break; } //LOG_INFO("DEBUG_FUNC : END : type : %d, subtype : %d", msg->m_mtype, subtype); } break; case MSG_SERVER_TO_SERVER: { pTypeBase* pType = reinterpret_cast<pTypeBase*>(msg->m_buf); int subtype = pType->subType; //LOG_INFO("DEBUG_FUNC : START : type : %d, subtype : %d", msg->m_mtype, subtype); switch (pType->subType) { case MSG_SUB_SERVERTOSERVER_KICK_REQ: ProcHelperKickUser(msg); break; case MSG_SUB_SERVERTOSERVER_KICK_ANSER: ProcHelperKickUserAnswer(msg); break; case MSG_SUB_SERVERTOSERVER_KICK_BY_CHAR_INDEX_ANSWER: ProcHelperKickUserByCharIndexAnswer(msg); break; case MSG_SUB_SERVERTOSERVER_KICK_BY_USER_INDEX_ANSWER: ProcHelperKickUserByUserIndexAnswer(msg); break; case MSG_SUB_SERVERTOSERVER_KICK_BY_USER_ID_ANSER: ProcHelperKickUserByUserIdAnswer(msg); break; case MSG_SUB_GUILD_BATTLE_REG_TO_HELPER: ProcHelperGuildBattleReg(msg); break; case MSG_SUB_GUILD_BATTLE_CHALLENGE_TO_HELPER: ProcHelperGuildBattleChallenge(msg); break; default: LOG_FATAL("not found subtype[%d]", pType->subType); break; } //LOG_INFO("DEBUG_FUNC : END : type : %d, subtype : %d", msg->m_mtype, subtype); } break; #ifdef PREMIUM_CHAR case MSG_PREMIUM_CHAR: { pTypeBase* pType = reinterpret_cast<pTypeBase*>(msg->m_buf); int subtype = pType->subType; switch (subtype) { case MSG_SUB_PREMIUM_CHAR_RESET_JUMP_COUNT_TIME: { ServerToServerPacket::premiumCharResetJumpCountTime* packet = reinterpret_cast<ServerToServerPacket::premiumCharResetJumpCountTime*>(msg->m_buf); PremiumChar::setResetJumpCountTime(packet->resetTime); } break; case MSG_SUB_PREMIUM_CHAR_RESET_JUMP_COUNT: { PCManager::instance()->resetPremiumCharJumpCount(); // Helper로 부터 따로 받지 않고, 게임서버가 바로 처리함 PremiumChar::setResetJumpCountTime(gserver->getNowSecond()); } break; default: LOG_ERROR("invalid subtype - mtype : %d : subtype : %d", pType->type, pType->subType); break; } } break; #endif default: break; } } void ProcHelperNameChange(CNetMsg::SP& msg) { // TODO : BS : 길드와 캐릭터명의 길이가 달라지면 바꿔야함 char bguild; char error; CLCString name(MAX_CHAR_NAME_LENGTH + 1); int index; RefMsg(msg) >> bguild >> index >> name >> error; CPC* pc = NULL; if(bguild == 1) { pc = gserver->m_guildlist.findguild(index)->boss()->GetPC(); if( !pc ) { GAMELOG << init("CASH_ITEM_USE_ERROR-notPC") << bguild << delim << index << delim << 843 << end; return; } if(error == MSG_EX_NAMECHANGE_ERROR_SUCCESS) { // 아이템 삭제 / 서버 변수 변경 // 길드 개명카드 삭제 // 아이템 검사 CItem* item = pc->m_inventory.FindByDBIndex(843, 0, 0); if (item == NULL) { { CNetMsg::SP rmsg(new CNetMsg); NameChangeRepMsg(rmsg, MSG_EX_NAMECHANGE_ERROR_HELPER, name, bguild); SEND_Q(rmsg, pc->m_desc); } { //롤백 CNetMsg::SP rmsg(new CNetMsg); HelperNameChangeReqMsg(rmsg, 3, pc->m_guildInfo->guild()->index(), pc->m_guildInfo->guild()->name()); SEND_Q(rmsg, gserver->m_helper); } GAMELOG << init("CASH_ITEM_USE_ERROR-notItem") << bguild << delim << index << delim << 843 << end; return; } if( (item->m_itemProto->getItemFlag() & ITEM_FLAG_CASH) ) { GAMELOG << init("CASH_ITEM_USE", pc) << itemlog(item) << delim << pc->m_guildInfo->guild()->name() << delim << name << delim << end; } pc->m_guildInfo->guild()->changeName(name); pc->m_inventory.decreaseItemCount(item, 1); { CNetMsg::SP rmsg(new CNetMsg); HelperNameChangeReqMsg(rmsg, 5, pc->m_guildInfo->guild()->index(), name); SEND_Q(rmsg, gserver->m_helper); } return; } { CNetMsg::SP rmsg(new CNetMsg); NameChangeRepMsg(rmsg, (MSG_EX_NAMECHANGE_ERROR_TYPE) error, name, bguild); SEND_Q(rmsg, pc->m_desc); } } else if( bguild == 5) { CGuild* guild = gserver->m_guildlist.findguild(index); if( guild == NULL) return; guild->changeName(name); CNetMsg::SP rmsg(new CNetMsg); NameChangeRepMsg(rmsg, (MSG_EX_NAMECHANGE_ERROR_TYPE) error, name, bguild); guild->SendToAll(rmsg, true); return; } else { pc = PCManager::instance()->getPlayerByCharIndex(index); if( !pc ) { GAMELOG << init("CASH_ITEM_USE_ERROR-notPC") << bguild << delim << index << delim << 842 << end; return; } // 에러코드에 따른 메세지 작성 if(error == MSG_EX_NAMECHANGE_ERROR_SUCCESS) { // 아이템 삭제/ 서버 변수 변경 // 개명카드 삭제 // 아이템 검사 CItem* item = pc->m_inventory.FindByDBIndex(842, 0, 0); if (item == NULL) { item = pc->m_inventory.FindByDBIndex(1120, 0, 0); } if (item == NULL) { { CNetMsg::SP rmsg(new CNetMsg); NameChangeRepMsg(rmsg, MSG_EX_NAMECHANGE_ERROR_HELPER, name, bguild); SEND_Q(rmsg, pc->m_desc); } { //롤백 CNetMsg::SP rmsg(new CNetMsg); HelperNameChangeReqMsg(rmsg, 4, pc->m_index, pc->GetName()); SEND_Q(rmsg, gserver->m_helper); } GAMELOG << init("CASH_ITEM_USE_ERROR-notItem") << bguild << delim << index << delim << 842 << end; return; } if( (item->m_itemProto->getItemFlag() & ITEM_FLAG_CASH) ) { GAMELOG << init("CASH_ITEM_USE", pc) << itemlog(item) << delim << pc->GetName() << delim << name << delim << end; } pc->m_inventory.decreaseItemCount(item, 1); pc->ChangeName(name); return; } { CNetMsg::SP rmsg(new CNetMsg); NameChangeRepMsg(rmsg, (MSG_EX_NAMECHANGE_ERROR_TYPE) error, name, bguild); SEND_Q(rmsg, pc->m_desc); } } } void ProcHelperPD4RankViewRep(CNetMsg::SP& msg) { ////////////////////////////////// // 받은 데이터를 클라이언트에게 보냄 : BW //MSG_HELPER_PD4_RANK_VIEW_REQ, // : charindex(n) charjob(c) //MSG_HELPER_PD4_RANK_VIEW_REP : charindex(n) multicount(c), charname(str), bclear(c), deadmon(n), ctime(ll); int charindex; char multicount; CLCString charname(MAX_CHAR_NAME_LENGTH + 1); char bclear; int deadmon; LONGLONG ctime; #ifdef NPC_CHECK int npcIndex; #endif if( !msg->CanRead() ) { return; } RefMsg(msg) >> charindex #ifdef NPC_CHECK >> npcIndex #endif >> multicount; CPC* ch = PCManager::instance()->getPlayerByCharIndex(charindex); if( !ch ) return; { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_QUEST); RefMsg(rmsg) << (unsigned char) MSG_QUEST_PD4_RANK_VIEW_REP #ifdef NPC_CHECK << npcIndex #endif << multicount; if(multicount == 0) { SEND_Q(rmsg, ch->m_desc); return; } for(int i = 0; i < multicount; i++) { RefMsg(msg) >> charname >> bclear >> deadmon >> ctime; RefMsg(rmsg) << charname << bclear << deadmon << ctime; } SEND_Q(rmsg, ch->m_desc); } //MSG_QUEST_PD4_RANK_VIEW_REP, // 랭크 뷰응답 : multicount(c) charname(str) bclear(c) deadmon(n) time(ll) } void ProcHelperPD4RewardViewRep(CNetMsg::SP& msg) { ////////////////////////////////// // 받은 데이터를 클라이언트에게 보냄 //MSG_HELPER_PD4_REWARD_VIEW_REQ, // : charindex(n) charjob(c) //MSG_HELPER_PD4_REWARD_VIEW_REP : charindex(n) multicount(c), charname(str) breward(c) int charindex; char multicount; CLCString charname(MAX_CHAR_NAME_LENGTH + 1); int itemindex[5] = { 85, 85, 85, 673, 673 }; char itemnum[5] = { 3, 2, 1, 3, 1 }; char breward; #ifdef NPC_CHECK int npcIndex; #endif if( !msg->CanRead() ) { return; } #ifdef NPC_CHECK RefMsg(msg) >> charindex >> npcIndex >> multicount; #else RefMsg(msg) >> charindex >> multicount; #endif CPC* ch = PCManager::instance()->getPlayerByCharIndex(charindex); if( !ch ) return; if(multicount == 0) { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_QUEST); RefMsg(rmsg) << (unsigned char) MSG_QUEST_PD4_RANK_REWARD_RANK_REP #ifdef NPC_CHECK << npcIndex #endif << (char) 0; SEND_Q(rmsg, ch->m_desc); return; } { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_QUEST); RefMsg(rmsg) << (unsigned char) MSG_QUEST_PD4_RANK_REWARD_RANK_REP #ifdef NPC_CHECK << npcIndex #endif << multicount; for(int i = 0; i < multicount; i++) { RefMsg(msg) >> charname >> breward; RefMsg(rmsg) << charname << itemindex[i] << itemnum[i] << breward; } SEND_Q(rmsg, ch->m_desc); } //MSG_QUEST_PD4_RANK_REWARD_RANK_REP, // 보상 뷰응답 : multicount(c) charname(str) itemindex(n) itemnum(c) breward(c) } void ProcHelperPD4RewardRep(CNetMsg::SP& msg) { ////////////////////////////////// // 받은 데이터를 클라이언트에게 보냄 //MSG_HELPER_PD4_REWARD_REQ : charindex(n) //MSG_HELPER_PD4_REWARD_REP : charindex(n) charrank(c) breward(c) int itemindex[5] = { 85, 85, 85, 673, 673 }; char itemnum[5] = { 3, 2, 1, 3, 1 }; int charindex; char charrank; char breward; int npcIndex; if(!msg->CanRead()) { GAMELOG << init("Quest reward Error"); return; } RefMsg(msg) >> charindex >> charrank >> breward >> npcIndex; CPC* ch = PCManager::instance()->getPlayerByCharIndex(charindex); if( !ch) { GAMELOG << init("PD4_REWARD_ERROR") << charindex << delim << charrank << delim << breward << end; return; } if(!charrank) { ////////////////////////// // 랭커가 아니다 CNetMsg::SP rmsg(new CNetMsg); QuestPD4ErrorMsg(rmsg, MSG_QUEST_ERR_REWARD_NOT_RANK); GAMELOG << init("QuestPD4Error Reward Not Rank", ch) << end; SEND_Q(rmsg, ch->m_desc); return; } if(breward) { //////////////////////////////////////////// // 이미 보상 받았으 CNetMsg::SP rmsg(new CNetMsg); QuestPD4ErrorMsg(rmsg, MSG_QUEST_ERR_BREWARD); GAMELOG << init("QuestPD4Error Reward Not Rank", ch) << end; SEND_Q(rmsg, ch->m_desc); return; } CItem* item = gserver->m_itemProtoList.CreateItem(itemindex[charrank - 1], -1, 0, 0, itemnum[charrank - 1]); if (!item) { ////////////////////////////// // item 생성 실패 return; } if(item->IsAccessary() && item->m_nOption < 1) { OptionSettingItem(ch, item); } if (ch->m_inventory.addItem(item) == false) { // 인젠토리 꽉차서 못 받을 때 // Quest Error Log GAMELOG << init("QUEST ERROR", ch) << 105 << delim << (int)MSG_QUEST_ERR_PRIZE_FULL << end; // 인벤토리 가득참 item = ch->m_pArea->DropItem(item, ch); if (!item) { ///////////////// // item drop 실패 return; } { CNetMsg::SP rmsg(new CNetMsg); item->m_preferenceIndex = ch->m_index; ItemDropMsg(rmsg, ch, item); ch->m_pArea->SendToCell(rmsg, ch, true); } { CNetMsg::SP rmsg(new CNetMsg); QuestErrorMsg(rmsg, MSG_QUEST_ERR_PRIZE_FULL); SEND_Q(rmsg, ch->m_desc); } return; } { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_QUEST); RefMsg(rmsg) << (unsigned char) MSG_QUEST_PD4_REWARD; RefMsg(rmsg) << npcIndex; SEND_Q(rmsg, ch->m_desc); } // Item LOG GAMELOG << init("ITEM_PICK_REWARD_PD4", ch) << itemlog(item) << end; // Quest Prize Log GAMELOG << init("QUEST PRIZE", ch) << 105 << delim << QPRIZE_ITEM << delim << itemindex[charrank-1] << delim << itemnum[charrank-1] << end; //MSG_QUEST_PD4_REWARD_REP, // 보상 요청 : charindex(n) } void ProcHelperWhisperReq(CNetMsg::SP& msg, int seq, int server, int subno, int zone) { int sidx; CLCString sname(MAX_CHAR_NAME_LENGTH + 1); CLCString rname(MAX_CHAR_NAME_LENGTH + 1); CLCString chat(1000); RefMsg(msg) >> sidx >> sname >> rname >> chat; CPC* receiver = PCManager::instance()->getPlayerByName(rname, true); if (receiver == NULL) { // 수신자가 없을 때 CNetMsg::SP rmsg(new CNetMsg); HelperRepWhisperNotFoundMsg(rmsg, seq, server, subno, zone, sidx, sname); SEND_Q(rmsg, gserver->m_helper); } else { { // 수신자가 있을 때 CNetMsg::SP rmsg(new CNetMsg); ChatWhisperMsg(rmsg, sidx, sname, receiver->GetName(), chat); SEND_Q(rmsg, receiver->m_desc); } { // 메신저에 응답 보내기 CNetMsg::SP rmsg(new CNetMsg); HelperRepWhisperRepMsg(rmsg, seq, server, subno, zone, sidx, sname, receiver->GetName() , chat); SEND_Q(rmsg, gserver->m_helper); } } } void ProcHelperWhisperRep(CNetMsg::SP& msg, int seq, int server, int subno, int zone) { int sidx, ridx; CLCString sname(MAX_CHAR_NAME_LENGTH + 1); CLCString rname(MAX_CHAR_NAME_LENGTH + 1); CLCString chat(1000); RefMsg(msg) >> sidx >> sname >> ridx >> rname >> chat; CPC* sender = PCManager::instance()->getPlayerByCharIndex(sidx); if (sender != NULL) { // 송신자가 있으면 CNetMsg::SP rmsg(new CNetMsg); ChatWhisperMsg(rmsg, sidx, sname, rname, chat); SEND_Q(rmsg, sender->m_desc); } } void ProcHelperWhisperNotfound(CNetMsg::SP& msg, int seq, int server, int subno, int zone) { int sidx; CLCString sname(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> sidx >> sname; CPC* sender = PCManager::instance()->getPlayerByCharIndex(sidx); if (sender != NULL) { // 송신자가 있으면 오류 알림 CNetMsg::SP rmsg(new CNetMsg); SysWhisperNotFoundMsg(rmsg); SEND_Q(rmsg, sender->m_desc); } } void ProcHelperGuildCreateRep(CNetMsg::SP& msg) { int charindex; unsigned char errcode; RefMsg(msg) >> charindex >> errcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (!pc) { return ; } if (errcode == MSG_GUILD_ERROR_OK) { if (pc->m_inventory.getMoney() >= GUILD_LEVEL1_NEED_MONEY) { pc->m_inventory.decreaseMoney(GUILD_LEVEL1_NEED_MONEY); } pc->m_skillPoint -= GUILD_LEVEL1_NEED_SP * 10000; pc->CalcStatus(true); { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_CREATE_OK); SEND_Q(rmsg, pc->m_desc); } } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperGuildCreateNotify(CNetMsg::SP& msg) { int guildindex; int guildlevel; CLCString guildname(MAX_GUILD_NAME_LENGTH + 1); int bossindex; CLCString bossname(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> guildindex >> guildlevel >> guildname >> bossindex >> bossname; CGuild* guild = gserver->m_guildlist.create(guildindex, guildname, bossindex, bossname, gserver->m_nowseconds, 0, 0, 0); if (!guild) { return ; } guild->level(guildlevel); guild->setMaxmember( GUILD_LEVEL1_MAX_MEMBER ); guild->incline( 0 ); guild->guildPointRanking( 0 ); gserver->m_guildlist.add(guild); // 보스가 있으면 알리기 CPC* pc = PCManager::instance()->getPlayerByCharIndex(bossindex); if (pc) { guild->findmember(bossindex)->online(1); guild->findmember(bossindex)->SetPC(pc); { CNetMsg::SP rmsg(new CNetMsg); GuildInfoMsg(rmsg, pc); SEND_Q(rmsg, pc->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); GuildListMsg(rmsg, pc); SEND_Q(rmsg, pc->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); GuildInfoChangeMsg(rmsg, pc->m_index, guildindex, guildname, MSG_GUILD_POSITION_BOSS, pc); pc->m_pArea->SendToCell(rmsg, pc, false); } { CNetMsg::SP rmsg(new CNetMsg); GuildPointRankingMsg( rmsg, pc->m_index, guildindex, guild->GetGuildPointRanking() ); SEND_Q(rmsg, pc->m_desc); pc->m_pArea->SendToCell( rmsg,pc, false ); } } GAMELOG << init("GUILD CREATE") << "INDEX" << delim << guild->index() << delim << "NAME" << delim << guild->name() << delim << "BOSS" << delim << guild->boss()->charindex() << delim << guild->boss()->GetName() << end; } void ProcHelperGuildOnlineNotify(CNetMsg::SP& msg) { int guildindex; int charindex; char online; RefMsg(msg) >> guildindex >> charindex >> online; int zoneindex; RefMsg(msg) >> zoneindex; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; CGuildMember* member = guild->findmember(charindex); if (!member) return ; member->online(online); member->zoneindex( zoneindex ); member->SetPC(NULL); if (online) { CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (pc) { member->SetPC(pc); CNetMsg::SP rmsg(new CNetMsg); HelperGuildLoadReq(rmsg, charindex ); SEND_Q(rmsg, gserver->m_helper); } } // 길드원에게 알려주기 // TODO : GUILD : 트리 구조에 전달하게 될 경우 변경 { CNetMsg::SP rmsg(new CNetMsg); GuildOnlineMsg(rmsg, member); guild->SendToAll(rmsg); } } void ProcHelperGuildMemberList(CNetMsg::SP& msg) { int guildindex; int count; int charindex; CLCString charname(MAX_CHAR_NAME_LENGTH + 1); int pos; char online; RefMsg(msg) >> guildindex >> count; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; int i; for (i = 0; i < count; i++) { RefMsg(msg) >> charindex >> charname >> pos >> online; int listindex = guild->addmember(charindex, charname); if (listindex == -1) continue ; switch (pos) { case MSG_GUILD_POSITION_BOSS: guild->changeboss(listindex); break; case MSG_GUILD_POSITION_OFFICER: guild->appoint(listindex); break; } CGuildMember* member = guild->member(listindex); if (!member) continue ; member->online(online); switch( pos ) { case MSG_GUILD_POSITION_RUSH_CAPTAIN: // 돌격조 대장 case MSG_GUILD_POSITION_SUPPORT_CAPTAIN: // 지원조 대장 case MSG_GUILD_POSITION_RECON_CAPTAIN: // 정찰조 대장 case MSG_GUILD_POSITION_RUSH_MEMBER: // 돌격조원 case MSG_GUILD_POSITION_SUPPORT_MEMBER: // 지원조원 case MSG_GUILD_POSITION_RECON_MEMBER: // 정찰조원 case MSG_GUILD_POSITION_MEMBER: // 일반 길드원 member->pos(pos); break; } guild->AddGradeExPosCount(pos); CPC* pc = PCManager::instance()->getPlayerByCharIndex(member->charindex()); if (pc) { member->online(1); member->SetPC(pc); CNetMsg::SP rmsg(new CNetMsg); HelperGuildOnline(rmsg, member); RefMsg(rmsg) << member->GetZoneNum(); SEND_Q(rmsg, gserver->m_helper); } else member->SetPC(NULL); } } void ProcHelperGuildLoadRep(CNetMsg::SP& msg) { CLCString idname(MAX_ID_NAME_LENGTH + 1); int charindex; unsigned char errcode; RefMsg(msg) >> idname >> charindex >> errcode; } void ProcHelperGuildLevelUpRep(CNetMsg::SP& msg) { int guildindex; int charindex; unsigned char errcode; RefMsg(msg) >> guildindex >> charindex >> errcode; CGuild* guild = gserver->m_guildlist.findguild(guildindex); CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (!guild) { return ; } if (errcode == MSG_GUILD_ERROR_OK) { int needlevel = 0x7fffffff; LONGLONG needmoney = 0x7fffffff; int needsp = 0x7fffffff; int needgp = 0x7fffffff; if( guild->level() < GUILD_EXTEND_BASE_LEVEL ) { switch (guild->level()) { case 2: needlevel = GUILD_LEVEL2_NEED_LEVEL; needmoney = GUILD_LEVEL2_NEED_MONEY; needsp = GUILD_LEVEL2_NEED_SP; break; case 3: needlevel = GUILD_LEVEL3_NEED_LEVEL; needmoney = GUILD_LEVEL3_NEED_MONEY; needsp = GUILD_LEVEL3_NEED_SP; break; case 4: needlevel = GUILD_LEVEL4_NEED_LEVEL; needmoney = GUILD_LEVEL4_NEED_MONEY; needsp = GUILD_LEVEL4_NEED_SP; break; case 5: needlevel = GUILD_LEVEL5_NEED_LEVEL; needmoney = GUILD_LEVEL5_NEED_MONEY; needsp = GUILD_LEVEL5_NEED_SP; break; case 6: needlevel = GUILD_LEVEL6_NEED_LEVEL; needmoney = GUILD_LEVEL6_NEED_MONEY; needsp = GUILD_LEVEL6_NEED_SP; break; } } else if( guild->level() >= GUILD_EXTEND_BASE_LEVEL ) { if( guild->level() > 6 && guild->level() < 11 ) needlevel = GUILD_LEVEL7_NEED_LEVEL; else if( guild->level() > 10 && guild->level() < 20 ) needlevel = GUILD_LEVEL7_NEED_LEVEL + 10; else if( guild->level() > 19 && guild->level() < 30 ) needlevel = GUILD_LEVEL7_NEED_LEVEL + 20; else if( guild->level() > 29 && guild->level() < 40 ) needlevel = GUILD_LEVEL7_NEED_LEVEL + 30; else if( guild->level() > 39 && guild->level() < 50 ) needlevel = GUILD_LEVEL7_NEED_LEVEL + 40; else needlevel = GUILD_LEVEL7_NEED_LEVEL + 50; int gap = guild->level() - GUILD_EXTEND_BASE_LEVEL; // 이미렙업한 상태 if( gap >= 0 ) { needmoney = (LONGLONG)( GUILD_LEVEL7_NEED_MONEY * pow(1.09, gap) ); needsp = (int)( GUILD_LEVEL7_NEED_SP * pow(1.09, gap) ); needgp = (int)( GUILD_LEVEL7_NEED_GP * pow(1.09, gap) ); } else { needmoney = GUILD_LEVEL7_NEED_MONEY; needsp = GUILD_LEVEL7_NEED_SP; needgp = GUILD_LEVEL7_NEED_GP; } } int guildmaxmember = 0; switch( guild->level()) { case 2: guildmaxmember = GUILD_LEVEL2_MAX_MEMBER; break; case 3: guildmaxmember = GUILD_LEVEL3_MAX_MEMBER; break; case 4: guildmaxmember = GUILD_LEVEL4_MAX_MEMBER; break; case 5: guildmaxmember = GUILD_LEVEL5_MAX_MEMBER; break; case 6: guildmaxmember = GUILD_LEVEL6_MAX_MEMBER; break; default : { int gap = guild->level() - GUILD_EXTEND_BASE_LEVEL; if( gap >= 0 ) { if( guild->m_passiveSkillList.Find( 444 ) ) { CSkill* skill = guild->m_passiveSkillList.Find( 444 ); if(skill->m_level <= 5) guildmaxmember = GUILD_LEVEL6_MAX_MEMBER + (5 * skill->m_level ); else guildmaxmember = 55 + 9 * (skill->m_level - 5); } else { guildmaxmember = GUILD_LEVEL6_MAX_MEMBER; } } } break; } guild->setMaxmember( guildmaxmember ); if( guild->GetGuildPoint() > needgp ) { guild->AddGuildPoint( -needgp ); } GAMELOG << init("GUILD LEVEL UP") << "Guild Max Member" << delim << guild->maxmember() << delim << "Guild Point" << delim << guild->GetGuildPoint() << end; if(pc) { if (pc->m_inventory.getMoney() >= needmoney) { pc->m_inventory.decreaseMoney(needmoney); } pc->m_skillPoint -= needsp * 10000; pc->CalcStatus(true); { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_LEVELUP_OK); GAMELOG << init("GUILD LEVEL UP ", pc ) << "Guild Index" << delim << guild->index() << delim << "NAS" << delim << needmoney << delim << "SP" << delim << pc->m_skillPoint << delim << "Need SP" << delim << needsp * 10000 << delim << "Guild Point" << delim << guild->GetGuildPoint() << delim << "Need GP" << delim << needgp << delim << end; SEND_Q(rmsg, pc->m_desc); } } } else { if(pc) { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } } } void ProcHelperGuildLevelUpNotify(CNetMsg::SP& msg) { int guildindex; int guildlevel; RefMsg(msg) >> guildindex >> guildlevel; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (guild) { guild->level(guildlevel); // TODO : GUILD : 트리 구성시 전체에 알리기 CNetMsg::SP rmsg(new CNetMsg); GuildLevelInfoMsg(rmsg, guildindex, guildlevel); guild->SendToAll(rmsg); GAMELOG << init("GUILD LEVELUP") << "INDEX" << delim << guild->index() << delim << "NAME" << delim << guild->name() << delim << "LEVEL" << delim << guild->level() << end; } } void ProcHelperGuildBreakUpRep(CNetMsg::SP& msg) { int charindex; unsigned char errcode; RefMsg(msg) >> charindex >> errcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (pc) { CNetMsg::SP rmsg(new CNetMsg); if (errcode == MSG_GUILD_ERROR_OK) GuildErrorMsg(rmsg, MSG_GUILD_ERROR_BREAKUP_OK); else GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperGuildBreakUpNotify(CNetMsg::SP& msg) { int guildindex; RefMsg(msg) >> guildindex; // 길드 삭제시 소유 성 정보 초기화 및 용병신청 초기화 CWarCastle::DeleteGuild(guildindex); // TODO : GUILD : 트리 안에 모두 알리기 CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; guild->guildPointRanking( 0 ); GAMELOG << init("GUILD BREAKUP") << "INDEX" << delim << guild->index() << delim << "NAME" << delim << guild->name() << end; { CNetMsg::SP rmsg(new CNetMsg); GuildBreakUpNotifyMsg(rmsg, guild->index(), guild->name()); PCManager::instance()->sendToAll(rmsg); } std::vector<CPC*> _vec; for (int i = 0; i < GUILD_MAX_MEMBER; i++) { if (guild->m_member[i] != NULL) { if (guild->m_member[i]->GetPC() != NULL && guild->m_member[i]->online() == 1 // 온라인 상태인 경우 && guild->m_member[i]->GetPC()->m_desc != NULL) // 디스크립터가 존재 하는 경우 { _vec.push_back(guild->m_member[i]->GetPC()); } } } #ifdef EXTREME_CUBE if(guild->m_cubeUniqueIdx != -1) { CCubeMemList* memlist; memlist = gserver->m_extremeCube.FindMemList(guild); if(memlist) { ((CGuildCubeMemList*)memlist)->SetGuild(NULL); } } #endif // EXTREME_CUBE gserver->m_guildlist.Remove(guild); std::vector<CPC*>::iterator it = _vec.begin(); std::vector<CPC*>::iterator it_end = _vec.end(); for(; it != it_end; it++) { (*it)->CalcStatus(true); } } void ProcHelperGuildMemberAddNotify(CNetMsg::SP& msg) { int guildindex; int charindex; CLCString charname(MAX_CHAR_NAME_LENGTH + 1); int pos; RefMsg(msg) >> guildindex >> charindex >> charname >> pos; int zoneindex; RefMsg(msg) >> zoneindex; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if(!guild) { return; } int listindex = guild->addmember(charindex, charname); if(listindex == -1) { return; } CGuildMember * member = guild->member(listindex); if(!member) { return; } member->online(0); member->zoneindex(zoneindex); member->SetContributeExp_min(guild->m_guild_contribute_all_exp_min); member->SetContributeExp_max(guild->m_guild_contribute_all_exp_max); member->SetContributeFame_min(guild->m_guild_contribute_all_fame_min); member->SetContributeFame_max(guild->m_guild_contribute_all_fame_max); { // 길드원 전부에게 추가 메세지 // 071210 kjban edit CNetMsg::SP rmsg(new CNetMsg); GuildMemberAddMsg(rmsg, guildindex, charindex, charname); guild->SendToAll(rmsg); } CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if(!pc) { // 혀해당 게임 채널에 캐릭이 없는 경우 아래 과정 생략 return; } member->online(1); member->SetPC(pc); time_t t; member->GetPC()->m_guild_in_date = time(&t) / 60 / 60 / 24; { CNetMsg::SP rmsg(new CNetMsg); GuildInfoMsg(rmsg, pc); SEND_Q(rmsg, pc->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); GuildListMsg(rmsg, pc); SEND_Q(rmsg, pc->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); HelperGuildOnline(rmsg, member); RefMsg(rmsg) << zoneindex; SEND_Q(rmsg, gserver->m_helper); } { CNetMsg::SP rmsg(new CNetMsg); GuildInfoChangeMsg(rmsg, charindex, guildindex, guild->name(), member->pos(), pc); pc->m_pArea->SendToCell(rmsg, pc, false); } #ifdef GMTOOL if(pc->m_bGmMonitor) { guild->m_bGmtarget = true; } #endif // GMTOOL GAMELOG << init("GUILD MEMBER ADD") << "GUILD" << delim << guild->index() << delim << guild->name() << delim << "MEMBER" << delim << member->charindex() << delim << member->GetName() << delim << end; } void ProcHelperGuildMemberAddRep(CNetMsg::SP& msg) { int guildindex; int bossindex; int charindex; unsigned char errcode; RefMsg(msg) >> guildindex >> bossindex >> charindex >> errcode; CPC* boss = PCManager::instance()->getPlayerByCharIndex(bossindex); CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (pc) { { CNetMsg::SP rmsg(new CNetMsg); if (errcode == MSG_GUILD_ERROR_OK) GuildErrorMsg(rmsg, MSG_GUILD_ERROR_REGIST_OK); else GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } pc->m_regGuild = 0; { CNetMsg::SP rmsg(new CNetMsg); GuildNameColorStateMsg( rmsg, pc ); SEND_Q( rmsg , pc->m_desc ); } // 가입한 길드에 공성전 정보가 있을경우 캐릭터에 공성정보 저장 CDratanCastle * pCastle = CDratanCastle::CreateInstance(); if( pCastle->IsAttackGuild(guildindex) ) { pc->SetJoinFlag(ZONE_DRATAN, WCJF_ATTACK_GUILD); } else if( pCastle->IsDefenseGuild(guildindex) ) { pc->SetJoinFlag(ZONE_DRATAN, WCJF_DEFENSE_GUILD); } else if( pCastle->GetOwnerGuildIndex() == guildindex ) { pc->SetJoinFlag(ZONE_DRATAN, WCJF_OWNER); } } if (boss) { boss->m_regGuild = 0; } if(pc != NULL) pc->CalcStatus(true); } void ProcHelperGuildMemberOutNotify(CNetMsg::SP& msg) { int guildindex; int charindex; CLCString name(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> guildindex >> charindex >> name; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; CGuildMember* member = guild->findmember(charindex); if (!member) return ; { CNetMsg::SP rmsg(new CNetMsg); GuildMemberOutMsg(rmsg, guildindex, charindex, member->GetName()); guild->SendToAll(rmsg); } if (member->GetPC()) { CNetMsg::SP rmsg(new CNetMsg); GuildInfoChangeMsg(rmsg, member->charindex(), -1, "", MSG_GUILD_POSITION_UNKNOWN, member->GetPC()); member->GetPC()->m_pArea->SendToCell(rmsg, member->GetPC(), false); } #ifdef GMTOOL if(member->GetPC() && member->GetPC()->m_bGmMonitor) { guild->m_bGmtarget = false; } #endif // GMTOOL guild->DelGradeExPosCount( member->pos() ); if( member->GetPC() ) member->GetPC()->CureGuildGradeSkill(); if(member->GetPC()) { member->GetPC()->CastllanTitleDelete( -1, true ); member->GetPC()->m_inventory.CastllanItemRemove(-1, false, true); // 옷만 벚긴다. } /*#ifdef EXTREME_CUBE if(member->GetPC() && member->GetPC()->m_pZone != NULL && member->GetPC()->m_pZone->IsExtremeCube()) { CCubeMemList* memlist; memlist = gserver->m_extremeCube.FindMemList(guild); if(memlist) { int zone = ZONE_MERAC; int extra = 0; int i; CZone* pZone; i = gserver->FindZone(zone); pZone = gserver->m_zones + i; if(member->GetPC()) { CPC* pc = member->GetPC(); GoZone(pc, pZone->m_index, pZone->m_zonePos[extra][0], // ylayer GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); // z } } } #endif // EXTREME_CUBE*/ GAMELOG << init("GUILD MEMBER OUT") << "GUILD" << delim << guild->index() << delim << guild->name() << delim << "MEMBER" << delim << member->charindex() << delim << member->GetName() << end; CPC* pc = member->GetPC(); guild->removemember(member); if(pc != NULL) pc->CalcStatus(true); } void ProcHelperGuildMemberOutRep(CNetMsg::SP& msg) { int guildindex; int charindex; unsigned char errcode; RefMsg(msg) >> guildindex >> charindex >> errcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (pc) { { CNetMsg::SP rmsg(new CNetMsg); if (errcode == MSG_GUILD_ERROR_OK) { CGuild * guild = gserver->m_guildlist.findguild(guildindex); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_OUT_OK, guild); } else { GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); } SEND_Q(rmsg, pc->m_desc); } // 캐릭터에 공성정보 삭제 pc->SetJoinFlag(ZONE_DRATAN, WCJF_NONE); ///=== 메라크? #ifdef EXTREME_CUBE if(pc && pc->m_pZone != NULL && pc->m_pZone->IsExtremeCube()) { #ifdef BUGFIX_CUBE_DELETE_MEMLIST CCubeMemList* memlist; if(gserver->m_extremeCube.IsGuildCubeTime()) { CGuild * guild = gserver->m_guildlist.findguild(guildindex); if(guild) { memlist = gserver->m_extremeCube.FindMemList(guild); if(memlist) { ((CGuildCubeMemList*)memlist)->DelPC(pc); GAMELOG << init("CUBE MEMBER DELETE", pc) << end; } } } #endif // BUGFIX_CUBE_DELETE_MEMLIST CZone* pZone = gserver->FindZone(ZONE_MERAC); if (pZone == NULL) return; int extra = 0; GoZone(pc, pZone->m_index, pZone->m_zonePos[extra][0], // ylayer GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); // z } #endif // EXTREME_CUBE if(pc && pc->m_pZone != NULL && pc->m_pZone->IsGuildRoom()) { CZone* pZone = gserver->FindZone(ZONE_START); if (pZone == NULL) return; GoZone(pc, ZONE_START, pZone->m_zonePos[0][0], // ylayer GetRandom(pZone->m_zonePos[0][1], pZone->m_zonePos[0][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[0][2], pZone->m_zonePos[0][4]) / 2.0f); // z } } } void ProcHelperGuildMemberKickRep(CNetMsg::SP& msg) { int guildindex; int bossindex; int charindex; unsigned char errcode; RefMsg(msg) >> guildindex >> bossindex >> charindex >> errcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex(bossindex); if (pc) { { CNetMsg::SP rmsg(new CNetMsg); if (errcode == MSG_GUILD_ERROR_OK) { CGuild * guild = gserver->m_guildlist.findguild(guildindex); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_KICK_OK, guild); } else GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } #ifdef EXTREME_CUBE if(pc && pc->m_pZone != NULL && pc->m_pZone->IsExtremeCube()) { #ifdef BUGFIX_CUBE_DELETE_MEMLIST CCubeMemList* memlist; if(gserver->m_extremeCube.IsGuildCubeTime()) { CGuild * guild = gserver->m_guildlist.findguild(guildindex); if(guild) { memlist = gserver->m_extremeCube.FindMemList(guild); if(memlist) { ((CGuildCubeMemList*)memlist)->DelPC(pc); GAMELOG << init("CUBE MEMBER DELETE", pc) << end; } } } #endif // BUGFIX_CUBE_DELETE_MEMLIST CZone* pZone = gserver->FindZone(ZONE_MERAC); if (pZone == NULL) return; int extra = 0; GoZone(pc, pZone->m_index, pZone->m_zonePos[extra][0], // ylayer GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); // z } #endif // EXTREME_CUBE CPC* kickpc = PCManager::instance()->getPlayerByCharIndex(charindex); if(kickpc && kickpc->m_pZone != NULL && kickpc->m_pZone->IsGuildRoom()) { CZone* pZone = gserver->FindZone(ZONE_START); if (pZone == NULL) return; GoZone(kickpc, ZONE_START, pZone->m_zonePos[0][0], // ylayer GetRandom(pZone->m_zonePos[0][1], pZone->m_zonePos[0][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[0][2], pZone->m_zonePos[0][4]) / 2.0f); // z } } } void ProcHelperGuildMemberKickNotify(CNetMsg::SP& msg) { int guildindex; int bossindex; int charindex; RefMsg(msg) >> guildindex >> bossindex >> charindex; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; CGuildMember* member = guild->findmember(charindex); if (!member) return ; { CNetMsg::SP rmsg(new CNetMsg); GuildMemberKickMsg(rmsg, guildindex, bossindex, charindex, member->GetName()); guild->SendToAll(rmsg); } GAMELOG << init("GUILD MEMBER KICK") << "GUILD" << delim << guild->index() << delim << guild->name() << delim << "MEMBER" << delim << member->charindex() << delim << member->GetName() << end; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (pc) { { CNetMsg::SP rmsg(new CNetMsg); GuildInfoChangeMsg(rmsg, charindex, -1, "", MSG_GUILD_POSITION_UNKNOWN, pc); pc->m_pArea->SendToCell(rmsg, pc, false); } #ifdef GMTOOL if(pc->m_bGmMonitor) { guild->m_bGmtarget = false; } #endif // GMTOOL if( guild->level() > MANAGE_NEED_LEVEL ) { if( gserver->isRunHelper() ) { if(pc->m_guildInfo && pc->m_guildInfo->guild()) { CNetMsg::SP rmsg(new CNetMsg); HelperNewGuildManage( rmsg, pc ); SEND_Q( rmsg, gserver->m_helper ); } } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_GAMESERVER); SEND_Q(rmsg, pc->m_desc); } } // 캐릭터에 공성정보 삭제 pc->SetJoinFlag(ZONE_DRATAN, WCJF_NONE); ///=== 메라크? #ifdef EXTREME_CUBE if(pc->m_pZone != NULL && pc->m_pZone->IsExtremeCube()) { CCubeMemList* memlist; memlist = gserver->m_extremeCube.FindMemList(guild); if(memlist) { CZone* pZone = gserver->FindZone(ZONE_MERAC); if (pZone == NULL) return; int extra = 0; GoZone(pc, pZone->m_index, pZone->m_zonePos[extra][0], // ylayer GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); // z } } #endif // EXTREME_CUBE } #ifdef GUILD_MEMBER_KICK_JOIN_DELAY // 핼퍼를 통해서 업데이트 해주자. else if(!pc) { time_t t; int outdate = time(&t) / 60 / 60 / 24; CNetMsg::SP rmsg(new CNetMsg); HelperGuildKickOutDateUpdateReqMsg(rmsg, charindex, outdate); SEND_Q(rmsg, gserver->m_helper); } #endif // GUILD_MEMBER_KICK_JOIN_DELAY guild->DelGradeExPosCount( member->pos() ); if( member->GetPC() ) member->GetPC()->CureGuildGradeSkill(); if(member->GetPC()) { member->GetPC()->CastllanTitleDelete( -1, true ); member->GetPC()->m_inventory.CastllanItemRemove(-1, false, true); // 옷만 벚긴다. } guild->removemember(member); if(pc != NULL) { pc->m_guild_in_date = 0; pc->CalcStatus(true); } } void ProcHelperGuildChangeBossNotify(CNetMsg::SP& msg) { int guildindex; int current; int change; RefMsg(msg) >> guildindex >> current >> change; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; CGuildMember* member = guild->findmember(change); if (!member) return ; // << kjban // GAMELOG << init("GUILD CHANGE BOSS") // << "GUILD" << delim // << guild->index() << delim // << guild->name() << delim // << "PRE BOSS" << delim; // if( guild->boss() ) // { // GAMELOG << guild->boss()->charindex() << delim // << guild->boss()->GetName(); // } // GAMELOG << "NEW BOSS" << delim // << member->charindex() << delim // << member->GetName() // << end; if(guild->boss() == NULL) { GAMELOG << init("GUILD CHANGE BOSS") << "GUILD" << delim << guild->index() << delim << guild->name() << delim << "NEW BOSS" << delim << member->charindex() << delim << member->GetName() << end; } else { GAMELOG << init("GUILD CHANGE BOSS") << "GUILD" << delim << guild->index() << delim << guild->name() << delim << "PRE BOSS" << delim << guild->boss()->charindex() << delim << guild->boss()->GetName() << delim << "NEW BOSS" << delim << member->charindex() << delim << member->GetName() << end; } // >> guild->changeboss(member->listindex()); { CNetMsg::SP rmsg(new CNetMsg); GuildChangeBossMsg(rmsg, guildindex, current, change); guild->SendToAll(rmsg); } if (member->GetPC()) { CNetMsg::SP rmsg(new CNetMsg); GuildInfoChangeMsg(rmsg, change, guildindex, guild->name(), MSG_GUILD_POSITION_BOSS, member->GetPC()); member->GetPC()->m_pArea->SendToCell(rmsg, member->GetPC(), false); } CDratanCastle* pDratanCastle = CDratanCastle::CreateInstance(); if( pDratanCastle->GetOwnerCharIndex() == current ) { CPC* pc = PCManager::instance()->getPlayerByCharIndex(current); if( pc ) { pc->CastllanTitleDelete(-1 , true); pc->m_inventory.CastllanItemRemove(-1, false, true); // 옷만 벚긴다. } } // 성주 길드라면 성주변경 CWarCastle * cast = CWarCastle::GetCastleObject( CWarCastle::GetCurSubServerCastleZoneIndex() ); if( cast && cast->GetOwnerGuildIndex() == guild->index() ) { // 이전 보스에 무기 뺏고, CPC* preboss = PCManager::instance()->getPlayerByCharIndex(current); if( preboss ) { BOOST_FOREACH(CItemProto* flagload_item, gserver->m_itemProtoList.m_flagload) { // 해당하는 모든 아이템을 검색한다. item_search_t vec; int sc = preboss->m_inventory.searchItemByCondition(flagload_item->getItemIndex(), 0, 0, vec); if (sc == 0) continue; item_search_t::iterator it = vec.begin(); item_search_t::iterator endit = vec.end(); for (; it != endit; ++it) { CItem* item = (*it).pItem; if (item->getWearPos() != WEARING_NONE) { if (item->getWearPos() >= WEARING_SHOW_START && item->getWearPos() <= WEARING_SHOW_END && preboss->m_pArea) { CNetMsg::SP rmsg(new CNetMsg); WearingMsg(rmsg, preboss, item->getWearPos(), -1, 0); preboss->m_pArea->SendToCell(rmsg, preboss, true); } preboss->m_wearInventory.RemoveItem(item->getWearPos()); } } } preboss->CastllanTitleDelete(-1, true ); preboss->m_inventory.CastllanItemRemove(-1, false, true); // 옷만 벚긴다. } cast->SetOwner(guild); CDBCmd cmd; cmd.Init(&gserver->m_dbcastle); std::string update_castle_query = boost::str(boost::format("UPDATE t_castle SET a_owner_charindex = %d, a_owner_char_name = '%s' WHERE a_zone_index = %d ") % member->charindex()% member->GetName()% cast->GetZoneIndex() ); cmd.SetQuery(update_castle_query); cmd.Update(); GAMELOG << init("WARCASTLE BOSS CHANGE") << member->charindex() << delim << member->GetName() << end; // 현재 보스에 무기 지급 CPC* boss = PCManager::instance()->getPlayerByCharIndex(change); if (boss && boss->m_guildInfo && boss->m_guildInfo->guild()) { int ownZoneCount; int* ownZoneIndex = CWarCastle::GetOwnCastle(boss->m_guildInfo->guild()->index(), &ownZoneCount); if (ownZoneIndex) { time_t curtime; time(&curtime); int i; for (i = 0; i < ownZoneCount; i++) { CWarCastle* castle = CWarCastle::GetCastleObject(ownZoneIndex[i]); if (castle) { // 060116 : BS : BEGIN : 공성 시작해도 칼 회수 안하게 // int nexttime = castle->GetNextWarTime(); if (castle->GetOwnerCharIndex() == boss->m_index) { // 060116 : BS : BEGIN : 공성 시작해도 칼 회수 안하게 // // 공성 시작 5분전에서 공성 진행중이면 회수 // if (castle->GetState() != WCSF_NORMAL || curtime + 5 * 60 >= nexttime) // { // castle->TakeLordItem(d->m_pChar); // } // // // 일반 상태에서 없으면 지급 // else // { castle->GiveLordItem(boss); // } // 060116 : BS : END : 공성 시작해도 칼 회수 안하게 } } } delete [] ownZoneIndex; } boss->CastllanTitleDelete(-1, true); boss->m_inventory.CastllanItemRemove(-1, false, true); // 옷만 벚긴다. } } CGuildMember* boss = guild->findmember(current); if (!boss) return ; if (boss->GetPC()) { CNetMsg::SP rmsg(new CNetMsg); GuildInfoChangeMsg(rmsg, current, guildindex, guild->name(), MSG_GUILD_POSITION_MEMBER, boss->GetPC()); boss->GetPC()->m_pArea->SendToCell(rmsg, boss->GetPC(), false); } if( guild->level() > MANAGE_NEED_LEVEL ) { CPC* ch = PCManager::instance()->getPlayerByCharIndex(current); CPC* ch1 = PCManager::instance()->getPlayerByCharIndex(change); if( ch && ch1 ) { if( gserver->isRunHelper() ) { { CNetMsg::SP rmsg(new CNetMsg); HelperNewGuildManage( rmsg, ch ); SEND_Q( rmsg, gserver->m_helper ); } { CNetMsg::SP rmsg(new CNetMsg); HelperNewGuildManage( rmsg, ch1 ); SEND_Q( rmsg, gserver->m_helper ); } } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_GAMESERVER); SEND_Q(rmsg, ch->m_desc); SEND_Q(rmsg, ch1->m_desc); } } } // 길마가 바뀌었을 때, GP정보 쏴주기 // current와 change PC로 발송. CGuildMember* pPrevBoss = NULL; CGuildMember* pChangeBoss = NULL; pPrevBoss = guild->findmember(current); pChangeBoss = guild->findmember(change); if(pPrevBoss->GetPC()) { CNetMsg::SP rmsg(new CNetMsg); GuildPointInfo(rmsg, 0); SEND_Q(rmsg, pPrevBoss->GetPC()->m_desc); } if(pChangeBoss->GetPC()) { CNetMsg::SP rmsg(new CNetMsg); GuildPointInfo(rmsg, guild->GetGuildPoint()); SEND_Q(rmsg, pChangeBoss->GetPC()->m_desc); } } void ProcHelperGuildChangeBossRep(CNetMsg::SP& msg) { int guildindex; int current; int change; unsigned char errcode; RefMsg(msg) >> guildindex >> current >> change >> errcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex(current); if (pc) { CNetMsg::SP rmsg(new CNetMsg); if (errcode == MSG_GUILD_ERROR_OK) { GuildErrorMsg(rmsg, MSG_GUILD_ERROR_CHANGE_BOSS_OK); } else GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperGuildAppointOfficerRep(CNetMsg::SP& msg) { int guildindex; int bossindex; int charindex; unsigned char errcode; RefMsg(msg) >> guildindex >> bossindex >> charindex >> errcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex(bossindex); if (pc) { CNetMsg::SP rmsg(new CNetMsg); if (errcode == MSG_GUILD_ERROR_OK) GuildErrorMsg(rmsg, MSG_GUILD_ERROR_APPOINT_OFFICER_OK); else GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperGuildAppointOfficerNotify(CNetMsg::SP& msg) { int guildindex; int bossindex; int charindex; RefMsg(msg) >> guildindex >> bossindex >> charindex; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; CGuildMember* member = guild->findmember(charindex); if (!member) return ; guild->appoint(member->listindex()); { CNetMsg::SP rmsg(new CNetMsg); GuildAppointOfficerMsg(rmsg, guildindex, charindex); guild->SendToAll(rmsg); } if (member->GetPC()) { CNetMsg::SP rmsg(new CNetMsg); GuildInfoChangeMsg(rmsg, charindex, guildindex, guild->name(), MSG_GUILD_POSITION_OFFICER, member->GetPC()); member->GetPC()->m_pArea->SendToCell(rmsg, member->GetPC(), false); } GAMELOG << init("GUILD OFFICER APPOINT") << "GUILD" << delim << guild->index() << delim << guild->name() << delim << "NEW OFFICER" << delim << member->charindex() << delim << member->GetName() << end; if( guild->level() > MANAGE_NEED_LEVEL ) { CPC* ch = PCManager::instance()->getPlayerByCharIndex(bossindex); if( ch ) { if( gserver->isRunHelper() ) { CNetMsg::SP rmsg(new CNetMsg); HelperNewGuildManage( rmsg, ch ); SEND_Q( rmsg, gserver->m_helper ); } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_GAMESERVER); SEND_Q(rmsg, ch->m_desc); } } } } void ProcHelperGuildChat(CNetMsg::SP& msg) { int guildindex; int charindex; CLCString charname(MAX_CHAR_NAME_LENGTH + 1); CLCString chat(1000); RefMsg(msg) >> guildindex >> charindex >> charname >> chat; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (guild) { { CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_GUILD, charindex, charname, "", chat); guild->SendToAll(rmsg); } #ifdef GMTOOL if(guild->m_bGmtarget) { bool bSend = false; for(int i = 0; i < GUILD_MAX_MEMBER; ++i) { CGuildMember* member = guild->member(i); if(member && member->GetPC() && member->GetPC()->m_bGmMonitor) { CNetMsg::SP rmsg(new CNetMsg); MsgrNoticeGmChatMonitorGuildMsg(rmsg, -1, 1, 1, 0, gserver->m_serverno, gserver->m_subno, -1, chat, guildindex, charname, member->GetPC()->m_index, member->GetPC()->m_name); SEND_Q(rmsg, gserver->m_messenger); bSend = true; } } if(!bSend) { guild->m_bGmtarget = false; } } #endif // GMTOOL } } void ProcHelperGuildFireOfficerRep(CNetMsg::SP& msg) { int guildindex; int bossindex; int charindex; unsigned char errcode; RefMsg(msg) >> guildindex >> bossindex >> charindex >> errcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex(bossindex); if (pc) { CNetMsg::SP rmsg(new CNetMsg); if (errcode == MSG_GUILD_ERROR_OK) GuildErrorMsg(rmsg, MSG_GUILD_ERROR_FIRE_OFFICER_OK); else GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperGuildFireOfficerNotify(CNetMsg::SP& msg) { int guildindex; int bossindex; int charindex; RefMsg(msg) >> guildindex >> bossindex >> charindex; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; CGuildMember* member = guild->findmember(charindex); if (!member) return ; guild->fire(member->listindex()); { CNetMsg::SP rmsg(new CNetMsg); GuildFireOfficerMsg(rmsg, guildindex, charindex); guild->SendToAll(rmsg); } if (member->GetPC()) { CNetMsg::SP rmsg(new CNetMsg); GuildInfoChangeMsg(rmsg, charindex, guildindex, guild->name(), MSG_GUILD_POSITION_MEMBER, member->GetPC()); member->GetPC()->m_pArea->SendToCell(rmsg, member->GetPC(), false); } GAMELOG << init("GUILD OFFICER FIRE") << "GUILD" << delim << guild->index() << delim << guild->name() << delim << "OFFICER" << delim << member->charindex() << delim << member->GetName() << end; if( guild->level() > MANAGE_NEED_LEVEL ) { CPC* ch = PCManager::instance()->getPlayerByCharIndex(bossindex); if( ch ) { if( gserver->isRunHelper() ) { CNetMsg::SP rmsg(new CNetMsg); HelperNewGuildManage( rmsg, ch ); SEND_Q( rmsg, gserver->m_helper ); } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_GAMESERVER); SEND_Q(rmsg, ch->m_desc); } } } } void ProcHelperGuildLoadNotify(CNetMsg::SP& msg) { int guildindex; int guildlevel; CLCString guildname(MAX_GUILD_NAME_LENGTH + 1); int bossindex; CLCString bossname(MAX_CHAR_NAME_LENGTH + 1); int battleIndex; int create_time; #ifdef DEV_GUILD_MARK char gm_row; char gm_col; char bg_row; char bg_col; int markTime; #endif int battle_win_count, battle_lose_count, battle_total_count; int contribute_exp_min, contribute_exp_max, contribute_fame_min, contribute_fame_max; RefMsg(msg) >> guildindex >> guildlevel >> guildname >> bossindex >> bossname >> battleIndex >> create_time >> battle_win_count >> battle_lose_count >> battle_total_count; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) { guild = gserver->m_guildlist.create(guildindex, guildname, bossindex, bossname, create_time, battle_win_count, battle_lose_count, battle_total_count); if (!guild) return; guild->level(guildlevel); gserver->m_guildlist.add(guild); } int battlePrize; int battleTime; int battleZone; int killCount; char battleState; int maxmember; RefMsg(msg) >> battlePrize >> battleTime >> battleZone >> killCount >> battleState >> maxmember; guild->setMaxmember( maxmember ); if (battleIndex != -1) { guild->BattleSet(battleIndex, battlePrize, battleZone); guild->BattleTime(battleTime); guild->KillCount(killCount); guild->BattleState(battleState); } #ifdef DEV_GUILD_MARK RefMsg(msg) >> gm_row >> gm_col >> bg_row >> bg_col >> markTime; guild->SetGuildMark(gm_row, gm_col, bg_row, bg_col, markTime); #endif int _kickStatus = GMKS_NORMAL, _requestChar = 0, _requestTime = 0, create_date = 0; RefMsg(msg) >> _kickStatus >> _requestChar >> _requestTime >> contribute_exp_min >> contribute_exp_max >> contribute_fame_min >> contribute_fame_max; guild->getGuildKick()->setKickStatus(_kickStatus); guild->getGuildKick()->setKickReuestChar(_requestChar); guild->getGuildKick()->setKickRequestTime(_requestTime); guild->m_create_date = create_time; guild->m_guild_contribute_all_exp_min = contribute_exp_min; guild->m_guild_contribute_all_exp_max = contribute_exp_max; guild->m_guild_contribute_all_fame_min = contribute_fame_min; guild->m_guild_contribute_all_fame_max = contribute_fame_max; /* CGuild* guild = gserver->m_guildlist.create(guildindex, guildname, bossindex, bossname); if (!guild) { return ; } guild->level(guildlevel); gserver->m_guildlist.add(guild); */ } void ProcHelperGuildBattleRep(CNetMsg::SP& msg) { int guildindex1; CLCString guildname1(MAX_GUILD_NAME_LENGTH + 1); int guildindex2; CLCString guildname2(MAX_GUILD_NAME_LENGTH + 1); int prize; int zone; int time; RefMsg(msg) >> guildindex1 >> guildname1 >> guildindex2 >> guildname2 >> prize >> zone >> time; CGuild* g1 = gserver->m_guildlist.findguild(guildindex1); CGuild* g2 = gserver->m_guildlist.findguild(guildindex2); CPC* boss1 = NULL; CPC* boss2 = NULL; if (g1) boss1 = g1->boss()->GetPC(); if (g2) boss2 = g2->boss()->GetPC(); if (!g1 || !g2 || !boss1 || !boss2) return ; //if (boss1) //{ // if (boss1->m_inventory.getMoney()) // { // if (boss1->m_inventory.getMoney() >= (LONGLONG)prize) // { // //길드창고에서 차감하도록 수정 // boss1->m_inventory.decreaseMoney(prize); // } // } //} //if (boss2) //{ // if (boss2->m_inventory.getMoney()) // { // if (boss2->m_inventory.getMoney() >= (LONGLONG)prize) // { // //길드창고에서 차감하도록 수정 // boss2->m_inventory.decreaseMoney(prize); // } // } //} // 세부 셋팅 g1->BattleSet(g2->index(), prize * 95 / 100, zone); g1->BattleTime(time); g1->BattleState(GUILD_BATTLE_STATE_WAIT); g2->BattleSet(g1->index(), prize * 95 / 100, zone); g2->BattleTime(time); g2->BattleState(GUILD_BATTLE_STATE_WAIT); { // 길전이 성립되다! CNetMsg::SP rmsg(new CNetMsg); GuildBattleReqAccpetMsg(rmsg, guildindex1, guildname1, guildindex2, guildname2, prize * 2 * 95 / 100 / 10000, zone, time); g1->SendToAll(rmsg); g2->SendToAll(rmsg); } } void ProcHelperGuildBattleStart(CNetMsg::SP& msg) { int guildindex1; CLCString guildname1(MAX_GUILD_NAME_LENGTH + 1); int guildindex2; CLCString guildname2(MAX_GUILD_NAME_LENGTH + 1); int prize; int zone; int time; CNetMsg::SP rmsg(new CNetMsg); RefMsg(msg) >> guildindex1 >> guildname1 >> guildindex2 >> guildname2 >> prize >> zone >> time; CGuild* g1 = gserver->m_guildlist.findguild(guildindex1); CGuild* g2 = gserver->m_guildlist.findguild(guildindex2); if (g1) { g1->BattleState(GUILD_BATTLE_STATE_ING); g1->BattleTime(time); } if (g2) { g2->BattleState(GUILD_BATTLE_STATE_ING); g2->BattleTime(time); } } void ProcHelperGuildBattleStopRep(CNetMsg::SP& msg) { int winner_index; int guildindex1; CLCString guildname1(MAX_GUILD_NAME_LENGTH + 1); int guildindex2; CLCString guildname2(MAX_GUILD_NAME_LENGTH + 1); int prize_nas; int prize_gp; int zone; int guildkill1; int guildkill2; int battle_win_count1, battle_lose_count1, battle_total_count1; int battle_win_count2, battle_lose_count2, battle_total_count2; int isAccept; RefMsg(msg) >> winner_index >> guildindex1 >> guildname1 >> guildkill1 >> guildindex2 >> guildname2 >> guildkill2 >> prize_nas >> prize_gp >> zone >> battle_win_count1 >> battle_lose_count1 >> battle_total_count1 >> battle_win_count2 >> battle_lose_count2 >> battle_total_count2 >> isAccept; CGuild* g1 = gserver->m_guildlist.findguild(guildindex1); CGuild* g2 = gserver->m_guildlist.findguild(guildindex2); CPC* boss = NULL; bool bHaveMoney = false; // 동점이면 상금이 반 if (winner_index == -1) { prize_nas /= 2; prize_gp /= 2; if (g1) g1->BattleSet(guildindex2, prize_nas, zone); if (g2) g2->BattleSet(guildindex1, prize_nas, zone); } // 있는 길드 우선 셋팅 해제 if (g1) { g1->BattleState(GUILD_BATTLE_STATE_PRIZE); //승리길드일때 길드장 찾기 if(isAccept == true) { int origin_gp = prize_gp * 100 / 90; int fee = origin_gp - prize_gp; g1->AddGuildPoint(-fee); } else if (winner_index == g1->index()) { boss = g1->boss()->GetPC(); // 길드장이 있으면 상금 주고 길드 상태 해제 요청 if (boss) { g1->AddGuildPoint(prize_gp); } } else if(winner_index == -1) { //무승부일때는 아무것도 하지 않는다. } else { //졌을때 처리 g1->BattleSet(-1, 0, -1); g1->BattleTime(0); g1->KillCount(0); g1->BattleState(GUILD_BATTLE_STATE_PEACE); if(g2 != NULL) { g2->AddGuildPoint(-prize_gp * 100 / 90); } } // 길드전 해제 요청 if (gserver->isRunHelper()) { CNetMsg::SP rmsg(new CNetMsg); HelperGuildBattlePeaceReqMsg(rmsg, g1); SEND_Q(rmsg, gserver->m_helper); } g1->BattleSet(-1, 0, -1); g1->BattleTime(0); g1->KillCount(0); g1->BattleState(GUILD_BATTLE_STATE_PEACE); g1->m_battle_win_count = battle_win_count1; g1->m_battle_lose_count = battle_lose_count1; g1->m_battle_total_count = battle_total_count1; g1->m_isUseTheStashAndSkill = true; } boss = NULL; bHaveMoney = false; if (g2) { g2->BattleState(GUILD_BATTLE_STATE_PRIZE); // 동점이거나 승리길드일때 길드장 찾기 if(isAccept == true) { int origin_gp = prize_gp * 100 / 90; int fee = origin_gp - prize_gp; g2->AddGuildPoint(-fee); } else if (winner_index == g2->index()) { boss = g2->boss()->GetPC(); // 길드장이 있으면 상금 주고 길드 상태 해제 요청 if (boss) { g2->AddGuildPoint(prize_gp); } } else if(winner_index == -1) { } else { g2->BattleSet(-1, 0, -1); g2->BattleTime(0); g2->KillCount(0); g2->BattleState(GUILD_BATTLE_STATE_PEACE); if(g2 != NULL) { g2->AddGuildPoint(-prize_gp * 100 / 90); } } // 길드전 해제 요청 if (gserver->isRunHelper()) { CNetMsg::SP rmsg(new CNetMsg); HelperGuildBattlePeaceReqMsg(rmsg, g2); SEND_Q(rmsg, gserver->m_helper); } g2->BattleSet(-1, 0, -1); g2->BattleTime(0); g2->KillCount(0); g2->BattleState(GUILD_BATTLE_STATE_PEACE); g2->m_battle_win_count = battle_win_count2; g2->m_battle_lose_count = battle_lose_count2; g2->m_battle_total_count = battle_total_count2; g2->m_isUseTheStashAndSkill = true; } { CNetMsg::SP rmsg(new CNetMsg); GuildBattleCoreInitMsg(rmsg); CZone* _zone = gserver->FindZone(zone); if(_zone == NULL) return; for(int i = 0 ; i < _zone->m_countArea; i++) { _zone->m_area[i].SendToAllClient(rmsg); } } { // 길드전 종료 메시지 CNetMsg::SP rmsg(new CNetMsg); GuildBattleEndMsg(rmsg, winner_index, guildindex1, guildname1, guildindex2, guildname2, prize_nas); if (g1) g1->SendToAll(rmsg); if (g2) g2->SendToAll(rmsg); } if( (g1 != NULL && gserver->m_battle_guild_index == g1->index()) || (g2 != NULL && gserver->m_battle_guild_index == g2->index()) ) { gserver->m_battle_guild_index = -1; gserver->m_battle_guild_gm = -1; } } void ProcHelperGuildBattleStatus(CNetMsg::SP& msg) { int guildindex1; CLCString guildname1(MAX_GUILD_NAME_LENGTH + 1); int killCount1; int guildindex2; CLCString guildname2(MAX_GUILD_NAME_LENGTH + 1); int killCount2; int battleTime; int battleZone; RefMsg(msg) >> guildindex1 >> guildname1 >> killCount1 >> guildindex2 >> guildname2 >> killCount2 >> battleTime >> battleZone; CGuild* g1 = gserver->m_guildlist.findguild(guildindex1); CGuild* g2 = gserver->m_guildlist.findguild(guildindex2); if (g1) { g1->KillCount(killCount1); g1->BattleTime(battleTime); } else return; if (g2) { g2->KillCount(killCount2); g2->BattleTime(battleTime); } else return; { CNetMsg::SP rmsg(new CNetMsg); GuildBattleStatusMsg(rmsg, guildindex1, guildname1, killCount1, guildindex2, guildname2, killCount2, battleTime, battleZone); if(g1) g1->SendToAll(rmsg); if(g2) g2->SendToAll(rmsg); //운영자 명령어에 의해서 명령어가 있는 경우 존에 있는 모든 유저들에게 전송 아닐경우 길드원에게만 전송 if( (g1 != NULL && gserver->m_battle_guild_index == g1->index()) || (g2 != NULL && gserver->m_battle_guild_index == g2->index()) ) { //gm및 진행 중인 유저에게 패킷 전달 if(gserver->m_battle_guild_gm != -1) { //gm에게도 패킷 전달 CPC* gm = PCManager::instance()->getPlayerByCharIndex(gserver->m_battle_guild_gm); SEND_Q(rmsg, gm->m_desc); } //모든 유저에게 전달 else { CZone* zone = gserver->FindZone(battleZone); if(zone == NULL) return; for(int i = 0 ; i < zone->m_countArea; i++) { zone->m_area[i].SendToAllClient(rmsg); } } } } } void ProcHelperGuildBattlePeaceRep(CNetMsg::SP& msg) { int guildindex; RefMsg(msg) >> guildindex; CGuild* g = gserver->m_guildlist.findguild(guildindex); if (!g) return; g->BattleSet(-1, 0, -1); g->BattleTime(0); g->KillCount(0); g->BattleState(GUILD_BATTLE_STATE_PEACE); } void ProcHelperGuildMarkTable(CNetMsg::SP& msg) { for(int i=0; i < 3; i++) { RefMsg(msg) >> gserver->m_nGuildMarkTable[i]; } } void ProcHelperEventMoonStoneLoad(CNetMsg::SP& msg) { int moonstone_nas; RefMsg(msg) >> moonstone_nas; if(moonstone_nas >= 0) { gserver->m_nMoonStoneNas = moonstone_nas; } } void ProcHelperEventMoonStoneJackpot(CNetMsg::SP& msg) { int moonstone_nas; int chaindex; RefMsg(msg) >> moonstone_nas >> chaindex; CPC* ch = PCManager::instance()->getPlayerByCharIndex(chaindex); if(!ch) return; ch->m_inventory.decreaseMoney(moonstone_nas); GAMELOG << init("CHANGE_MOONSTONE", ch) << "NAS is " << moonstone_nas << end; } void ProcHelper_FriendAddRep(CNetMsg::SP& msg) { UpdateServer::doFriendAddRepToHelper *packet = reinterpret_cast<UpdateServer::doFriendAddRepToHelper*>(msg->m_buf); CPC* appPc = PCManager::instance()->getPlayerByCharIndex(packet->approvalindex); CPC* reqPc = PCManager::instance()->getPlayerByCharIndex(packet->requesterindex); if (!appPc || !reqPc) { return; } if((MSG_FRIEND_ERROR_TYPE)packet->errorCode == MSG_FRIEND_ERROR_GAMESERVER) { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendErrorMsg(rmsg, (MSG_FRIEND_ERROR_TYPE)packet->errorCode);//요청자에게 성공여부를 알린다. SEND_Q(rmsg, reqPc->m_desc); reqPc->m_nRegFriend = 0; appPc->m_nRegFriend = 0; } else { if (reqPc)//동시에 접속해 있어야 한다. { { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendErrorMsg(rmsg, (MSG_FRIEND_ERROR_TYPE)packet->errorCode);//요청자에게 성공여부를 알린다. SEND_Q(rmsg, reqPc->m_desc); } reqPc->m_nRegFriend = 0; reqPc->m_Friend->AddFriend(packet->approvalindex, packet->appname, packet->appjob, MSG_FRIEND_CONDITION_NORMAL, 0); { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendAddNotify(rmsg, appPc->m_index, appPc->GetName(), appPc->m_job, appPc->m_nCondition); //승낙자에게 멤버가 추가됨을 알림 SEND_Q(rmsg, reqPc->m_desc); } } if(appPc) { appPc->m_Friend->AddFriend(packet->requesterindex, packet->reqname, packet->reqjob, MSG_FRIEND_CONDITION_NORMAL, 0); appPc->m_nRegFriend = 0; CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendAddNotify(rmsg, reqPc->m_index, reqPc->GetName(), reqPc->m_job, reqPc->m_nCondition); //요청자에게 멤버가 추가됨을 알림. SEND_Q(rmsg, appPc->m_desc); } } } void ProcHelper_FriendDelRep(CNetMsg::SP& msg) { UpdateServer::doFriendDelMemberRepToGameServer *packet = reinterpret_cast<UpdateServer::doFriendDelMemberRepToGameServer*>(msg->m_buf); //삭제 요청자... CPC* pPc = PCManager::instance()->getPlayerByCharIndex(packet->removerIndex); if(pPc) { pPc->m_Friend->RemoveFriend(packet->deleteIndex); pPc->m_listBlockPC.erase(packet->deleteIndex); { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendErrorMsg(rmsg, (MSG_FRIEND_ERROR_TYPE)packet->errorCode); SEND_Q(rmsg, pPc->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendDelNotify(rmsg, packet->deleteIndex); SEND_Q(rmsg, pPc->m_desc); } } //삭제 당한자... CPC* pPc2 = PCManager::instance()->getPlayerByCharIndex(packet->deleteIndex); if(pPc2)//접속해있다면... { pPc2->m_Friend->RemoveFriend(packet->removerIndex); pPc2->m_listBlockPC.erase(packet->removerIndex); CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendDelNotify(rmsg, packet->removerIndex); SEND_Q(rmsg, pPc2->m_desc); } } void ProcHelper_BlockPCRep(CNetMsg::SP& msg) { int reqindex; int blockIndex; CLCString blockName(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> reqindex >> blockIndex >> blockName; //삭제 요청자... CPC* pPc = PCManager::instance()->getPlayerByCharIndex(reqindex); if(pPc) { if( blockIndex == -1 ) { CNetMsg::SP rmsg(new CNetMsg); BlockPCRepMsg(rmsg, MSG_EX_MESSENGER_BLOCK_NOTCHAR, blockIndex, blockName); SEND_Q(rmsg, pPc->m_desc); return; } { CNetMsg::SP rmsg(new CNetMsg); if( pPc->AddBlockPC(blockIndex, blockName) ) { // 블럭 요청이 성공하였다는 메세지 : 할일 // GS->C : errcode(c) charIndex(n) name(str) BlockPCRepMsg(rmsg, MSG_EX_MESSENGER_SUCCESS, blockIndex, blockName); } else BlockPCRepMsg(rmsg, MSG_EX_MESSENGER_ALREADY_BLOCK, blockIndex, blockName); SEND_Q(rmsg, pPc->m_desc); } } CPC* pPc2 = PCManager::instance()->getPlayerByCharIndex(blockIndex); if(pPc2)//접속해있다면... { CFriendMember* fMember = pPc2->m_Friend->FindFriendMember(reqindex); if( fMember ) { fMember->SetCondition(MSG_FRIEND_CONDITION_OFFLINE); } CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendSetConditionMsg(rmsg, reqindex, MSG_FRIEND_CONDITION_OFFLINE); SEND_Q(rmsg, pPc2->m_desc); } } void ProcHelper_GiftRecvChar(CNetMsg::SP& msg) { int count = 0; int idx[10], ctid[10], i; int sendUserIdx, sendCharIdx; int recvuserIndex, recvcharIndex; CLCString recvcharName( MAX_CHAR_NAME_LENGTH + 1); CLCString strMsg( MAX_GIFT_MESSAGE_LENGTH + 1); //int sendUserIdx, int sendCharIdx, int recvUserIdx, int recvCharIdx, const char* recvCharName, const char* sendMsg, int count, int idx[], int ctid[] ) RefMsg(msg) >> sendUserIdx >> sendCharIdx >> recvuserIndex >> recvcharIndex >> recvcharName >> strMsg >> count; CPC* ch = PCManager::instance()->getPlayerByCharIndex(sendCharIdx); if( !ch ) return; if( recvcharIndex == -1 ) { ch->ResetPlayerState(PLAYER_STATE_CASHITEM); ch->m_billReqTime = 0; CNetMsg::SP rmsg(new CNetMsg); CashItemGiftSendRepMsg(rmsg, MSG_EX_CASHITEM_ERROR_GIFT_WRONGCHAR); SEND_Q(rmsg, ch->m_desc); return; } if( count < 1 ) { ch->ResetPlayerState(PLAYER_STATE_CASHITEM); ch->m_billReqTime = 0; CNetMsg::SP rmsg(new CNetMsg); CashItemGiftSendRepMsg(rmsg, MSG_EX_CASHITEM_ERROR_GIFT_NOCTID); SEND_Q(rmsg, ch->m_desc); return; } for( i = 0; i < count; i++ ) { RefMsg(msg) >> idx[i] >> ctid[i]; } if( gserver->isRunConnector() ) { { CNetMsg::SP rmsg(new CNetMsg); ConnCashItemGiftReqMsg(rmsg, ch->m_desc->m_index, ch->m_index, ch->GetName(), strMsg, recvuserIndex, recvcharIndex, recvcharName, count, idx, ctid); SEND_Q(rmsg, gserver->m_connector); } GAMELOG << init("CASH_ITEM_BRING_GIFT_SEND_REQ", ch) << "RECEIVER" << delim << "USRIDX" << delim << recvuserIndex << delim << "CHARIDX" << delim << recvcharIndex << delim << "CHARNAME" << delim << recvcharName << delim << count << delim; CCatalog* catalog = NULL; for(i = 0; i < count; i++ ) { GAMELOG << idx[i] << delim << ctid[i] << delim; catalog = gserver->m_catalogList.Find( ctid[i] ); if( catalog ) GAMELOG << catalog->GetName() << delim; } GAMELOG << end; } else { ch->ResetPlayerState(PLAYER_STATE_CASHITEM); ch->m_billReqTime = 0; } } //상태가 바뀐걸 모든 친구에게 보낸다. void ProcHelper_FriendSetConditionRep(CNetMsg::SP& msg) { int chaindex; int condition; int reply; CFriendMember * pMember = NULL; RefMsg(msg) >> chaindex >> condition >> reply; if(reply == -1) { int sum, index; RefMsg(msg) >> sum; for(int i =0; i < sum; i++) { RefMsg(msg) >> index; CPC* pPc = PCManager::instance()->getPlayerByCharIndex(index); if(pPc) { { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendSetConditionMsg(rmsg, chaindex, condition); SEND_Q(rmsg, pPc->m_desc); } // 친구 리스트 업데이트 if (pPc->m_Friend) { pMember = pPc->m_Friend->FindFriendMember( chaindex ); if( pMember != NULL ) { pMember->SetCondition( condition ); } { //접속한 사람에게 내 자신의 상태도 보내줘야지.. CNetMsg::SP rmsg(new CNetMsg); HelperFriendSetConditionMsg(rmsg, index, pPc->m_nCondition, chaindex, NULL); SEND_Q(rmsg, gserver->m_helper); } } } } } else { CPC* pPc = PCManager::instance()->getPlayerByCharIndex(reply); if(pPc) { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::FriendSetConditionMsg(rmsg, chaindex, condition); SEND_Q(rmsg, pPc->m_desc); // 친구 리스트 업데이트 pMember = pPc->m_Friend->FindFriendMember( chaindex ); if( pMember != NULL ) { pMember->SetCondition( condition ); } } } } void ProcHelperWarNoticeTime(CNetMsg::SP& msg) { int zoneindex; char month; char day; char hour; char min; RefMsg(msg) >> zoneindex >> month >> day >> hour >> min; { CNetMsg::SP rmsg(new CNetMsg); GuildWarNoticeTimeMsg(rmsg, zoneindex, month, day, hour, min); PCManager::instance()->sendToAll(rmsg); } } void ProcHelperWarNoticeTimeRemain(CNetMsg::SP& msg) { int zoneindex; char remain; RefMsg(msg) >> zoneindex >> remain; CNetMsg::SP rmsg(new CNetMsg); GuildWarNoticeTimeRemainMsg(rmsg, zoneindex, remain); PCManager::instance()->sendToAll(rmsg); } void ProcHelperWarNoticeStart(CNetMsg::SP& msg) { int zoneindex; int remainSec; RefMsg(msg) >> zoneindex >> remainSec; CNetMsg::SP rmsg(new CNetMsg); GuildWarNoticeStartMsg(rmsg, zoneindex, remainSec); PCManager::instance()->sendToAll(rmsg); // 공성 상태 갱신 : 진행중인 서브 서버는 직접 바꾸므로 스킵 CWarCastle* castle = CWarCastle::GetCastleObject(zoneindex); if (castle && !castle->CheckSubServer()) { castle->SetState(WCSF_WAR_FIELD); } } void ProcHelperWarJoinAttackGuild(CNetMsg::SP& msg) { int zoneindex; int guildindex; RefMsg(msg) >> zoneindex >> guildindex; CWarCastle* castle = CWarCastle::GetCastleObject(zoneindex); if (!castle) return ; if (castle->IsAttackGuild(guildindex)) return ; if (castle->GetOwnerGuildIndex() == guildindex) return ; if (castle->IsDefenseGuild(guildindex)) castle->RemoveDefenseGuild(guildindex); castle->AddAttackGuild(guildindex); CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; int i; int guildMaxMember = guild->maxmember(); for (i = 0; i < guildMaxMember; i++) { if (guild->member(i)) { if (castle->IsAttackChar(guild->member(i)->charindex())) castle->RemoveAttackChar(guild->member(i)->charindex()); if (castle->IsDefenseChar(guild->member(i)->charindex())) castle->RemoveDefenseChar(guild->member(i)->charindex()); if (guild->member(i)->GetPC()) { guild->member(i)->GetPC()->SetJoinFlag(zoneindex, WCJF_ATTACK_GUILD); guild->member(i)->GetPC()->m_bChangeStatus = true; } } } } void ProcHelperWarJoinDefenseGuild(CNetMsg::SP& msg) { int zoneindex; int guildindex; RefMsg(msg) >> zoneindex >> guildindex; CWarCastle* castle = CWarCastle::GetCastleObject(zoneindex); if (!castle) return ; if (castle->IsDefenseGuild(guildindex)) return ; if (castle->GetOwnerGuildIndex() == guildindex) return ; if (castle->IsAttackGuild(guildindex)) return ; castle->AddDefenseGuild(guildindex); CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; int i; int guildMaxMember = guild->maxmember(); for (i = 0; i < guildMaxMember; i++) { if (guild->member(i)) { if (castle->IsAttackChar(guild->member(i)->charindex())) castle->RemoveAttackChar(guild->member(i)->charindex()); if (castle->IsDefenseChar(guild->member(i)->charindex())) castle->RemoveDefenseChar(guild->member(i)->charindex()); if (guild->member(i)->GetPC()) { guild->member(i)->GetPC()->SetJoinFlag(zoneindex, WCJF_DEFENSE_GUILD); guild->member(i)->GetPC()->m_bChangeStatus = true; } } } } void ProcHelperWarNoticeStartAttackCastle(CNetMsg::SP& msg) { int zoneindex; int remainSec; int guildindex1 = -1; int guildindex2 = -1; int guildindex3 = -1; CLCString guildname1(MAX_GUILD_NAME_LENGTH + 1); CLCString guildname2(MAX_GUILD_NAME_LENGTH + 1); CLCString guildname3(MAX_GUILD_NAME_LENGTH + 1); RefMsg(msg) >> zoneindex >> remainSec >> guildindex1 >> guildname1 >> guildindex2 >> guildname2 >> guildindex3 >> guildname3; { CNetMsg::SP rmsg(new CNetMsg); GuildWarNoticeStartCastleMsg(rmsg, zoneindex, remainSec, guildindex1, guildname1, guildindex2, guildname2, guildindex3, guildname3); PCManager::instance()->sendToAll(rmsg); } // 공성 상태 갱신 : 진행중인 서브 서버는 직접 바꾸므로 스킵 CWarCastle* castle = CWarCastle::GetCastleObject(zoneindex); if (castle && !castle->CheckSubServer()) { castle->SetState(WCSF_WAR_CASTLE); } // 포인트 변경 알림 if (castle != NULL) { PCManager::instance()->sendGuildWarPointMsg(castle, zoneindex); castle->SetGuildGradeSkillTime( gserver->getNowSecond() ); } } void ProcHelperWarNoticeRemainFieldTime(CNetMsg::SP& msg) { int zoneindex; int remainSec; RefMsg(msg) >> zoneindex >> remainSec; CNetMsg::SP rmsg(new CNetMsg); GuildWarNoticeRemainFieldTimeMsg(rmsg, zoneindex, remainSec); PCManager::instance()->sendToWarJoinUser(rmsg, zoneindex, false); } void ProcHelperWarNoticeEnd(CNetMsg::SP& msg) { int zoneindex; char bWinDefense; int ownerguildindex; CLCString ownerguildname(MAX_GUILD_NAME_LENGTH + 1); int ownercharindex; CLCString ownercharname(MAX_CHAR_NAME_LENGTH + 1); int nextmonth; int nextday; int nexthour; int nextwday; RefMsg(msg) >> zoneindex >> bWinDefense >> ownerguildindex >> ownerguildname >> ownercharindex >> ownercharname >> nextmonth >> nextday >> nexthour >> nextwday; { CNetMsg::SP rmsg(new CNetMsg); GuildWarEndMsg(rmsg, zoneindex, bWinDefense, ownerguildindex, ownerguildname, ownercharindex, ownercharname, nextmonth, nextday, nexthour, nextwday); PCManager::instance()->sendToAll(rmsg); } PCManager::map_t& playerMap = PCManager::instance()->getPlayerMap(); PCManager::map_t::iterator iter = playerMap.begin(); PCManager::map_t::iterator endIter = playerMap.end(); for (; iter != endIter; ++iter) { CPC* pc = (*iter).pPlayer; if (pc) { // 바로 보내기 CNetMsg::SP rmsg(new CNetMsg); StatusMsg(rmsg, pc); SEND_Q(rmsg, pc->m_desc ); } } // 공성 상태 갱신 : 진행중인 서브 서버는 직접 바꾸므로 스킵 CWarCastle* castle = CWarCastle::GetCastleObject(zoneindex); if(castle != NULL) { if( zoneindex == ZONE_DRATAN ) { { CNetMsg::SP rmsg(new CNetMsg); CastletowerQuartersListMsg( rmsg, (CDratanCastle*)castle ); castle->GetArea()->SendToAllClient(rmsg); } { CNetMsg::SP rmsg(new CNetMsg); GuildWarGateStateMsg(rmsg, 0xffffffff, 0xffffffff); castle->GetArea()->SendToAllClient(rmsg); } } if (!castle->CheckSubServer() && zoneindex == ZONE_MERAC) { // 상태 변경 castle->SetState(WCSF_NORMAL); // 시간 설정 castle->m_lastWarTime = castle->GetNextWarTime() + WCT_WAR; castle->SetNextWarTime(0); // 성주 설정 if (!bWinDefense) { if (ownerguildindex > 0) { castle->m_ownerGuildIndex = ownerguildindex; castle->m_ownerGuildName = ownerguildname; castle->m_ownerCharIndex = ownercharindex; castle->m_ownerCharName = ownercharname; } else castle->ResetOwner(); } // 기타 castle->SetNoticeWarTime(false); castle->SetNoticeRemain(9999); castle->m_defensePoint = 0; castle->m_gateState = 0; // 참여정보 초기화 castle->ResetJoinFlag(); // 참여 리스트 초기화 castle->RemoveAllJoinList(); } castle->EndWarRegenPoint(); } // 공성 상태 갱신 : 진행중인 서브 서버는 직접 바꾸므로 스킵 CDratanCastle * pCastle = CDratanCastle::CreateInstance(); if (!pCastle->CheckSubServer() && zoneindex == ZONE_DRATAN) { // 상태 변경 pCastle->SetState(WCSF_NORMAL); // 시간 설정 pCastle->m_lastWarTime = pCastle->GetNextWarTime() + WCT_WAR; pCastle->SetNextWarTime(0); // 성주 설정 if (!bWinDefense) { int i; CGuild* guild; int prevOwnerGuildIndex = pCastle->m_ownerGuildIndex; if (ownerguildindex > 0) { pCastle->m_ownerGuildIndex = ownerguildindex; pCastle->m_ownerGuildName = ownerguildname; pCastle->m_ownerCharIndex = ownercharindex; pCastle->m_ownerCharName = ownercharname; } else pCastle->ResetOwner(); // 성주가 바꿔서 길드명색을 다시 보내줌 guild = gserver->m_guildlist.findguild(prevOwnerGuildIndex); if(guild) { int guildMaxMember = guild->maxmember(); for(i=0; i<guildMaxMember; i++) { if(guild->member(i) && guild->member(i)->GetPC()) { GuildNameColorStateMsg(msg, guild->member(i)->GetPC() ); SEND_Q(msg , guild->member(i)->GetPC()->m_desc); } } } guild = gserver->m_guildlist.findguild(pCastle->m_ownerGuildIndex); if(guild) { int guildMaxMember = guild->maxmember(); for(i=0; i<guildMaxMember; i++) { if(guild->member(i) && guild->member(i)->GetPC()) { GuildNameColorStateMsg(msg, guild->member(i)->GetPC() ); SEND_Q(msg , guild->member(i)->GetPC()->m_desc); } } } } // 기타 pCastle->SetNoticeWarTime(false); pCastle->SetNoticeRemain(9999); pCastle->m_gateState = 0; // 참여정보 초기화 pCastle->ResetJoinFlag(); // 참여 리스트 초기화 pCastle->RemoveAllJoinList(); } } void ProcHelperPetCreateRep(CNetMsg::SP& msg) { int index; int owner; char typeGrade; RefMsg(msg) >> index >> owner >> typeGrade; bool bSuccess = false; CPC* pc = PCManager::instance()->getPlayerByCharIndex(owner); if (pc) { int itemdbindex = 0; const char* petTypeName; switch (typeGrade & PET_TYPE_MASK) { case PET_TYPE_HORSE: itemdbindex = PET_HORSE_ITEM_INDEX; petTypeName = "HORSE"; break; case PET_TYPE_BLUE_HORSE: itemdbindex = PET_BLUE_HORSE_ITEM_INDEX; petTypeName = "BLUE_HORSE"; break; case PET_TYPE_UNKOWN_HORSE: itemdbindex = PET_UNKOWN_HORSE_ITEM_INDEX; petTypeName = "UNKOWN_HORSE"; break; case PET_TYPE_DRAGON: itemdbindex = PET_DRAGON_ITEM_INDEX; petTypeName = "DRAGON"; break; case PET_TYPE_PINK_DRAGON: itemdbindex = PET_PINK_DRAGON_ITEM_INDEX; petTypeName = "PINK_DRAGON"; break; case PET_TYPE_UNKOWN_DRAGON: itemdbindex = PET_UNKOWN_DRAGON_ITEM_INDEX; petTypeName = "UNKOWN_DRAGON"; break; default: return ; } // Helper의 펫 지급 실패시 펫 아이템을 삭제하고 피리지급 if( index == -1 ) { CItem* item = pc->m_inventory.FindByDBIndex(itemdbindex, 0, 0); if( item ) { pc->m_inventory.decreaseItemCount(item, 1); int egg_index = 0; switch(itemdbindex) { case PET_HORSE_ITEM_INDEX: egg_index = PET_HORSE_EGG_INDEX; break; case PET_BLUE_HORSE_ITEM_INDEX: egg_index = PET_BLUE_HORSE_EGG_INDEX; break; case PET_UNKOWN_HORSE_ITEM_INDEX: egg_index = PET_UNKOWN_HORSE_EGG_INDEX; break; case PET_DRAGON_ITEM_INDEX: egg_index = PET_DRAGON_EGG_INDEX; break; case PET_PINK_DRAGON_ITEM_INDEX: egg_index = PET_PINK_DRAGON_EGG_INDEX; break; case PET_UNKOWN_DRAGON_ITEM_INDEX: egg_index = PET_UNKOWN_DRAGON_EGG_INDEX; break; } pc->GiveItem(egg_index, 0, 0, 1, true); } return; } CPet* pet = new CPet(pc, index, typeGrade, 1); if (pet) { // 펫의 이미 지급한 아이템의 옵션을 변경한닷 CItem* item = pc->m_inventory.FindByDBIndex(itemdbindex, 0, 0); if( item ) { item->unWearPos(); item->setPlus(index); item->setFlag(0); { CNetMsg::SP rmsg(new CNetMsg); ExPetStatusMsg(rmsg, pet); SEND_Q(rmsg, pc->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); ExPetSkillListMsg(rmsg, pet); SEND_Q(rmsg, pc->m_desc); } pc->m_inventory.sendOneItemInfo(item); ADD_TO_BILIST(pet, pc->m_petList, m_prevPet, m_nextPet); bSuccess = true; // TODO : petlog GAMELOG << init("PET CREATE", pc) << "TYPE" << delim << petTypeName << end; } if (!bSuccess) { if (item) delete item; delete pet; } } } } void ProcHelperPetDeleteRep(CNetMsg::SP& msg) { int index; int owner; RefMsg(msg) >> index >> owner; CPC* pc = PCManager::instance()->getPlayerByCharIndex(owner); if (pc) { pc->DelPet(index); } } void ProcHelperGuildStashHistoryRep(CNetMsg::SP& msg) { int charindex; int errcode; int month[7] = {0, 0, 0, 0, 0, 0, 0}; int day[7] = {0, 0, 0, 0, 0, 0, 0}; LONGLONG money[7] = {0, 0, 0, 0, 0, 0, 0}; RefMsg(msg) >> charindex >> errcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (!pc) return ; if (errcode == MSG_HELPER_GUILD_STASH_ERROR_OK) { int i; for (i = 0; i < 7; i++) { RefMsg(msg) >> month[i] >> day[i] >> money[i]; } } { CNetMsg::SP rmsg(new CNetMsg); GuildStashHistoryRepMsg(rmsg, (MSG_GUILD_STASH_ERROR_TYPE)errcode, month, day, money); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperGuildStashViewRep(CNetMsg::SP& msg) { int charindex; int errcode; LONGLONG money = 0; RefMsg(msg) >> charindex >> errcode >> money; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (!pc) return ; { CNetMsg::SP rmsg(new CNetMsg); GuildStashViewRepMsg(rmsg, (MSG_GUILD_STASH_ERROR_TYPE)errcode, money); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperGuildStashTakeRep(CNetMsg::SP& msg) { int guildindex; int charindex; int errcode; LONGLONG money = 0; LONGLONG balance = 0; RefMsg(msg) >> guildindex >> charindex >> errcode >> money >> balance; bool bRollback = false; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if (!pc) { // 찾으려던 사람이 없어서 롤백 bRollback = true; } else { if (errcode == MSG_HELPER_GUILD_STASH_ERROR_OK) { // 돈을 생성 지급 pc->m_inventory.increaseMoney(money); { // 성공 메시지 전달 CNetMsg::SP rmsg(new CNetMsg); GuildStashTakeRepMsg(rmsg, MSG_GUILD_STASH_ERROR_OK); SEND_Q(rmsg, pc->m_desc); } GAMELOG << init("GUILD STASH TAKE MONEY", pc) << "GUILD" << delim << guildindex << delim << "MONEY" << delim << money << delim << "BALANCE" << delim << balance << end; } else { // 실패 알림 GAMELOG << init("GUILD STASH TAKE MONEY FAIL", pc) << "GUILD" << delim << guildindex << delim << "ERROR" << delim << errcode << end; CNetMsg::SP rmsg(new CNetMsg); GuildStashTakeRepMsg(rmsg, (MSG_GUILD_STASH_ERROR_TYPE)errcode); SEND_Q(rmsg, pc->m_desc); } } if (bRollback && errcode == MSG_HELPER_GUILD_STASH_ERROR_OK) { if (gserver->isRunHelper()) { if (pc) GAMELOG << init("GUILD STASH ROLLBACK TAKE MONEY", pc); else GAMELOG << init("GUILD STASH ROLLBACK TAKE MONEY") << "CHARINDEX" << delim << charindex << delim; GAMELOG << "GUILD" << delim << guildindex << delim << "MONEY" << delim << money << delim << "BALANCE" << delim << balance << end; { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashRollbackMsg(rmsg, guildindex, money); SEND_Q(rmsg, gserver->m_helper); } } else { if (pc) GAMELOG << init("GUILD STASH FAIL ROLLBACK TAKE MONEY", pc); else GAMELOG << init("GUILD STASH FAIL ROLLBACK TAKE MONEY") << "CHARINDEX" << delim << charindex << delim; GAMELOG << "GUILD" << delim << guildindex << delim << "MONEY" << delim << money << delim << "BALANCE" << delim << balance << end; } } } void ProcHelperGuildStashSaveTaxRep(CNetMsg::SP& msg) { int errcode; int guildindex = 0; int zoneindex = 0; LONGLONG taxItem; LONGLONG taxProduce; RefMsg(msg) >> errcode >> guildindex >> zoneindex >> taxItem >> taxProduce; switch (errcode) { case MSG_HELPER_GUILD_STASH_ERROR_OK: { CDBCmd cmd; cmd.Init(&gserver->m_dbcastle); struct tm tmCur = NOW(); std::string update_castle_query = boost::str(boost::format( "UPDATE t_castle SET a_tax_wday=%1%, a_tax_item = a_tax_item - %2%, a_tax_produce = a_tax_produce - %3% WHERE a_zone_index = %4%") % tmCur.tm_wday % taxItem % taxProduce % zoneindex); cmd.SetQuery(update_castle_query); if (!cmd.Update()) { GAMELOG << init("TAX RESET FAIL") << "ZONE" << delim << zoneindex << delim << "GUILD" << delim << guildindex << delim << "TAX ITEM" << delim << taxItem << delim << "TAX PRODUCT" << delim << taxProduce << end; } else { GAMELOG << init("TAX RESET SUCCESS") << "ZONE" << delim << zoneindex << delim << "GUILD" << delim << guildindex << delim << "TAX ITEM" << delim << taxItem << delim << "TAX PRODUCT" << delim << taxProduce << end; } } break; default: GAMELOG << init("TAX SAVE FAIL") << "ZONE" << delim << zoneindex << delim << "GUILD" << delim << guildindex << delim << "TAX ITEM" << delim << taxItem << delim << "TAX PRODUCT" << delim << taxProduce << end; break; } } void ProcHelperTeacherLoadRep(CNetMsg::SP& msg) { CLCString idname(MAX_ID_NAME_LENGTH + 1); int charindex; RefMsg(msg) >> idname >> charindex; CDescriptor* d = DescManager::instance()->getDescById(idname); if( d && d->m_pChar && d->m_pChar->m_index ) { char bteacher; RefMsg(msg) >> d->m_pChar->m_cntTeachingStudent >> d->m_pChar->m_guardian >> d->m_pChar->m_superstone >> d->m_pChar->m_cntFailStudent >> d->m_pChar->m_cntCompleteStudent >> d->m_pChar->m_teachType >> d->m_pChar->m_fame >> bteacher; if(bteacher) d->m_pChar->m_bTeacher = true; else d->m_pChar->m_bTeacher = false; if( d->m_pChar->m_teachType == MSG_TEACH_NO_STUDENT_TYPE) return; if( d->m_pChar->m_teachType == MSG_TEACH_TEACHER_TYPE ) { RefMsg(msg) >> d->m_pChar->m_teachTime[0] >> d->m_pChar->m_teachTime[1]; CLCString teachName(MAX_CHAR_NAME_LENGTH + 1); for(int i = 0; i < TEACH_MAX_STUDENTS; i++) { RefMsg(msg) >> d->m_pChar->m_teachIdx[i] >> d->m_pChar->m_teachJob[i] >> d->m_pChar->m_teachJob2[i] >> d->m_pChar->m_teachLevel[i] >> teachName; strcpy(d->m_pChar->m_teachName[i], teachName); if( d->m_pChar->m_teachIdx[i] != -1 ) { CPC* student = PCManager::instance()->getPlayerByCharIndex(d->m_pChar->m_teachIdx[i]); if( student ) { d->m_pChar->m_teachIdx[i] = student->m_index; d->m_pChar->m_teachJob[i] = student->m_job; d->m_pChar->m_teachJob2[i] = student->m_job2; d->m_pChar->m_teachLevel[i] = student->m_level; strcpy(d->m_pChar->m_teachName[i], student->GetName()); { // 접속해 있으면 로그인 했다고 보내주자. CNetMsg::SP rmsg(new CNetMsg); TeachLoginMsg(rmsg, d->m_pChar); SEND_Q(rmsg, student->m_desc); } } } } } else if( d->m_pChar->m_teachType == MSG_TEACH_STUDENT_TYPE ) // 학생 { CLCString teachName(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> d->m_pChar->m_teachIdx[0] >> d->m_pChar->m_teachJob[0] >> d->m_pChar->m_teachJob2[0] >> d->m_pChar->m_teachLevel[0] >> teachName >> d->m_pChar->m_teachTime[0]; strcpy(d->m_pChar->m_teachName[0], teachName); // 자신이 학생이면 idx[1]을 선생의 명성수치로, idx[2]를 선생의 양성중이 초보로, time[1]을 완료인원, time[2]을 실패인원으로 쓴다. RefMsg(msg) >> d->m_pChar->m_teachIdx[1] >> d->m_pChar->m_teachIdx[2] >> d->m_pChar->m_teachTime[1] >> d->m_pChar->m_teachTime[2]; if( d->m_pChar->m_teachIdx[0] != -1 ) { CPC* teacher = PCManager::instance()->getPlayerByCharIndex(d->m_pChar->m_teachIdx[0]); if( teacher ) { d->m_pChar->m_teachIdx[0] = teacher->m_index; d->m_pChar->m_teachJob[0] = teacher->m_job; d->m_pChar->m_teachJob2[0] = teacher->m_job2; d->m_pChar->m_teachLevel[0] = teacher->m_level; strcpy(d->m_pChar->m_teachName[0], teacher->GetName()); { // 접속해 있으면 로그인 했다고 보내주자. CNetMsg::SP rmsg(new CNetMsg); TeachLoginMsg(rmsg, d->m_pChar); SEND_Q(rmsg, teacher->m_desc); } } } } else // MSG_TEACH_LIMITE_DAY_FAIL || MSG_TEACH_NO_TYPE, { RefMsg(msg) >> d->m_pChar->m_teachTime[0]; } } } void ProcHelperFameupRep(CNetMsg::SP& msg) { int teachidx; int fameup; RefMsg(msg) >> teachidx >> fameup; CPC* tch = PCManager::instance()->getPlayerByCharIndex(teachidx); if(tch) { GAMELOG << init("TEACH_FAME_UP") << tch->m_name << delim << tch->m_nick << delim << tch->m_desc->m_idname << delim << tch->m_fame << end; #if defined( EVENT_TEACH ) || defined ( EVENT_CHILDERN_DAY ) tch->m_fame = tch->m_fame + fameup * 2; #else tch->m_fame = tch->m_fame + fameup; #endif //0627 if( tch->m_displayCanSstone && ((tch->m_fame >= 200 && tch->m_superstone < 1 ) || (tch->m_fame >= 300 && tch->m_superstone < 2 ) || (tch->m_fame >= 500 && tch->m_superstone < 3) || (tch->m_fame >= 800 && tch->m_superstone < 4) || (tch->m_fame >= 1200 && tch->m_superstone < 5) || (tch->m_fame >= 1700 && tch->m_superstone < 6) || (tch->m_fame >= 2300 && tch->m_superstone < 7)) ) { CNetMsg::SP rmsg(new CNetMsg); SysEnableSuperStoneMsg(rmsg, tch->m_fame); SEND_Q(rmsg, tch->m_desc); tch->m_displayCanSstone = false; } { CNetMsg::SP rmsg(new CNetMsg); StatusMsg(rmsg, tch); SEND_Q(rmsg, tch->m_desc); } } else { GAMELOG << init("TEACH_FAME_UP_HELPER_REP-notTeacher") << teachidx << delim << fameup << end; } } void ProcHelperPartyMemberChangeJob(CNetMsg::SP& msg) { int nBossIndex; int nCharIndex; char job1; char job2; RefMsg(msg) >> nBossIndex >> nCharIndex >> job1 >> job2; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty) { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::makeChangeJob(rmsg, nCharIndex, job1, job2); pParty->SendToAllPC(rmsg, nCharIndex); } } void ProcHelperPartyChat(CNetMsg::SP& msg) { int nBossIndex; int nCharIndex; CLCString strName(MAX_CHAR_NAME_LENGTH + 1); CLCString strChat(1000); RefMsg(msg) >> nBossIndex >> nCharIndex >> strName >> strChat; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty) { { CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_PARTY, nCharIndex, strName, "", strChat); pParty->SendToAllPC(rmsg); } #ifdef GMTOOL if(pParty->m_bGmtarget) { bool bSend = false; for(int i = 0; i < MAX_PARTY_MEMBER; ++i) { const CPartyMember* member = pParty->GetMemberByListIndex(i); if(member && member->GetMemberPCPtr() && member->GetMemberPCPtr()->m_bGmMonitor) { CNetMsg::SP rmsg(new CNetMsg); MsgrNoticeGmChatMonitorPartyMsg(rmsg, -1, 1, 1, 0, gserver->m_serverno, gserver->m_subno, -1, strChat, nBossIndex, strName, member->GetMemberPCPtr()->m_index, member->GetMemberPCPtr()->m_name); SEND_Q(rmsg, gserver->m_messenger); bSend = true; } } if(!bSend) { pParty->m_bGmtarget = false; } } #endif // GMTOOL } } void ProcHelperPartyRecallPrompt(CNetMsg::SP& msg) { int nBossIndex; int nReqIndex; CLCString strReqName(MAX_CHAR_NAME_LENGTH + 1); char cIsInCastle = 0; int nGuildIndex = 0; char bUseContinent = false; int zoneID = -1; CPos pos(0, 0, 0, 0, 0); RefMsg(msg) >> nBossIndex >> nReqIndex >> strReqName >> cIsInCastle >> nGuildIndex >> bUseContinent >> zoneID >> pos.m_x >> pos.m_z >> pos.m_yLayer; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty == NULL) { return; } pParty->SetPartyRecallUseInfo(zoneID, pos, nGuildIndex, cIsInCastle, nReqIndex); CNetMsg::SP rmsg(new CNetMsg); ExPartyRecallPromptMsg(rmsg, nReqIndex, strReqName); #ifdef CONTINENT_PARTY_RECALL if(bUseContinent == false) { pParty->SendToPartyRecallPC(rmsg, nReqIndex); } else { pParty->SendToSameContinentPC(rmsg, nReqIndex); } #else pParty->SendToPartyRecallPC(rmsg, nReqIndex); #endif } void ProcHelperPartyRecallConfirm(CNetMsg::SP& msg) { int nBossIndex; int reqindex; int repindex; char yesno; CLCString strReqName(MAX_CHAR_NAME_LENGTH + 1); CLCString strRepName(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> nBossIndex >> reqindex >> strReqName >> repindex >> strRepName >> yesno; CPC* pReqPC = PCManager::instance()->getPlayerByCharIndex(reqindex); CPC* pResPC = PCManager::instance()->getPlayerByCharIndex(repindex); if (pResPC == NULL || pResPC->m_party == NULL) return; CPartyMember* pPartyMember = pResPC->m_party->GetMemberByCharIndex(reqindex); if (pPartyMember == NULL) { // 취소 명령 전달 CNetMsg::SP rmsg(new CNetMsg); WarpErrorMsg(rmsg, MSG_WARP_ERROR_NOTCHAR, strReqName); SEND_Q(rmsg, pResPC->m_desc); pResPC->getPartyRecallInfo()->resetPartyRecallInfo(); return; } int moveZoneID = pResPC->getPartyRecallInfo()->getZoneID(); CPos* pos = pResPC->getPartyRecallInfo()->getPos(); int guildIndex = pResPC->getPartyRecallInfo()->getGuildIndex(); char cIsInCastle = pResPC->getPartyRecallInfo()->getIsInCastle(); if (yesno) { if (moveZoneID == ZONE_MONDSHINE) { if( !(pResPC->m_questList.FindQuest(249, QUEST_STATE_DONE) || pResPC->m_questList.FindQuest(249, QUEST_STATE_RUN)) ) { if (pReqPC != NULL) { CNetMsg::SP rmsg(new CNetMsg); ExPartyRecallCancelMsg(rmsg, reqindex, strReqName, repindex, strRepName); SEND_Q(rmsg, pReqPC->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); WarpCancelMsg(rmsg, pResPC); SEND_Q(rmsg, pResPC->m_desc); } pResPC->getPartyRecallInfo()->resetPartyRecallInfo(); return ; } } if( moveZoneID != -1 ) { CNetMsg::SP rmsg(new CNetMsg); HelperPartyRecallProcMsg(rmsg, nBossIndex, repindex, moveZoneID, pos, cIsInCastle, guildIndex); SEND_Q(rmsg, gserver->m_helper); pResPC->getPartyRecallInfo()->resetPartyRecallInfo(); } else { // 존을 못찾아 거절로 전송 if (pReqPC != NULL) { CNetMsg::SP rmsg(new CNetMsg); ExPartyRecallCancelMsg(rmsg, reqindex, strReqName, repindex, strRepName); SEND_Q(rmsg, pReqPC->m_desc); } { pResPC->getPartyRecallInfo()->resetPartyRecallInfo(); CNetMsg::SP rmsg(new CNetMsg); HelperPartyRecallConfirmFail(rmsg); SEND_Q(rmsg, pResPC->m_desc); } } } else { if (pReqPC != NULL) { // 존을 못찾아 거절로 전송 { CNetMsg::SP rmsg(new CNetMsg); ExPartyRecallCancelMsg(rmsg, reqindex, strReqName, repindex, strRepName); SEND_Q(rmsg, pReqPC->m_desc); } { pResPC->getPartyRecallInfo()->resetPartyRecallInfo(); CNetMsg::SP rmsg(new CNetMsg); HelperPartyRecallConfirmFail(rmsg); SEND_Q(rmsg, pResPC->m_desc); } } } pResPC->m_party->deletePartyRecallMember(repindex); } void ProcHelperPartyRecallProc(CNetMsg::SP& msg) { int nBossIndex; int nRepIndex; int nZone; float x; float z; char nYlayer; char cIsInCastle = 0; int nGuildIndex = 0; RefMsg(msg) >> nBossIndex >> nRepIndex >> nZone >> x >> z >> nYlayer >> cIsInCastle >> nGuildIndex; CPC* pRepPC = PCManager::instance()->getPlayerByCharIndex(nRepIndex); if (pRepPC) { if (pRepPC->IsParty() && pRepPC->m_party->GetBossIndex() == nBossIndex) { if (cIsInCastle) { if (pRepPC->m_guildInfo && pRepPC->m_guildInfo->guild() && pRepPC->m_guildInfo->guild()->index() == nGuildIndex) { if((pRepPC->m_pZone->m_index != nZone)) { pRepPC->SetPlayerState(PLAYER_STATE_CASH_ZONE_MOVE); } if(!GoZone(pRepPC, nZone, nYlayer, x, z)) { if(pRepPC->IsSetPlayerState(PLAYER_STATE_CASH_ZONE_MOVE)) pRepPC->ResetPlayerState(PLAYER_STATE_CASH_ZONE_MOVE); } } else { CNetMsg::SP rmsg(new CNetMsg); HelperPartyRecallConfirmFail(rmsg); SEND_Q(rmsg, pRepPC->m_desc); return ; } } else { { CNetMsg::SP rmsg(new CNetMsg); WarpStartMsg(rmsg, pRepPC); SEND_Q(rmsg, pRepPC->m_desc); } if((pRepPC->m_pZone->m_index != nZone)) { pRepPC->SetPlayerState(PLAYER_STATE_CASH_ZONE_MOVE); } if(!GoZone(pRepPC, nZone, nYlayer, x, z)) { if(pRepPC->IsSetPlayerState(PLAYER_STATE_CASH_ZONE_MOVE)) pRepPC->ResetPlayerState(PLAYER_STATE_CASH_ZONE_MOVE); } { CNetMsg::SP rmsg(new CNetMsg); WarpEndMsg(rmsg, pRepPC); SEND_Q(rmsg, pRepPC->m_desc); } } } } } void ProcHelperPartyInviteReq(CNetMsg::SP& msg) { int nBossIndex; CLCString strBossName(MAX_CHAR_NAME_LENGTH + 1); int nBossLevel; int nTargetIndex; char nPartyType; RefMsg(msg) >> nBossIndex >> strBossName >> nBossLevel >> nTargetIndex >> nPartyType; GAMELOG << init("PARTY DEBUG HELPER INVITE REQ") << "nBossIndex" << delim << nBossIndex << delim << "strBossName" << delim << strBossName << delim << "nBossLevel" << delim << nBossLevel << delim << "nTargetIndex" << delim << nTargetIndex << delim << "nPartyType" << delim << nPartyType << end; CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); if (!pTargetPC) return ; CPC* pBossPC = PCManager::instance()->getPlayerByCharIndex(nBossIndex); if (!pBossPC) return ; if (pTargetPC->m_Exped || pBossPC->m_Exped ) // 원정대 상태에서 파티초대 불가 return; #if defined (LC_USA) if(pBossPC->IsSetPlayerState(PLAYER_STATE_PKMODE) || pTargetPC->IsSetPlayerState(PLAYER_STATE_PKMODE)) { CNetMsg::SP rmsg(new CNetMsg); HelperPartyInviteRepMsg(rmsg, nBossIndex, strBossName, nTargetIndex, pTargetPC->GetName(), nPartyType, MSG_HELPER_PARTY_ERROR_INVITE_PVP, pTargetPC->m_level); SEND_Q(rmsg, gserver->m_helper); return ; } #endif // #if defined (LC_USA) // 파티 타입이 2이면 tch와 ch의 레벨 차이를 검사 // 차이가 +- 10이상이면 ERROR; if (nPartyType == MSG_PARTY_TYPE_BATTLE) { if (ABS(pTargetPC->m_level - nBossLevel) > 10) { CNetMsg::SP rmsg(new CNetMsg); HelperPartyInviteRepMsg(rmsg, nBossIndex, strBossName, nTargetIndex, pTargetPC->GetName(), nPartyType, MSG_HELPER_PARTY_ERROR_INVITE_LEVEL, pTargetPC->m_level); SEND_Q(rmsg, gserver->m_helper); return ; } } { CNetMsg::SP rmsg(new CNetMsg); HelperPartyInviteRepMsg(rmsg, nBossIndex, strBossName, nTargetIndex, pTargetPC->GetName(), nPartyType, MSG_HELPER_PARTY_ERROR_INVITE_OK, pTargetPC->m_level); SEND_Q(rmsg, gserver->m_helper); } } void ProcHelperPartyInviteRep(CNetMsg::SP& msg) { int nBossIndex; CLCString strBossName(MAX_CHAR_NAME_LENGTH + 1); int nTargetIndex; CLCString strTargetName(MAX_CHAR_NAME_LENGTH + 1); char cPartyType1, cPartyType2, cPartyType3; int nErrorCode; RefMsg(msg) >> nBossIndex >> strBossName >> nTargetIndex >> strTargetName >> cPartyType1 >> cPartyType2 >> cPartyType3 >> nErrorCode; GAMELOG << init("PARTY DEBUG HELPER INVITE REP") << "nBossIndex" << delim << nBossIndex << delim << "strBossName" << delim << strBossName << delim << "nTargetIndex" << delim << nTargetIndex << delim << "strTargetName" << delim << strTargetName << delim << "nPartyType1" << delim << cPartyType1 << delim << "nErrorCode" << delim << nErrorCode << end; CPC* pBossPC = PCManager::instance()->getPlayerByCharIndex(nBossIndex); CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); CParty* pParty = NULL; // 파티 관련 서버 다운되는 현상 방지 if(!pBossPC || !pTargetPC) { GAMELOG << init("PARTY Error : NULL Check 1") << end; return; } switch (nErrorCode) { case MSG_HELPER_PARTY_ERROR_INVITE_OK: { pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty) { // 기존 파티에 초대 상태로 pParty->SetRequest(nTargetIndex, strTargetName); if (pTargetPC) pTargetPC->m_party = pParty; } else { // 신규 파티 #ifdef PARTY_ONLINE pParty = new CParty(cPartyType1, nBossIndex, strBossName, pBossPC, nTargetIndex, strTargetName, pBossPC->m_level ); #else pParty = new CParty(cPartyType1, nBossIndex, strBossName, pBossPC, nTargetIndex, strTargetName); #endif // PARTY_ONLINE if (pBossPC) pBossPC->m_party = pParty; if (pTargetPC) pTargetPC->m_party = pParty; gserver->m_listParty.insert(map_listparty_t::value_type(pParty->GetBossIndex(), pParty)); } { CNetMsg::SP rmsg(new CNetMsg); PartyInviteMsg(rmsg, cPartyType1, cPartyType2, cPartyType3, nBossIndex, strBossName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); if (pTargetPC) SEND_Q(rmsg, pTargetPC->m_desc); } } break; case MSG_HELPER_PARTY_ERROR_INVITE_ALREADY_ME: { CNetMsg::SP rmsg(new CNetMsg); PartyErrorMsg(rmsg, MSG_PARTY_ERROR_ALREADY_ME); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } break; case MSG_HELPER_PARTY_ERROR_INVITE_DIFF_TYPE: { CNetMsg::SP rmsg(new CNetMsg); PartyErrorMsg(rmsg, MSG_PARTY_ERROR_DIFF_TYPE); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } break; case MSG_HELPER_PARTY_ERROR_INVITE_LEVEL: { CNetMsg::SP rmsg(new CNetMsg); PartyErrorMsg(rmsg, MSG_PARTY_ERROR_INVALID_LEVEL); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } break; case MSG_HELPER_PARTY_ERROR_INVITE_ALREADY_TARGET: { CNetMsg::SP rmsg(new CNetMsg); PartyErrorMsg(rmsg, MSG_PARTY_ERROR_ALREADY_TARGET); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } break; case MSG_HELPER_PARTY_ERROR_INVITE_FULL: { CNetMsg::SP rmsg(new CNetMsg); PartyErrorMsg(rmsg, MSG_PARTY_ERROR_FULL); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } break; case MSG_HELPER_PARTY_ERROR_INVITE_ALREADY_REQUEST: { CNetMsg::SP rmsg(new CNetMsg); PartyErrorMsg(rmsg, MSG_PARTY_ERROR_ALREADY_REQUEST); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } break; #if defined (LC_USA) case MSG_HELPER_PARTY_ERROR_INVITE_PVP: { CNetMsg::SP rmsg(new CNetMsg); PartyErrorMsg(rmsg, MSG_PARTY_ERROR_PVP); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } break; #endif // #if defined (LC_USA) } } void ProcHelperPartyAllowRep(CNetMsg::SP& msg) { int nBossIndex; int nTargetIndex; CLCString strTargetName(MAX_CHAR_NAME_LENGTH + 1); int nErrorCode; RefMsg(msg) >> nBossIndex >> nTargetIndex >> strTargetName >> nErrorCode; GAMELOG << init("PARTY DEBUG HELPER ALLOW REP") << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "strTargetName" << delim << strTargetName << delim << "nErrorCode" << delim << nErrorCode << end; CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); // 파티 관련 서버 다운되는 현상 방지 if(!pTargetPC) { GAMELOG << init("PARTY Error : NULL Check ALLOW REP 1") << end; return; } CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty == NULL) { GAMELOG << init("PARTY DEBUG HELPER ALLOW REP : NOT FOUND PARTY") << end; return ; } int nListIndex = pParty->JoinRequest(strTargetName, pTargetPC); if (nListIndex == -1) { GAMELOG << init("PARTY DEBUG HELPER ALLOW REP : CANNOT JOIN") << end; return ; } // 파티매칭에도 현재 인원을 업데이트 해줍니다. CPartyMatchParty * pPartyMatch = gserver->FindPartyMatchPartyByBossIndex( pParty->GetBossIndex() ); if( pPartyMatch ) { pPartyMatch->SetMemberCount( pParty->GetMemberCount() ); } { // 파티원들에게 결과 알리기 CNetMsg::SP addmsg(new CNetMsg); PartyAddMsg(addmsg, nTargetIndex, strTargetName, pTargetPC, ((pParty->GetBossIndex() == nTargetIndex) ? 1 : 0)); for (int i = 0; i < MAX_PARTY_MEMBER; i++) { const CPartyMember* pMember = pParty->GetMemberByListIndex(i); if (pMember && i != nListIndex) { // 타인에게 target을 추가하고 if (pMember->GetMemberPCPtr()) SEND_Q(addmsg, pMember->GetMemberPCPtr()->m_desc) // target에게는 타인을 추가 if (pTargetPC) { CNetMsg::SP rmsg(new CNetMsg); PartyAddMsg(rmsg, pMember->GetCharIndex(), pMember->GetCharName(), pMember->GetMemberPCPtr(), ((pParty->GetBossIndex() == pMember->GetCharIndex()) ? 1 : 0)); SEND_Q(rmsg, pTargetPC->m_desc); } } } } #ifdef GMTOOL CPC* boss = PCManager::instance()->getPlayerByCharIndex(nBossIndex); if((pTargetPC && pTargetPC->m_bGmMonitor) || (boss && boss->m_bGmMonitor)) { pParty->m_bGmtarget = true; } #endif // GMTOOL } void ProcHelperPartyRejectRep(CNetMsg::SP& msg) { int nBossIndex; int nTargetIndex; int nErrorCode; RefMsg(msg) >> nBossIndex >> nTargetIndex >> nErrorCode; GAMELOG << init("PARTY DEBUG HELPER REJECT REP") << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "nErrorCode" << delim << nErrorCode << end; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (!pParty) { GAMELOG << init("PARTY DEBUG HELPER REJECT REP : NOT FOUND PARTY") << end; return ; } if (pParty->GetRequestIndex() < 1) { GAMELOG << init("PARTY DEBUG HELPER REJECT REP : NOT FOUND REQUEST") << end; return ; } CPC* pBossPC = pParty->GetMemberByListIndex(0)->GetMemberPCPtr(); CPC* pRequestPC = PCManager::instance()->getPlayerByCharIndex(pParty->GetRequestIndex()); if (nErrorCode == MSG_HELPER_PARTY_ERROR_REJECT_OK) { { CNetMsg::SP rmsg(new CNetMsg); if (pParty->GetRequestIndex() == nTargetIndex) PartyMsg(rmsg, MSG_PARTY_REJECT_DEST); else if (pParty->GetBossIndex() == nTargetIndex) PartyMsg(rmsg, MSG_PARTY_REJECT_SRC); else { GAMELOG << init("PARTY DEBUG HELPER REJECT REP : NO MATCH CHAR") << end; return ; } pParty->SetMemberPCPtr(pParty->GetRequestIndex(), NULL); if (pBossPC) { SEND_Q(rmsg, pBossPC->m_desc); } if (pRequestPC) { SEND_Q(rmsg, pRequestPC->m_desc); pRequestPC->m_party = NULL; } } pParty->SetRequest(-1, ""); if (pParty->GetMemberCount() < 2) { // 파티 종료 #ifdef EXTREME_CUBE if(pParty->m_cubeUniqueIdx != -1) { CCubeMemList* memlist = gserver->m_extremeCube.FindMemList(pParty); if(memlist && memlist->IsPartyCubeMemList()) { memlist->GetOutAll(); ((CPartyCubeMemList*)memlist)->SetParty(NULL); } } #endif // EXTREME_CUBE // 파티 지우기 gserver->m_listParty.erase(pParty->GetBossIndex()); pParty->SetEndParty(); delete pParty; } } } void ProcHelperPartyQuitRep(CNetMsg::SP& msg) { int nBossIndex; int nTargetIndex; int nErrorCode; int nNewBossIndex; CLCString strNewBossName(MAX_CHAR_NAME_LENGTH + 1); CLCString strOldBossName(MAX_CHAR_NAME_LENGTH + 1); bool bEndMonsterCombo = false; RefMsg(msg) >> nBossIndex >> nTargetIndex >> nErrorCode >> nNewBossIndex >> strNewBossName; GAMELOG << init("PARTY DEBUG HELPER QUIT REP") << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "nErrorCode" << delim << nErrorCode << delim << "nNewBossIndex" << delim << nNewBossIndex << delim << "strNewBossName" << delim << strNewBossName << end; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (!pParty) { GAMELOG << init("PARTY DEBUG HELPER QUIT REP : NOT FOUND PARTY") << end; return ; } strOldBossName = pParty->GetMemberByListIndex(0)->GetCharName(); CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); if (pTargetPC) { // 콤보 area에 있는 pc 파티 탈퇴하면 콤보존 나감 if(pTargetPC->m_pZone->IsComboZone()) { CZone* pZone = gserver->FindZone(ZONE_DRATAN); if (pZone == NULL) return; GAMELOG << init("GET OUT COMBO AREA BY PARTY QUIT", pTargetPC) << "AREA INDEX: " << pTargetPC->m_pArea->m_index << "COMBO INDEX: " << pTargetPC->m_pArea->m_monsterCombo->m_nIndex << end; int extra = 0; GoZoneForce(pTargetPC, pZone->m_index, pZone->m_zonePos[extra][0], // ylayer GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); // z bEndMonsterCombo = true; } #ifdef EXTREME_CUBE // 큐브존에 있는 PC 파티 탈퇴하면 큐브존 나감 if(pTargetPC->m_pZone) { if(pTargetPC->m_pZone->IsExtremeCube()) { CCubeMemList* memlist; memlist = gserver->m_extremeCube.FindMemList(pParty); if(memlist) { CZone* pZone = gserver->FindZone(ZONE_MERAC); if (pZone == NULL) return; int extra = 0; GoZoneForce(pTargetPC, pZone->m_index, pZone->m_zonePos[extra][0], // ylayer GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); // z GAMELOG << init("GET OUT CUBE BY PARTY QUIT", pTargetPC) << pTargetPC->m_pZone->m_index << end; // memlist->DelPC(pTargetPC); } } } else { GAMELOG << init("GET OUT CUBE BY PARTY QUIT", pTargetPC) << "ZONE (NULL)" << end; } #endif // EXTREME_CUBE // 인존에 있는 PC 파티 탈퇴하면 인존을 나감(멤버) if(pTargetPC->m_pZone !=NULL && (pTargetPC->m_pZone->IsExpedRaidZone() || pTargetPC->m_pZone->IsPartyRaidZone()) && pTargetPC->m_nJoinInzone_ZoneNo >=0 && pTargetPC->m_nJoinInzone_RoomNo >= 0) { CNetMsg::SP rmsg(new CNetMsg); RaidInzoneQuitReq(rmsg,1,0); do_Raid(pTargetPC, rmsg); } if( pTargetPC->m_party && pTargetPC->m_party != pParty) { // 가입되있는 파티와 탈퇴하는 파티가 다른 경우는 // 파티 초기화 제외 } else { pTargetPC->CancelDamageLink(); pTargetPC->m_party = NULL; } } pParty->SetMemberPCPtr(nTargetIndex, NULL); pParty->DeleteMember(nTargetIndex); #ifdef GMTOOL if( pTargetPC ) { if(pTargetPC->m_bGmMonitor) { pParty->m_bGmtarget = false; } } #endif // GMTOOL if (nErrorCode == MSG_HELPER_PARTY_ERROR_QUIT_END || pParty->GetBossIndex() != nNewBossIndex) { if (pTargetPC) { // 파티 해체 알림 CNetMsg::SP rmsg(new CNetMsg); PartyMsg(rmsg, MSG_PARTY_END); SEND_Q(rmsg, pTargetPC->m_desc); } if(pParty->m_comboAreaIndex != -1 && bEndMonsterCombo) { int i; CArea* area; i = gserver->m_comboZone->FindComboArea(pParty->m_comboAreaIndex); if(i != -1) { area = gserver->m_comboZone->m_area + i; GAMELOG << init("CLOSE COMBO AREA") << "BY Party End" << "AREA INDEX: " << area->m_index << "COMBO INDEX: " << area->m_monsterCombo->m_nIndex << end; area->CloseComboZone(); } } #ifdef EXTREME_CUBE if(pParty->m_cubeUniqueIdx != -1) { CCubeMemList* memlist = gserver->m_extremeCube.FindMemList(pParty); if(memlist && memlist->IsPartyCubeMemList()) { memlist->GetOutAll(); ((CPartyCubeMemList*)memlist)->SetParty(NULL); } } #endif // EXTREME_CUBE // 파티 지우기 gserver->m_listParty.erase(pParty->GetBossIndex()); pParty->SetEndParty(); delete pParty; } else { { // 파티원 나감 CNetMsg::SP rmsg(new CNetMsg); PartyDelMsg(rmsg, false, nTargetIndex); if (pTargetPC) SEND_Q(rmsg, pTargetPC->m_desc); pParty->SendToAllPC(rmsg, nTargetIndex); } // 파티매칭에도 현재 인원을 업데이트 해줍니다. CPartyMatchParty * pMatchParty = gserver->FindPartyMatchPartyByBossIndex( nBossIndex ); // 보스 변경 알림 if (nBossIndex != nNewBossIndex) { if (pMatchParty) { pMatchParty->SetBossIndex(pParty->GetBossIndex()); pMatchParty->SetBossName(pParty->GetMemberByListIndex(0)->GetCharName()); gserver->m_listPartyMatchParty.erase(nBossIndex); gserver->m_listPartyMatchParty.insert(map_listPartyMatchParty_t::value_type(pParty->GetBossIndex(), pMatchParty)); } { CNetMsg::SP rmsg(new CNetMsg); PartyChangeBoss(rmsg, strOldBossName, nNewBossIndex, strNewBossName, false); pParty->SendToAllPC(rmsg); } } // 파티매칭에도 현재 인원을 업데이트 해줍니다. if( pMatchParty ) { pMatchParty->SetMemberCount( pParty->GetMemberCount() ); } } } void ProcHelperPartyKickRep(CNetMsg::SP& msg) { int nBossIndex; int nTargetIndex; int nErrorCode; bool bEndMonsterCombo = false; RefMsg(msg) >> nBossIndex >> nTargetIndex >> nErrorCode; GAMELOG << init("PARTY DEBUG HELPER KICK REP") << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "nErrorCode" << delim << nErrorCode << end; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (!pParty) { GAMELOG << init("PARTY DEBUG HELPER KICK REP : NOT FOUND PARTY") << end; return ; } CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); if (pTargetPC && pTargetPC->m_party && pTargetPC->m_party == pParty) { // 콤보 area에 있는 pc 파티 탈퇴하면 콤보존 나감 if(pTargetPC->m_pZone->IsComboZone()) { CZone* pZone = gserver->FindZone(ZONE_DRATAN); if (pZone == NULL) return; GAMELOG << init("GET OUT COMBO AREA BY PARTY KICK", pTargetPC) << "AREA INDEX: " << pTargetPC->m_pArea->m_index << "COMBO INDEX: " << pTargetPC->m_pArea->m_monsterCombo->m_nIndex << end; int extra = 0; GoZoneForce(pTargetPC, pZone->m_index, pZone->m_zonePos[extra][0], // ylayer GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); // z bEndMonsterCombo = true; } #ifdef EXTREME_CUBE // 큐브존에 있는 PC 파티 탈퇴하면 큐브존 나감 if(pTargetPC->m_pZone) { if(pTargetPC->m_pZone->IsExtremeCube()) { CCubeMemList* memlist; memlist = gserver->m_extremeCube.FindMemList(pParty); if(memlist) { CZone* pZone = gserver->FindZone(ZONE_MERAC); if (pZone == NULL) return; int extra = 0; GoZoneForce(pTargetPC, pZone->m_index, pZone->m_zonePos[extra][0], // ylayer GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, // x GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); // z GAMELOG << init("GET OUT CUBE BY PARTY KICK", pTargetPC) << pTargetPC->m_pZone->m_index << end; // memlist->DelPC(pTargetPC); } } } else { GAMELOG << init("GET OUT CUBE BY PARTY KICK", pTargetPC) << "ZONE (NULL)" << end; } #endif // EXTREME_CUBE // 인존에 있는 PC 파티 탈퇴하면 인존을 나감(멤버) if(pTargetPC->m_pZone !=NULL && (pTargetPC->m_pZone->IsExpedRaidZone() || pTargetPC->m_pZone->IsPartyRaidZone()) && pTargetPC->m_nJoinInzone_ZoneNo >=0 && pTargetPC->m_nJoinInzone_RoomNo >= 0) { CNetMsg::SP rmsg(new CNetMsg); RaidInzoneQuitReq(rmsg,1,0); do_Raid(pTargetPC, rmsg); } pTargetPC->CancelDamageLink(); pTargetPC->m_party = NULL; } pParty->SetMemberPCPtr(nTargetIndex, NULL); pParty->DeleteMember(nTargetIndex); if (nErrorCode == MSG_HELPER_PARTY_ERROR_KICK_END) { { // 파티 해체 알림 CNetMsg::SP rmsg(new CNetMsg); PartyMsg(rmsg, MSG_PARTY_END); if (pTargetPC) SEND_Q(rmsg, pTargetPC->m_desc); CPC* pBossPC = PCManager::instance()->getPlayerByCharIndex(nBossIndex); if(pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } if(pParty->m_comboAreaIndex != -1 && bEndMonsterCombo) { int i; CArea* area; i = gserver->m_comboZone->FindComboArea(pParty->m_comboAreaIndex); if(i != -1) { area = gserver->m_comboZone->m_area + i; GAMELOG << init("CLOSE COMBO AREA") << "BY Party End" << "AREA INDEX: " << area->m_index << "COMBO INDEX: " << area->m_monsterCombo->m_nIndex << end; area->CloseComboZone(); } } #ifdef EXTREME_CUBE if(pParty->m_cubeUniqueIdx != -1) { CCubeMemList* memlist = gserver->m_extremeCube.FindMemList(pParty); if(memlist && memlist->IsPartyCubeMemList()) { memlist->GetOutAll(); ((CPartyCubeMemList*)memlist)->SetParty(NULL); } } #endif // EXTREME_CUBE // 파티 지우기 gserver->m_listParty.erase(pParty->GetBossIndex()); pParty->SetEndParty(); delete pParty; } else { { // 파티원 나감 CNetMsg::SP rmsg(new CNetMsg); PartyDelMsg(rmsg, false, nTargetIndex); if (pTargetPC) SEND_Q(rmsg, pTargetPC->m_desc); pParty->SendToAllPC(rmsg, nTargetIndex); } // 파티매칭에도 현재 인원을 업데이트 해줍니다. CPartyMatchParty * pPartyMatch = gserver->FindPartyMatchPartyByBossIndex( pParty->GetBossIndex() ); if( pPartyMatch ) { pPartyMatch->SetMemberCount( pParty->GetMemberCount() ); } } } void ProcHelperPartyChangeBossRep(CNetMsg::SP& msg) { int nBossIndex; CLCString strBossName(MAX_CHAR_NAME_LENGTH + 1); int nNewBossIndex; CLCString strNewBossName(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> nBossIndex >> strBossName >> nNewBossIndex >> strNewBossName; GAMELOG << init("PARTY DEBUG HELPER CHANGE BOSS REP") << "nBossIndex" << delim << nBossIndex << delim << "strBossName" << delim << strBossName << delim << "nNewBossIndex" << delim << nNewBossIndex << delim << "strNewBossName" << delim << strNewBossName << end; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (!pParty) { GAMELOG << init("PARTY DEBUG HELPER CHANGE BOSS REP : NOT FOUND PARTY") << end; return ; } if(!pParty->ChangeBoss(strNewBossName)) { GAMELOG << init("PARTY DEBUG HELPER CHANGE BOSS REP : FAILED") << "nBossIndex" << delim << nBossIndex << delim << "strBossName" << delim << strBossName << delim << "nNewBossIndex" << delim << nNewBossIndex << delim << "strNewBossName" << delim << strNewBossName << end; { CNetMsg::SP rmsg(new CNetMsg); HelperPartyBreakReqMsg(rmsg, nNewBossIndex); SEND_Q(rmsg, gserver->m_helper); } #ifdef EXTREME_CUBE if(pParty->m_cubeUniqueIdx != -1) { CCubeMemList* memlist = gserver->m_extremeCube.FindMemList(pParty); if(memlist && memlist->IsPartyCubeMemList()) { memlist->GetOutAll(); ((CPartyCubeMemList*)memlist)->SetParty(NULL); } } #endif // EXTREME_CUBE gserver->m_listParty.erase(pParty->GetBossIndex()); pParty->SetEndParty(); delete pParty; return ; } { CNetMsg::SP rmsg(new CNetMsg); PartyChangeBoss(rmsg, strBossName, nNewBossIndex, strNewBossName, true); pParty->SendToAllPC(rmsg); } CPartyMatchParty* pMatchParty = gserver->FindPartyMatchPartyByBossIndex(nBossIndex); if (pMatchParty) { pMatchParty->SetBossIndex(nNewBossIndex); pMatchParty->SetBossName(strNewBossName); gserver->m_listPartyMatchParty.erase(nBossIndex); gserver->m_listPartyMatchParty.insert(map_listPartyMatchParty_t::value_type(nNewBossIndex, pMatchParty)); CPC* pBossPC = PCManager::instance()->getPlayerByCharIndex(nNewBossIndex); if (pBossPC && pBossPC->m_pZone) { CNetMsg::SP rmsg(new CNetMsg); HelperPartyMatchMemberChangeInfoMsg(rmsg, nNewBossIndex, MSG_HELPER_PARTY_MATCH_MEMBER_CHANGE_INFO_ZONE, "", pBossPC->m_level, pBossPC->m_pZone->m_index); SEND_Q(rmsg, gserver->m_helper); } } CPC* pc = PCManager::instance()->getPlayerByCharIndex(nBossIndex); if(pc) pc->m_listSaveComboData.clear(); } void ProcHelperPartyChangeTypeRep(CNetMsg::SP& msg) { int nBossIndex; char cPartyType; char cDiviType, cAllOneSet; RefMsg(msg) >> nBossIndex >> cPartyType >> cDiviType >> cAllOneSet; GAMELOG << init("PARTY DEBUG HELPER CHANGE TYPE REP") << "nBossIndex" << delim << nBossIndex << delim << "PartyType" << delim << cPartyType << "cDiviType" << delim << cDiviType << "cAllOneSet" << delim << cAllOneSet << end; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (!pParty) { GAMELOG << init("PARTY DEBUG HELPER CHANGE TYPE REP : NOT FOUND PARTY") << end; return ; } if(cAllOneSet==MSG_PARTY_SETALLONE_ALL) //대표 타입 설정 { pParty->SetPartyTypeAll(cPartyType); }else if(cAllOneSet==MSG_PARTY_SETALLONE_ONE) //세분화 1개 설정 { pParty->SetPartyType(cDiviType,cPartyType); } { CNetMsg::SP rmsg(new CNetMsg); PartyChangeType(rmsg, cPartyType, cDiviType, cAllOneSet); pParty->SendToAllPC(rmsg); } } //파티 해체 void ProcHelperPartyEndPartyRep(CNetMsg::SP& msg) { int nBossIndex; RefMsg(msg) >> nBossIndex; CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (!pParty) return ; #ifdef EXTREME_CUBE if(pParty->m_cubeUniqueIdx != -1) { CCubeMemList* memlist = gserver->m_extremeCube.FindMemList(pParty); if(memlist && memlist->IsPartyCubeMemList()) { memlist->GetOutAll(); ((CPartyCubeMemList*)memlist)->SetParty(NULL); } } #endif // EXTREME_CUBE // 파티 해체(리스트 삭제) gserver->m_listParty.erase(pParty->GetBossIndex()); pParty->SetEndParty(); delete pParty; } void ProcHelperPartyMatchRegMemberRep(CNetMsg::SP& msg) { int nErrorCode; int nCharIndex; CLCString strCharName(MAX_CHAR_NAME_LENGTH + 1); int nCharLevel; int nZone; char nCharJob; char nPartyType; CPC* pPC; RefMsg(msg) >> nErrorCode >> nCharIndex >> strCharName >> nCharLevel >> nZone >> nCharJob >> nPartyType; GAMELOG << init("PARTY DEBUG HELPER MATCH REG MEMBER REP") << "nErrorCode" << delim << nErrorCode << delim << "nCharIndex" << delim << nCharIndex << delim << "strCharName" << delim << strCharName << delim << "nCharLevel" << delim << nCharLevel << delim << "nZone" << delim << nZone << delim << "nCharJob" << delim << nCharJob << delim << "nPartyType" << delim << nPartyType << end; pPC = PCManager::instance()->getPlayerByCharIndex(nCharIndex); switch (nErrorCode) { case MSG_HELPER_PARTY_MATCH_ERROR_REG_MEMBER_OK: break; case MSG_HELPER_PARTY_MATCH_ERROR_REG_MEMBER_ALREADY_PARTY: if (pPC) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchRegMemberRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_REG_MEMBER_ALREADY_PARTY); SEND_Q(rmsg, pPC->m_desc); #ifdef _DEBUG { CLCString chat(1000); chat = "REG MEMBER REPLY: ALREADY PARTY"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pPC->m_desc); } #endif // _DEBUG } return ; case MSG_HELPER_PARTY_MATCH_ERROR_REG_MEMBER_ALREADY_REG: if (pPC) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchRegMemberRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_REG_MEMBER_ALREADY_REG); SEND_Q(rmsg, pPC->m_desc); #ifdef _DEBUG { CLCString chat(1000); chat = "REG MEMBER REPLY: ALREADY REGIST"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pPC->m_desc); } #endif // _DEBUG } return ; default: return ; } CPartyMatchMember* pMatchMember = new CPartyMatchMember(nCharIndex, strCharName, nCharLevel, nZone, nCharJob, nPartyType); gserver->m_listPartyMatchMember.insert(map_listPartyMatchMember_t::value_type(pMatchMember->GetIndex(), pMatchMember)); if (pPC) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchRegMemberRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_REG_MEMBER_OK); SEND_Q(rmsg, pPC->m_desc); #ifdef _DEBUG { CLCString chat(1000); chat = "REG MEMBER REPLY: OK"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pPC->m_desc); } #endif // _DEBUG } } void ProcHelperPartyMatchRegPartyRep(CNetMsg::SP& msg) { int nErrorCode; int nBossIndex; CLCString strBossName(MAX_CHAR_NAME_LENGTH + 1); int nBossLevel; int nZone; int nJobFlag; char cLimitLevel; char cPartyType; int nMemberCount; CLCString strComment(PARTY_MATCHING_COMMENT + 1); RefMsg(msg) >> nErrorCode >> nBossIndex >> strBossName >> nBossLevel >> nZone >> nMemberCount >> nJobFlag >> cLimitLevel >> cPartyType >> strComment; GAMELOG << init("PARTY DEBUG HELPER MATCH REG PARTY REP") << "nErrorCode" << delim << nErrorCode << delim << "nBossIndex" << delim << nBossIndex << delim << "strBossName" << delim << strBossName << delim << "nBossLevel" << delim << nBossLevel << delim << "nZone" << delim << nZone << delim << "nJobFlag" << delim << nJobFlag << delim << "cLimitLevel" << delim << cLimitLevel << delim << "cPartyType" << delim << cPartyType << end; CPC* pBossPC = PCManager::instance()->getPlayerByCharIndex(nBossIndex); switch (nErrorCode) { case MSG_HELPER_PARTY_MATCH_ERROR_REG_PARTY_OK: break; case MSG_HELPER_PARTY_MATCH_ERROR_REG_PARTY_NO_BOSS: if (pBossPC) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchRegPartyRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_REG_PARTY_NO_BOSS); SEND_Q(rmsg, pBossPC->m_desc); #ifdef _DEBUG { CLCString chat(1000); chat = "REG PARTY REPLY: NO BOSS"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } return ; case MSG_HELPER_PARTY_MATCH_ERROR_REG_PARTY_ALREADY_REG: if (pBossPC) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchRegPartyRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_REG_PARTY_ALREADY_REG); SEND_Q(rmsg, pBossPC->m_desc); #ifdef _DEBUG { CLCString chat(1000); chat = "REG PARTY REPLY: ALREADY REGIST"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } return ; case MSG_HELPER_PARTY_MATCH_ERROR_REG_PARTY_FULL: if (pBossPC) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchRegPartyRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_REG_PARTY_FULL); SEND_Q(rmsg, pBossPC->m_desc); #ifdef _DEBUG { CLCString chat(1000); chat = "REG PARTY REPLY: FULL PARTY"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } return ; default: return ; } CPartyMatchParty* pMatchParty = new CPartyMatchParty(nBossIndex, strBossName, nBossLevel, nZone, nJobFlag, cPartyType, (cLimitLevel) ? true : false, strComment); pMatchParty->SetMemberCount(nMemberCount); gserver->m_listPartyMatchParty.insert(map_listPartyMatchParty_t::value_type(pMatchParty->GetBossIndex(), pMatchParty)); if (pBossPC) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchRegPartyRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_REG_PARTY_OK); SEND_Q(rmsg, pBossPC->m_desc); #ifdef _DEBUG { CLCString chat(1000); chat = "REG PARTY REPLY: OK"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } } void ProcHelperPartyMatchDelRep(CNetMsg::SP& msg) { int nCharIndex; int nErrorCode; RefMsg(msg) >> nCharIndex >> nErrorCode; GAMELOG << init("PARTY DEBUG HELPER MATCH DEL REP") << "nCharIndex" << delim << nCharIndex << delim << "nErrorCode" << delim << nErrorCode << end; CPartyMatchMember* pMatchMember = NULL; CPartyMatchParty* pMatchParty = NULL; CPC* pPC = PCManager::instance()->getPlayerByCharIndex(nCharIndex); switch (nErrorCode) { case MSG_HELPER_PARTY_MATCH_ERROR_DEL_MEMBER: pMatchMember = gserver->FindPartyMatchMemberByCharIndex(nCharIndex); if (pMatchMember) { gserver->m_listPartyMatchMember.erase(pMatchMember->GetIndex()); delete pMatchMember; if (pPC) { if (!pPC->m_party) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchDelRepMsg(rmsg); SEND_Q(rmsg, pPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "DEL REPLY: DEL MEMBER"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pPC->m_desc); } #endif // _DEBUG } } break; case MSG_HELPER_PARTY_MATCH_ERROR_DEL_PARTY: pMatchParty = gserver->FindPartyMatchPartyByBossIndex(nCharIndex); if (pMatchParty) { gserver->m_listPartyMatchParty.erase(pMatchParty->GetBossIndex()); delete pMatchParty; if (pPC) { if (pPC->IsParty() && pPC->m_party->GetMemberCount() < MAX_PARTY_MEMBER) { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchDelRepMsg(rmsg); SEND_Q(rmsg, pPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "DEL REPLY: DEL PARTY"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); SEND_Q(rmsg, pPC->m_desc); } #endif // _DEBUG } } break; } } void ProcHelperPartyMatchInviteRep(CNetMsg::SP& msg) { int nErrorCode; int nBossIndex; CLCString strBossName(MAX_CHAR_NAME_LENGTH + 1); int nCharIndex; CLCString strCharName(MAX_CHAR_NAME_LENGTH + 1); char cPartyType; RefMsg(msg) >> nErrorCode >> nBossIndex >> strBossName >> nCharIndex >> strCharName >> cPartyType; GAMELOG << init("PARTY DEBUG HELPER MATCH INVITE REP") << "nErrorCode" << delim << nErrorCode << delim << "nBossIndex" << delim << nBossIndex << delim << "strBossName" << delim << strBossName << delim << "nCharIndex" << delim << nCharIndex << delim << "strCharName" << delim << strCharName << delim << "cPartyType" << delim << cPartyType << end; CPC* pBossPC = PCManager::instance()->getPlayerByCharIndex(nBossIndex); CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nCharIndex); CParty* pParty = NULL; // 파티 관련 서버 다운되는 현상 방지 if(!pBossPC || !pTargetPC) { GAMELOG << init("PARTY Error : NULL Check 2") << end; //return; } /* // 워프 중이면 취소 if (pBossPC->CanWarp() || pTargetPC->CanWarp()) { GAMELOG << init("PARTY Error : NULL Check 4") << end; return; } */ switch (nErrorCode) { case MSG_HELPER_PARTY_MATCH_ERROR_INVITE_OK: { pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty) { // 기존 파티에 초대 상태로 pParty->SetRequest(nCharIndex, strCharName); if (pTargetPC) pTargetPC->m_party = pParty; } else { // 신규 파티 pParty = new CParty(cPartyType, nBossIndex, strBossName, pBossPC, nCharIndex, strCharName); if (pBossPC) pBossPC->m_party = pParty; if (pTargetPC) pTargetPC->m_party = pParty; gserver->m_listParty.insert(map_listparty_t::value_type(pParty->GetBossIndex(), pParty)); } { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchInviteRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_INVITE_OK, cPartyType, nBossIndex, strBossName, nCharIndex, strCharName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); if (pTargetPC) SEND_Q(rmsg, pTargetPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat.Format("INVITE REP: TYPE: %d, BOSS: %d, TARGET: %d", cPartyType, nBossIndex, nCharIndex); CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); if (pTargetPC) SEND_Q(rmsg, pTargetPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_INVITE_NOT_FOUND: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchInviteRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_INVITE_NOT_FOUND, cPartyType, nBossIndex, strBossName, nCharIndex, strCharName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "INVITE REP: NOT FOUND TARGET"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_INVITE_LEVEL: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchInviteRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_INVITE_LEVEL, cPartyType, nBossIndex, strBossName, nCharIndex, strCharName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "INVITE REP: LEVEL"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_INVITE_NOBOSS: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchInviteRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_INVITE_NOBOSS, cPartyType, nBossIndex, strBossName, nCharIndex, strCharName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "INVITE REP: NO BOSS"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_INVITE_DIFF_TYPE: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchInviteRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_INVITE_DIFF_TYPE, cPartyType, nBossIndex, strBossName, nCharIndex, strCharName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "INVITE REP: DIFF TYPE"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_INVITE_ALREADY_TARGET: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchInviteRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_INVITE_ALREADY_TARGET, cPartyType, nBossIndex, strBossName, nCharIndex, strCharName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "INVITE REP: ALREADY TARGET"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_INVITE_FULL: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchInviteRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_INVITE_FULL, cPartyType, nBossIndex, strBossName, nCharIndex, strCharName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "INVITE REP: FULL"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_INVITE_ALREADY_REQUEST: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchInviteRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_INVITE_ALREADY_REQUEST, cPartyType, nBossIndex, strBossName, nCharIndex, strCharName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "INVITE REP: ALREADY REQUEST"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #endif // _DEBUG } break; } } void ProcHelperPartyMatchJoinRep(CNetMsg::SP& msg) { int nErrorCode; char cPartyType; int nBossIndex; CLCString strBossName(MAX_CHAR_NAME_LENGTH + 1); int nReqCharIndex; CLCString strReqCharName(MAX_CHAR_NAME_LENGTH + 1); char cReqCharJob; RefMsg(msg) >> nErrorCode >> cPartyType >> nBossIndex >> strBossName >> nReqCharIndex >> strReqCharName >> cReqCharJob; CPC* pBossPC = PCManager::instance()->getPlayerByCharIndex(nBossIndex); CPC* pReqPC = PCManager::instance()->getPlayerByCharIndex(nReqCharIndex); CParty* pParty = NULL; ///////////////파티오토매칭 시 전투파티로 파티타입 전환/////////////// if(strReqCharName == "" || cReqCharJob == -1) { if(pReqPC) { strReqCharName = pReqPC->m_nick; cReqCharJob = pReqPC->m_job; } else // 요청 플레이어를 못찾을 경우 (게임에서 나갔을때나...)이름과 직업의 로그를 찍지 못하기에 임시로 string을 넣음. { strReqCharName = "Reference The Charindex(CANT FIND PC)"; cReqCharJob = -1; } } ///////////////파티오토매칭 시 전투파티로 파티타입 전환/////////////// GAMELOG << init("PARTY DEBUG HELPER MATCH JOIN REP") << "nErrorCode" << delim << nErrorCode << delim << "cPartyType" << delim << cPartyType << delim << "nBossIndex" << delim << nBossIndex << delim << "strBossName" << delim << strBossName << delim << "nReqCharIndex" << delim << nReqCharIndex << delim << "strReqCharName" << delim << strReqCharName << delim << "cReqCharJob" << delim << cReqCharJob << end; // 파티 관련 서버 다운되는 현상 방지 if(!pBossPC || !pReqPC) { GAMELOG << init("PARTY Error : NULL Check MATCH JOIN REP 1") << end; //return; } /* // 워프 중이면 취소 if (pBossPC->CanWarp() || pReqPC->CanWarp()) { GAMELOG << init("PARTY Error : NULL Check MATCH JOIN REP 2") << end; return; } */ switch (nErrorCode) { case MSG_HELPER_PARTY_MATCH_ERROR_JOIN_OK: { pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty) { // 기존 파티의 초대 상태로 pParty->SetRequest(nReqCharIndex, strReqCharName); if (pReqPC) pReqPC->m_party = pParty; { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchJoinRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_JOIN_OK, cPartyType, nBossIndex, strBossName, nReqCharIndex, strReqCharName, cReqCharJob); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat.Format("JOIN REPLY: TYPE: %d, BOSS: %d, REQ: %d, JOB: %d", cPartyType, nBossIndex, nReqCharIndex, cReqCharJob); CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #endif // _DEBUG } else { GAMELOG << init("PARTY DEBUG HELPER MATCH JOIN REP : NOT FOUND PARTY") << end; } } break; case MSG_HELPER_PARTY_MATCH_ERROR_JOIN_ALREADY_TARGET: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchJoinRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_JOIN_ALREADY_TARGET, cPartyType, nBossIndex, strBossName, nReqCharIndex, strReqCharName, cReqCharJob); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "JOIN REPLY: ALREADY TARGET"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_JOIN_NOT_FOUND: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchJoinRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_JOIN_NOT_FOUND, cPartyType, nBossIndex, strBossName, nReqCharIndex, strReqCharName, cReqCharJob); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "JOIN REPLY: NOT FOUND"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_JOIN_LEVEL: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchJoinRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_JOIN_LEVEL, cPartyType, nBossIndex, strBossName, nReqCharIndex, strReqCharName, cReqCharJob); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "JOIN REPLY: LEVEL"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_JOIN_LIMIT_LEVEL: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchJoinRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_JOIN_LIMIT_LEVEL, cPartyType, nBossIndex, strBossName, nReqCharIndex, strReqCharName, cReqCharJob); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "JOIN REPLY: LIMIT LEVEL"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_JOIN_JOB: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchJoinRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_JOIN_JOB, cPartyType, nBossIndex, strBossName, nReqCharIndex, strReqCharName, cReqCharJob); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "JOIN REPLY: JOB"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_JOIN_FULL: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchJoinRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_JOIN_FULL, cPartyType, nBossIndex, strBossName, nReqCharIndex, strReqCharName, cReqCharJob); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "JOIN REPLY: FULL"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #endif // _DEBUG } break; case MSG_HELPER_PARTY_MATCH_ERROR_JOIN_ALREADY_REQUEST: { { CNetMsg::SP rmsg(new CNetMsg); ExPartyMatchJoinRepMsg(rmsg, MSG_EX_PARTY_MATCH_ERROR_JOIN_ALREADY_REQUEST, cPartyType, nBossIndex, strBossName, nReqCharIndex, strReqCharName, cReqCharJob); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #ifdef _DEBUG { CLCString chat(1000); chat = "JOIN REPLY: ALREADY REQUEST"; CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", chat); if (pReqPC) SEND_Q(rmsg, pReqPC->m_desc); } #endif // _DEBUG } break; } } void ProcHelperPartyMatchJoinAllowRep(CNetMsg::SP& msg) { int nErrorCode; int nBossIndex; int nTargetIndex; CLCString strTargetName(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> nErrorCode >> nBossIndex >> nTargetIndex >> strTargetName; GAMELOG << init("PARTY DEBUG HELPER MATCH JOIN ALLOW REP") << "nErrorCode" << delim << nErrorCode << delim << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "strTargetName" << delim << strTargetName << end; CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); // 파티 관련 서버 다운되는 현상 방지 if(!pTargetPC) { GAMELOG << init("PARTY Error : NULL Check MATCH JOIN ALLOW REP 1") << end; //return; } /* // 워프 중이면 취소 if (pTargetPC->CanWarp()) { GAMELOG << init("PARTY Error : NULL Check MATCH JOIN ALLOW REP 2") << end; return; } */ CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty == NULL) { GAMELOG << init("PARTY DEBUG HELPER MATCH JOIN ALLOW REP : NOT FOUND PARTY") << end; return ; } int nListIndex = pParty->JoinRequest(strTargetName, pTargetPC); if (nListIndex == -1) { GAMELOG << init("PARTY DEBUG HELPER MATCH JOIN ALLOW REP : NOT FOUND REQUEST") << end; return ; } // 파티매칭에도 현재 인원을 업데이트 해줍니다. CPartyMatchParty * pPartyMatch = gserver->FindPartyMatchPartyByBossIndex( pParty->GetBossIndex() ); if( pPartyMatch ) { pPartyMatch->SetMemberCount( pParty->GetMemberCount() ); } // 파티원들에게 결과 알리기 { CNetMsg::SP addmsg(new CNetMsg); PartyAddMsg(addmsg, nTargetIndex, strTargetName, pTargetPC, ((pParty->GetBossIndex() == nTargetIndex) ? 1 : 0)); for (int i = 0; i < MAX_PARTY_MEMBER; i++) { const CPartyMember* pMember = pParty->GetMemberByListIndex(i); if (pMember && i != nListIndex) { // 타인에게 target을 추가하고 if (pMember->GetMemberPCPtr()) SEND_Q(addmsg, pMember->GetMemberPCPtr()->m_desc) // target에게는 타인을 추가 if (pTargetPC) { CNetMsg::SP rmsg(new CNetMsg); PartyAddMsg(rmsg, pMember->GetCharIndex(), pMember->GetCharName(), pMember->GetMemberPCPtr(), ((pParty->GetBossIndex() == pMember->GetCharIndex()) ? 1 : 0)); SEND_Q(rmsg, pTargetPC->m_desc); } } } } } void ProcHelperPartyMatchJoinRejectRep(CNetMsg::SP& msg) { int nErrorCode; int nJoinCharIndex; int nRejectCharIndex; RefMsg(msg) >> nErrorCode >> nJoinCharIndex >> nRejectCharIndex; GAMELOG << init("PARTY DEBUG HELPER MATCH JOIN REJECT REP") << "nErrorCode" << delim << nErrorCode << delim << "nJoinCharIndex" << delim << nJoinCharIndex << delim << "nRejectCharIndex" << delim << nRejectCharIndex << end; // nJoinCharIndex로 파티 검색 CParty* pParty = gserver->FindPartyByMemberIndex(nJoinCharIndex, true); if (!pParty) { GAMELOG << init("PARTY DEBUG HELPER MATCH JOIN REJECT REP : NOT FOUND PARTY") << end; return ; } // 각각의 CPC 구하기 CPC* pBossPC = pParty->GetMemberByListIndex(0)->GetMemberPCPtr(); CPC* pRequestPC = PCManager::instance()->getPlayerByCharIndex(pParty->GetRequestIndex()); if (nErrorCode == MSG_HELPER_PARTY_MATCH_ERROR_JOIN_REJECT_OK) { { CNetMsg::SP rmsg(new CNetMsg); if (pParty->GetRequestIndex() == nRejectCharIndex) PartyMsg(rmsg, MSG_PARTY_REJECT_DEST); else if (pParty->GetBossIndex() == nRejectCharIndex) PartyMsg(rmsg, MSG_PARTY_REJECT_SRC); else { GAMELOG << init("PARTY DEBUG HELPER MATCH JOIN REJECT REP : NOT FOUND CHAR") << end; return ; } pParty->SetMemberPCPtr(pParty->GetRequestIndex(), NULL); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); if (pRequestPC) { SEND_Q(rmsg, pRequestPC->m_desc); pRequestPC->m_party = NULL; } } pParty->SetRequest(-1, ""); if (pParty->GetMemberCount() < 2) { // 파티 종료 #ifdef EXTREME_CUBE if(pParty->m_cubeUniqueIdx != -1) { CCubeMemList* memlist = gserver->m_extremeCube.FindMemList(pParty); if(memlist && memlist->IsPartyCubeMemList()) { memlist->GetOutAll(); ((CPartyCubeMemList*)memlist)->SetParty(NULL); } } #endif // EXTREME_CUBE // 파티 지우기 gserver->m_listParty.erase(pParty->GetBossIndex()); pParty->SetEndParty(); delete pParty; } } } void ProcHelperPartyMatchMemberChangeInfo(CNetMsg::SP& msg) { int nCharIndex; int nType; CLCString strCharName(MAX_CHAR_NAME_LENGTH + 1); int nLevel; int nZone; RefMsg(msg) >> nCharIndex >> nType; CPartyMatchMember* pMatchMember = gserver->FindPartyMatchMemberByCharIndex(nCharIndex); CPartyMatchParty* pMatchParty = gserver->FindPartyMatchPartyByBossIndex(nCharIndex); switch (nType) { case MSG_HELPER_PARTY_MATCH_MEMBER_CHANGE_INFO_NAME: RefMsg(msg) >> strCharName; if (pMatchMember) pMatchMember->SetName(strCharName); if (pMatchParty) pMatchParty->SetBossName(strCharName); break; case MSG_HELPER_PARTY_MATCH_MEMBER_CHANGE_INFO_LEVEL: RefMsg(msg) >> nLevel; if (pMatchMember) pMatchMember->SetLevel(nLevel); if (pMatchParty) pMatchParty->SetBossLevel(nLevel); break; case MSG_HELPER_PARTY_MATCH_MEMBER_CHANGE_INFO_ZONE: RefMsg(msg) >> nLevel >> nZone; if (pMatchMember) { pMatchMember->SetLevel(nLevel); pMatchMember->SetZone(nZone); } if (pMatchParty) { pMatchParty->SetBossLevel(nLevel); pMatchParty->SetZone(nZone); } break; } } void ProcHelperPartyInfoEnd(CNetMsg::SP& msg) { // 헬퍼로부터 파티, 파티 매칭 정보를 모두 읽어 들이면 서버는 클라이언트 처리를 시작한다. gserver->m_bLoadPartyInfo = true; } void ProcHelperPartyInfoParty(CNetMsg::SP& msg) { char cPartyType; int nRequestIndex; CLCString strRequestName(MAX_CHAR_NAME_LENGTH + 1); int nMemberCount; int nBossIndex; int nCharIndex; CLCString strCharName(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> cPartyType >> nRequestIndex >> strRequestName >> nMemberCount >> nBossIndex >> strCharName; CParty* pParty = new CParty(cPartyType, nBossIndex, strCharName, NULL, nRequestIndex, strRequestName); LOG_INFO("PARTY CALL ProcHelperPartyInfoParty. boss_index[%d], boss_name[%s]", nBossIndex, (const char*)strCharName); int i; for (i = 1; i < nMemberCount; i++) { RefMsg(msg) >> nCharIndex >> strCharName; pParty->m_listMember[i] = new CPartyMember(nCharIndex, strCharName, NULL); pParty->m_nCount++; } gserver->m_listParty.insert(map_listparty_t::value_type(pParty->GetBossIndex(), pParty)); // 초대 중인 것이 있었으면 자동으로 거절 처리하도록 함 if (nRequestIndex > 0) { CNetMsg::SP rmsg(new CNetMsg); HelperPartyRejectReqMsg(rmsg, nBossIndex, nRequestIndex); SEND_Q(rmsg, gserver->m_helper); } } void ProchelperPartyInfoPartyMatchMember(CNetMsg::SP& msg) { int nCharIndex; CLCString strCharName(MAX_CHAR_NAME_LENGTH + 1); int nLevel; int nZone; char cJob; char cPartyType; RefMsg(msg) >> nCharIndex >> strCharName >> nLevel >> nZone >> cJob >> cPartyType; CPartyMatchMember* pMatchMember = new CPartyMatchMember(nCharIndex, strCharName, nLevel, nZone, cJob, cPartyType); gserver->m_listPartyMatchMember.insert(map_listPartyMatchMember_t::value_type(pMatchMember->GetIndex(), pMatchMember)); } void ProchelperPartyInfoPartyMatchParty(CNetMsg::SP& msg) { int nBossIndex; CLCString strBossName(MAX_CHAR_NAME_LENGTH + 1); int nBossLevel; int nZone; int nJobFlag; char cPartyType; char cLimitLevel; CLCString strComment(PARTY_MATCHING_COMMENT + 1); RefMsg(msg) >> nBossIndex >> strBossName >> nBossLevel >> nZone >> nJobFlag >> cPartyType >> cLimitLevel >> strComment; CPartyMatchParty* pMatchParty = new CPartyMatchParty(nBossIndex, strBossName, nBossLevel, nZone, nJobFlag, cPartyType, (cLimitLevel) ? true : false, strComment); gserver->m_listPartyMatchParty.insert(map_listPartyMatchParty_t::value_type(pMatchParty->GetBossIndex(), pMatchParty)); } void ProcHelperGuildInclineEstablish( CNetMsg::SP& msg ) { int guildindex; int charindex; char guildincline; int errorcode; RefMsg(msg) >> guildindex >> charindex >> guildincline >> errorcode; LONGLONG needMoney; int needGP; RefMsg(msg) >> needMoney >> needGP; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc || !guild ) { return; } if( guild ) { if( errorcode == MSG_NEW_GUILD_ERROR_INCLINE_OK ) { guild->incline( guildincline ); guild->AddGuildPoint( -needGP ); if (pc->m_inventory.getMoney() >= needMoney) { pc->m_inventory.decreaseMoney(needMoney); } pc->CalcStatus(true); { CNetMsg::SP rmsg(new CNetMsg); GuildInclineEstablishMsg( rmsg, guildincline ); guild->SendToAll( rmsg ); } } } } void ProcHelperGuildMemberAdjust( CNetMsg::SP& msg ) { int guildindex; int ownerindexindex; int charindex; CLCString strPositionName(GUILD_POSITION_NAME+1); int contribute_exp, contribute_fame; int contributeExp_min, contributeExp_max; int contributeFame_min, contributeFame_max; int errorcode; int pos; RefMsg(msg) >> guildindex >> ownerindexindex >> charindex >> strPositionName >> contribute_exp >> contribute_fame >> contributeExp_min >> contributeExp_max >> contributeFame_min >> contributeFame_max >> errorcode; RefMsg(msg) >> pos; CPC* guildOwner = PCManager::instance()->getPlayerByCharIndex( ownerindexindex ); CGuildMember* guildMember = gserver->m_guildlist.findmember( charindex); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !guild ) return; if( errorcode == MSG_NEW_GUILD_ERROR_ADJUST_OK && guildMember ) { guildMember->positionName( strPositionName ); guildMember->contributeExp(contribute_exp); guildMember->contributeFame(contribute_fame); guildMember->SetContributeExp_min(contributeExp_min); guildMember->SetContributeExp_max(contributeExp_max); guildMember->SetContributeFame_min(contributeFame_min); guildMember->SetContributeFame_max(contributeFame_max); guild->ChangeGradeExPosCount(guildMember->pos(), pos); guildMember->pos(pos); int needGP = guild->GetGradeExPosNeedGuilPoint( pos ) ; if( needGP >= guild->GetGuildPoint() ) guild->guildPoint( 0 ); else if( needGP > 0) guild->guildPoint(guild->GetGuildPoint() - needGP ); } if( guildOwner ) { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, (MSG_GUILD_ERROR_TYPE )errorcode, guild ); SEND_Q( rmsg, guildOwner->m_desc ); } } void ProcHelperGuildInfoNotice( CNetMsg::SP& msg ) { int charindex; int guildindex; int avelevel; int usepoint; int errorcode; RefMsg(msg) >> charindex >> guildindex >> avelevel >> usepoint >> errorcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc || !guild ) return; if( errorcode == MSG_NEW_GUILD_INFO_ERROR_OK ) { if( guild ) { CNetMsg::SP rmsg(new CNetMsg); GuildNewInfo( rmsg, pc, avelevel, guild->GetGuildPoint(), usepoint ); SEND_Q( rmsg, pc->m_desc ); } } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, (MSG_GUILD_ERROR_TYPE )errorcode ); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperNewGuildMemberListRep( CNetMsg::SP& msg ) { int charindex; int guildindex; int errorcode; int membercount; int membercharindex[GUILD_MAX_MEMBER]; int cumulatePoint[GUILD_MAX_MEMBER]; char CharName[GUILD_MAX_MEMBER][MAX_CHAR_NAME_LENGTH + 1]; char PositionName[GUILD_MAX_MEMBER][GUILD_POSITION_NAME+1]; CLCString strCharName( MAX_CHAR_NAME_LENGTH + 1 ); CLCString strPositionName( GUILD_POSITION_NAME +1); char job[GUILD_MAX_MEMBER]; char job2[GUILD_MAX_MEMBER]; int level[GUILD_MAX_MEMBER]; int position[GUILD_MAX_MEMBER]; int logout_date[GUILD_MAX_MEMBER]; RefMsg(msg) >> charindex >> guildindex >> errorcode >> membercount; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc || !guild ) return; if( errorcode == MSG_NEW_GUILD_MEMBERLIST_ERROR_OK ) { for( int i = 0; i < membercount; i++ ) { RefMsg(msg) >> membercharindex[i] >> cumulatePoint[i] >> strCharName >> strPositionName >> job[i] >> job2[i] >> level[i] >> position[i] >> logout_date[i]; strcpy( CharName[i], strCharName ); strcpy( PositionName[i], strPositionName ); guild->AddGradeExPosCount(position[i]); } { CNetMsg::SP rmsg(new CNetMsg); GuildMemberListRep( rmsg, membercount, membercharindex, cumulatePoint, CharName, PositionName, job, job2, level, position, guild, logout_date ); SEND_Q( rmsg, pc->m_desc ); } } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, (MSG_GUILD_ERROR_TYPE )errorcode ); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperNewGuilManageRep( CNetMsg::SP& msg ) { int charindex; int guildindex; int errorcode; int membercount; int membercharindex[GUILD_MAX_MEMBER]; int contributeExp_min[GUILD_MAX_MEMBER]; int contributeExp_max[GUILD_MAX_MEMBER]; int contributeFame_min[GUILD_MAX_MEMBER]; int contributeFame_max[GUILD_MAX_MEMBER]; int contributeExp[GUILD_MAX_MEMBER]; int contributeFame[GUILD_MAX_MEMBER]; int level[GUILD_MAX_MEMBER]; char charName[GUILD_MAX_MEMBER][MAX_CHAR_NAME_LENGTH + 1]; char positionName[GUILD_MAX_MEMBER][GUILD_POSITION_NAME+1]; CLCString strCharName( MAX_CHAR_NAME_LENGTH + 1 ); CLCString strPositionName( GUILD_POSITION_NAME+1 ); int position[GUILD_MAX_MEMBER]; #ifdef DEV_GUILD_STASH char cStashAuth[GUILD_MAX_MEMBER] = {0,}; #endif //DEV_GUILD_STASH char first; RefMsg(msg) >> first >> charindex >> guildindex >> errorcode >> membercount; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc || !guild ) return; if( errorcode == MSG_NEW_GUILD_MANAGE_ERROR_OK ) { for( int i = 0; i < membercount; i++ ) { RefMsg(msg) >> membercharindex[i] >> contributeExp_min[i] >> contributeExp_max[i] >> contributeFame_min[i] >> contributeFame_max[i] >> contributeExp[i] >> contributeFame[i] >> strCharName >> strPositionName >> level[i] >> position[i]; RefMsg(msg) >> cStashAuth[i]; strcpy( charName[i], strCharName ); strcpy( positionName[i], strPositionName ); guild->AddGradeExPosCount(position[i]); } { CNetMsg::SP rmsg(new CNetMsg); GuildNewManageRep( rmsg, membercount, membercharindex, contributeExp, contributeFame, contributeExp_min, contributeExp_max, contributeFame_min, contributeFame_max, charName, positionName, level, position, cStashAuth, guild, first ); SEND_Q( rmsg, pc->m_desc ); } } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, (MSG_GUILD_ERROR_TYPE )errorcode ); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperNewGuildNotifyRep( CNetMsg::SP& msg ) { int charindex; int guildindex; CLCString title( GUILD_NOTICE_TITLE_MAX + 1 ); CLCString text( GUILD_NOTICE_TEXT_MAX + 1 ); RefMsg(msg) >> charindex >> guildindex >> title >> text; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc || !guild ) return; { CNetMsg::SP rmsg(new CNetMsg); GuildNewNotify( rmsg, title, text ); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperNewGuildNotifyUpdateReP( CNetMsg::SP& msg ) { int charindex; int guildindex; int errorcode; RefMsg(msg) >> charindex >> guildindex >> errorcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc || !guild ) return; { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, (MSG_GUILD_ERROR_TYPE )errorcode ); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperNewGuildNotifyTrans( CNetMsg::SP& msg ) { int guildindex; CLCString title( GUILD_NOTICE_TITLE_MAX + 1 ); CLCString text( GUILD_NOTICE_TEXT_MAX + 1 ); RefMsg(msg) >> guildindex >> title >> text; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; { CNetMsg::SP rmsg(new CNetMsg); GuildNewNotifyTrans(rmsg, guild->name(), title, text); guild->SendToAll(rmsg); } } void ProcHelperNewGuildNotifyTransRepMsg( CNetMsg::SP& msg ) { int guildindex; int charindex; int error; RefMsg(msg) >> guildindex >> charindex >> error; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc || !guild ) return; { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, (MSG_GUILD_ERROR_TYPE )error ); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperNewGuildSkillListRepMsg( CNetMsg::SP& msg ) { int i = 0; int charindex = 0; int guildindex = 0; int error; int checkflag = 0; int active_skillcount = 0; int passive_skillcount = 0; int etc_skillcount = 0; boost::scoped_array< int > active_skill_index; boost::scoped_array< int > passive_skill_index; boost::scoped_array< int > etc_skill_index; boost::scoped_array< int > active_skill_level; boost::scoped_array< int > passive_skill_level; boost::scoped_array< int > etc_skill_level; boost::scoped_array< int > active_skill_cooltime; bool endloop = true; RefMsg(msg) >> charindex >> guildindex >> error; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc || !guild ) return; if(error == MSG_NEW_GUILD_SKILL_ERROR_NOTEXIST) { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, MSG_NEW_GUILD_SKILL_ERROR_NOTEXIST ); SEND_Q( rmsg, pc->m_desc ); return ; } while (endloop) { RefMsg(msg) >> checkflag; switch(checkflag) { case GUILD_ACTIVE_SKILL_START: { RefMsg(msg) >> active_skillcount; active_skill_index.reset(new int[active_skillcount]); active_skill_level.reset(new int[active_skillcount]); active_skill_cooltime.reset(new int[active_skillcount]); for(i = 0; i < active_skillcount; i++) { RefMsg(msg) >> active_skill_index[i] >> active_skill_level[i]; } if( error == MSG_NEW_GUILD_SKILL_ERROR_OK ) { for(i = 0; i < active_skillcount; i++) { CSkill* skill = guild->m_activeSkillList.Find(active_skill_index[i]); if(!skill) { GAMELOG << init("NEW_GUILD_SKILL_LIST", pc) << "guild " << delim << guildindex << delim << "error " << delim << error << delim << "skill count " << delim << active_skillcount << delim << " skill index " << delim << active_skill_index[i] << end; return; } if(skill->m_proto->m_index == active_skill_index[i]) { if(active_skill_level[i] != skill->m_level) active_skill_level[i] = skill->m_level; std::map<int, int>::iterator it = skill->m_gskill_usetime.find(pc->m_index); if(it != skill->m_gskill_usetime.end()) { active_skill_cooltime[i] = int(gserver->m_nowseconds) - ((gserver->m_pulse - it->second) / 10); } else { active_skill_cooltime[i] = 0; } } } } } break; case GUILD_PASSIVE_SKILL_START: { RefMsg(msg) >> passive_skillcount; passive_skill_index.reset(new int[passive_skillcount]); passive_skill_level.reset(new int[passive_skillcount]); for(i = 0; i < passive_skillcount; i++) { RefMsg(msg) >> passive_skill_index[i] >> passive_skill_level[i]; } if( error == MSG_NEW_GUILD_SKILL_ERROR_OK ) { for(i = 0; i < passive_skillcount; i++) { CSkill* skill = guild->m_passiveSkillList.Find(passive_skill_index[i]); if(!skill) { GAMELOG << init("NEW_GUILD_SKILL_LIST", pc) << "guild " << delim << guildindex << delim << "error " << delim << error << delim << "skill count " << delim << passive_skillcount << delim << " skill index " << delim << passive_skill_index[i] << end; return; } if(skill->m_proto->m_index == passive_skill_index[i]) { if(passive_skill_level[i] != skill->m_level) passive_skill_level[i] = skill->m_level; } } } } break; case GUILD_ETC_SKILL_START: { RefMsg(msg) >> etc_skillcount; etc_skill_index.reset(new int[etc_skillcount]); etc_skill_level.reset(new int[etc_skillcount]); for(i = 0; i < etc_skillcount; i++) { RefMsg(msg) >> etc_skill_index[i] >> etc_skill_level[i]; } if( error == MSG_NEW_GUILD_SKILL_ERROR_OK ) { for(i = 0; i < etc_skillcount; i++) { CSkill* skill = guild->m_etcSkillList.Find(etc_skill_index[i]); if(!skill) { GAMELOG << init("NEW_GUILD_SKILL_LIST", pc) << "guild " << delim << guildindex << delim << "error " << delim << error << delim << "skill count " << delim << etc_skillcount << delim << " skill index " << delim << etc_skill_index[i] << end; return; } if(skill->m_proto->m_index == etc_skill_index[i]) { if(etc_skill_level[i] != skill->m_level) etc_skill_level[i] = skill->m_level; } } } } break; } if(checkflag == GUILD_ETC_SKILL_START) endloop = false; } // 메세지 전송 시작 if( error == MSG_NEW_GUILD_SKILL_ERROR_OK ) { CNetMsg::SP rmsg(new CNetMsg); GuildSkillListRepMsg(rmsg, active_skillcount, active_skill_index.get(), active_skill_level.get(), active_skill_cooltime.get(), passive_skillcount, passive_skill_index.get(), passive_skill_level.get(), etc_skillcount, etc_skill_index.get(), etc_skill_level.get()); SEND_Q(rmsg, pc->m_desc); } // 메세지 전송 끝 return ; } void ProcHelperNewGuildLoadNTF( CNetMsg::SP& msg ) { int guildindex; int guildpoint; char guildincline; int guildmaxmeber; int landcount; int land[256]; int skillcount; int skillIndex[256]; int skillLevel[256]; memset( land, -1, sizeof( land) ); int skilltype; RefMsg(msg) >> guildindex >> guildpoint >> guildincline >> guildmaxmeber >> landcount; if( landcount != 0 ) { for( int i = 0 ; i < landcount; i++ ) { RefMsg(msg) >> land[i]; } } else RefMsg(msg) >> land[0]; RefMsg(msg) >> skillcount; int i; for( i = 0; i < skillcount; i++ ) { RefMsg(msg) >> skillIndex[i] >> skillLevel[i]; } RefMsg(msg) >> skilltype; CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !guild ) return; guild->guildPoint( guildpoint ); guild->incline( guildincline ); guild->landcount( landcount ); guild->setMaxmember( guildmaxmeber ); guild->land( landcount, land ); if( skillcount > 0 ) { for( i = 0; i < skillcount; i++ ) { CSkill* skill = gserver->m_skillProtoList.Create( skillIndex[i], skillLevel[i] ); if( skill ) { switch(skilltype) { case 0: guild->m_activeSkillList.Add(skill); break; case 1: guild->m_passiveSkillList.Add( skill ); break; case 2: guild->m_etcSkillList.Add(skill); break; default: break; } } } } guild->SendToAllStatusMsg(); } void ProcHelperNewGuildMemberList( CNetMsg::SP& msg ) { int guildindex; int guildmembercount; int charindex; int contributeExp; int contributeFame; int exp_min, exp_max; int fame_min, fame_max; int cumulatePoint; int channel; int zoneNum; CLCString positionName( GUILD_POSITION_NAME + 1 ); RefMsg(msg) >> guildindex >> guildmembercount; CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !guild ) return; int i; for( i = 0; i < guildmembercount; i++ ) { RefMsg(msg) >> charindex >> contributeExp >> contributeFame >> exp_min >> exp_max >> fame_min >> fame_max >> cumulatePoint >> positionName >> channel >> zoneNum; CGuildMember* member = guild->findmember( charindex ); if( !member ) continue; member->contributeExp( contributeExp ); member->contributeFame( contributeFame ); member->SetContributeExp_min(exp_min); member->SetContributeExp_max(exp_max); member->SetContributeFame_min(fame_min); member->SetContributeFame_max(fame_max); member->cumulatePoint( cumulatePoint ); member->positionName( positionName ); member->channel( channel ); member->zoneindex( zoneNum ); } } void ProcHelperNewGuildInfoRepMsg( CNetMsg::SP& msg ) { int charindex; int errorcode; RefMsg(msg) >> charindex >> errorcode; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); if( !pc ) return; { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, (MSG_GUILD_ERROR_TYPE )errorcode ); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperNewGuildPointUpdateMsg( CNetMsg::SP& msg ) { int charindex; int guildindex; int guildpoint; RefMsg(msg) >> charindex >> guildindex >> guildpoint; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); CGuild* guild = gserver->m_guildlist.findguild( guildindex ); if( !pc && !guild ) return; guild->guildPoint( guildpoint ); } void ProcHelperNewGuildNotice( CNetMsg::SP& msg ) { int charindex; int guildindex; CLCString title( GUILD_NOTICE_TITLE_MAX + 1 ); CLCString text( GUILD_NOTICE_TEXT_MAX + 1 ); RefMsg(msg) >> charindex >> guildindex >> title >> text; CPC* pc = PCManager::instance()->getPlayerByCharIndex( charindex ); if( !pc ) return; CGuild* guild = gserver->m_guildlist.findguild(guildindex); if (!guild) return ; if( strlen(title) != 0 && strlen(text) != 0 ) { CNetMsg::SP rmsg(new CNetMsg); GuildNewNotifyTrans(rmsg, guild->name(), title, text); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperNewGuildMemberPointSaveMsg(CNetMsg::SP& msg) { int nCharIdx; int nGuildIdx; int nMemberPoint; RefMsg(msg) >> nGuildIdx >> nCharIdx >> nMemberPoint; CPC* pPC = PCManager::instance()->getPlayerByCharIndex(nCharIdx); CGuildMember* pMember = gserver->m_guildlist.findmember(nCharIdx); if(!pPC || !pMember) return; pMember->cumulatePoint(nMemberPoint); } void ProcHelperNewGuildSkillLearnSendMember(CNetMsg::SP& msg) { int guild_index; int skill_type, skill_index, skill_level; RefMsg(msg) >> guild_index >> skill_type >> skill_index >> skill_level; CGuild* guild = gserver->m_guildlist.findguild(guild_index); if(guild == NULL) return ; { CNetMsg::SP rmsg(new CNetMsg); UpdateClient::makenewGuildSkillLearnToMemberMsg(rmsg, skill_type, skill_index, skill_level); guild->SendToAll(rmsg, false); } } void ProcHelperGuildContributeSet(CNetMsg::SP& msg) { int char_index; int exp, fame; int error_code; RefMsg(msg) >> char_index >> exp >> fame >> error_code; CPC* pc = PCManager::instance()->getPlayerByCharIndex(char_index); if( pc == NULL ) return; if(error_code != 0) { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, MSG_GUILD_ERROR_CONTRIBUTE_SET_FAIL ); SEND_Q( rmsg, pc->m_desc ); return; } pc->m_guildInfo->contributeExp(exp); pc->m_guildInfo->contributeFame(fame); //성공 패킷 전송 { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg( rmsg, MSG_GUILD_ERROR_CONTRIBUTE_SET_SUCCESS ); SEND_Q( rmsg, pc->m_desc ); } } void ProcHelperGuildContributeSetAll(CNetMsg::SP& msg) { int char_index, guild_index; int exp, fame; int exp_min, exp_max; int fame_min, fame_max; int error_code; RefMsg(msg) >> char_index >> guild_index >> exp >> fame >> exp_min >> exp_max >> fame_min >> fame_max >> error_code; CPC* pc = PCManager::instance()->getPlayerByCharIndex(char_index); if(pc == NULL) return; if(error_code != 0) { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_CONTRIBUTE_SET_ALL_FAIL); SEND_Q(rmsg, pc->m_desc); return; } else { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_CONTRIBUTE_SET_ALL_SUCCESS); SEND_Q(rmsg, pc->m_desc); } CGuild* guild = gserver->m_guildlist.findguild(guild_index); if(guild == NULL) return; CPC* ch; for(int i = 0; i < GUILD_MAX_MEMBER; i++) { if(guild->m_member[i] != NULL) { ch = guild->m_member[i]->GetPC(); if(ch != NULL) { ch->m_guildInfo->SetContributeExp_min(exp_min); ch->m_guildInfo->SetContributeExp_max(exp_max); ch->m_guildInfo->SetContributeFame_min(fame_min); ch->m_guildInfo->SetContributeFame_max(fame_max); ch->m_guildInfo->contributeExp(exp); ch->m_guildInfo->contributeFame(fame); } } } guild->m_guild_contribute_all_exp_min = exp_min; guild->m_guild_contribute_all_exp_max = exp_max; guild->m_guild_contribute_all_fame_min = fame_min; guild->m_guild_contribute_all_fame_max = fame_max; } void ProcHelperPetChangeName( CNetMsg::SP& msg ) { int err; int charidx; int petidx; CLCString PetName( MAX_CHAR_NAME_LENGTH + 1 ); CPC* pc = NULL; RefMsg(msg) >> err >> charidx >> petidx >> PetName; pc = PCManager::instance()->getPlayerByCharIndex( charidx ); if( err == MSG_EX_PET_CHANGE_NAME_ERROR_OK ) { if( pc == NULL ) { GAMELOG << init( "CASH_ITEM_USE_ERROR-notPC" ) << charidx << delim << 2360 << end; // Helper로 롤백 처리 PetName = ""; CNetMsg::SP rmsg(new CNetMsg); HelperPetNameChange( rmsg, charidx, petidx, PetName ); SEND_Q( rmsg, gserver->m_helper ); /* PetNameChange( rmsg, (MSG_EX_PET_CHANGE_NAME_ERROR_TYPE)err, petidx, PetName ); SEND_Q( rmsg, pc->m_desc ); */ return; } else { CItem* pItem = pc->m_inventory.FindByDBIndex(2360, 0, 0); if (pItem == NULL) { GAMELOG << init( "CASH_ITEM_USE_ERROR-notPC" ) << charidx << delim << 2360 << end; { // Helper로 롤백 처리 PetName = ""; CNetMsg::SP rmsg(new CNetMsg); HelperPetNameChange( rmsg, charidx, petidx, PetName ); SEND_Q( rmsg, gserver->m_helper ); } { CNetMsg::SP rmsg(new CNetMsg); PetNameChange( rmsg, (MSG_EX_PET_CHANGE_NAME_ERROR_TYPE)err, petidx, PetName ); SEND_Q( rmsg, pc->m_desc ); } return; } CPet* pet = pc->GetPet( petidx ); if( (pItem->m_itemProto->getItemFlag() & ITEM_FLAG_CASH ) ) { GAMELOG << init( "CASH_ITEM_USE", pc ) << itemlog( pItem ) << delim << pet->m_name << delim << end; } { //Pet 이름 변경 pet->m_name = PetName; CNetMsg::SP rmsg(new CNetMsg); PetNameChange( rmsg, (MSG_EX_PET_CHANGE_NAME_ERROR_TYPE)err, petidx, PetName ); SEND_Q( rmsg, pc->m_desc ); pet->m_pArea->SendToCell( rmsg, pet, true ); } { // item 수량 변경 CNetMsg::SP rmsg(new CNetMsg); ResponseClient::ItemUseMsg( rmsg, pItem->tab(), pItem->getInvenIndex(), pItem->m_itemProto->getItemIndex(), 0 ); SEND_Q( rmsg, pc->m_desc ); } pc->m_inventory.decreaseItemCount(pItem, 1); return; } } else { if( pc ) { CNetMsg::SP rmsg(new CNetMsg); PetNameChange( rmsg, (MSG_EX_PET_CHANGE_NAME_ERROR_TYPE)err, petidx, PetName ); SEND_Q( rmsg, pc->m_desc ); return; } } } void ProcHelperHalloween2007( CNetMsg::SP& msg ) { int charIndex; unsigned char error; #ifdef EX_ROGUE #ifdef EX_MAGE int nPriceItem[JOBCOUNT] = { 7544, 7544, 7544, 7544, 7544, 7544, 7544, 7544, 7544 }; #else int nPriceItem[JOBCOUNT] = { 7544, 7544, 7544, 7544, 7544, 7544, 7544, 7544 }; #endif #else int nPriceItem[7] = { 7544, 7544, 7544, 7544, 7544, 7544, 7544 }; #endif // EX_ROGUE // JOB_TITAN 0, JOB_KNIGHT 1, JOB_HEALER 2, JOB_MAGE 3, JOB_ROGUE 4, JOB_SORCERER 5, JOB_NIGHTSHADOW 6 RefMsg(msg) >> charIndex >> error ; CPC* ch = PCManager::instance()->getPlayerByCharIndex(charIndex); if( ch == NULL ) return; // 해당유저 없음 if( error == 0 ) // 아이템 지급 { int nRow, nCol; CItem* pPriceItem = gserver->m_itemProtoList.CreateItem( nPriceItem[ch->m_job] , -1, 0, 0, 10 ); if( !pPriceItem ) { CNetMsg::SP rmsg(new CNetMsg); EventHalloween2007Msg( rmsg, MSG_EVENT_FULL_INVEN ); SEND_Q( rmsg, ch->m_desc ); return; } // 아이템 지급 if (ch->m_inventory.addItem(pPriceItem) == false) { delete pPriceItem; CNetMsg::SP rmsg(new CNetMsg); EventHalloween2007Msg( rmsg, MSG_EVENT_FULL_INVEN ); // FULL INVEN SEND_Q( rmsg, ch->m_desc ); return; } { CNetMsg::SP rmsg(new CNetMsg); EventHalloween2007Msg( rmsg, MSG_EVENT_TAKE_DEVILHEAIR, 0 ); // Sucess SEND_Q( rmsg, ch->m_desc ); } } else // 이미 받은적 있음 { CNetMsg::SP rmsg(new CNetMsg); EventHalloween2007Msg( rmsg, MSG_EVENT_TAKE_DEVILHEAIR, 1 ); SEND_Q( rmsg, ch->m_desc ); } } void ProcHelperDVDRateChange( CNetMsg::SP& msg ) { unsigned char subtype; int nRate; RefMsg(msg) >> subtype >> nRate; #if defined(LC_GAMIGO) GAMELOG << init("DRATAN DYNAMIC DUNGEON") << subtype << delim << nRate << delim; #endif // LC_GAMIGO CDratanCastle * pCastle = CDratanCastle::CreateInstance(); if(pCastle->m_dvd.GetZone() != NULL ) { switch( subtype ) { case MSG_MANAGEMENT_TAX_CHANGE : pCastle->m_dvd.SetFeeRate(nRate); #if defined(LC_GAMIGO) GAMELOG << "TAX CHANGE"; #endif // LC_GAMIGO break; case MSG_MANAGEMENT_HUNTER_TAX_CHANGE: pCastle->m_dvd.SetHuntRate(nRate); #if defined(LC_GAMIGO) GAMELOG << "HUNTER TAX CHANGE"; #endif // LC_GAMIGO break; case MSG_MANAGEMENT_ENV_CHANGE: pCastle->m_dvd.SetEnvRate(nRate); pCastle->m_dvd.SetChangeTime(gserver->m_pulse); pCastle->m_dvd.ChangeSetting(); #if defined(LC_GAMIGO) GAMELOG << "ENV CHANGE"; #endif // LC_GAMIGO break; case MSG_MANAGEMENT_STATE_CHANGE: pCastle->m_dvd.SetMobRate(nRate); pCastle->m_dvd.SetChangeTime(gserver->m_pulse); pCastle->m_dvd.ChangeSetting(); #if defined(LC_GAMIGO) GAMELOG << "STATE CHANGE"; #endif // LC_GAMIGO break; } } #if defined(LC_GAMIGO) GAMELOG << end; #endif // LC_GAMIGO } void ProcHelperDVDNormalChangeNotice (CNetMsg::SP& msg) { CNetMsg::SP rmsg(new CNetMsg); DVDDungeonNormalChangeNoticeMsg(rmsg); PCManager::instance()->sendToAll(rmsg); //드라탄 성주를 찾아보고 있으면 패킷 전달. CDratanCastle * pCastle = CDratanCastle::CreateInstance(); int char_index = pCastle->GetOwnerCharIndex(); CPC* pc = PCManager::instance()->getPlayerByCharIndex(char_index); if(pc != NULL) { CNetMsg::SP rmsg(new CNetMsg); DVDDungeonChangeToOwnerMsg(rmsg); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperComboGotoWaitRoomPrompt( CNetMsg::SP& msg ) { CLCString bossname(256); int bossindex; int nas; RefMsg(msg) >> bossindex >> bossname; CParty* party = gserver->FindPartyByBossIndex(bossindex); if(party) { int i = gserver->m_comboZone->FindComboArea(party->m_comboAreaIndex); if(i == -1) return; CArea* area = gserver->m_comboZone->m_area + i; nas = area->m_monsterCombo->GetTotalNas(); CNetMsg::SP rmsg(new CNetMsg); ResponseClient::makeMCGotoWaitRoomPrompt(rmsg, bossindex, nas); for(i = 0 ; i < MAX_PARTY_MEMBER; ++i) { if( party->GetMemberByListIndex(i) && party->GetMemberByListIndex(i)->GetMemberPCPtr() && party->GetMemberByListIndex(i)->GetCharIndex() != bossindex) { SEND_Q(rmsg, party->GetMemberByListIndex(i)->GetMemberPCPtr()->m_desc); } } } } void ProcHelperComboRecallToWaitRoomPrompt(CNetMsg::SP& msg) { int bossindex; int nas; RefMsg(msg) >> bossindex; CParty* party = gserver->FindPartyByBossIndex(bossindex); if(party) { // 파티가 던전에 있는지 int ret; ret = gserver->m_comboZone->FindComboArea(party->m_comboAreaIndex); if(ret == -1) return ; CArea* area = gserver->m_comboZone->m_area + ret; nas = area->m_monsterCombo->GetTotalNas(); CNetMsg::SP rmsg(new CNetMsg); ResponseClient::makeMCGotoWaitRoomPrompt(rmsg, bossindex, nas); for(int i = 0 ; i < MAX_PARTY_MEMBER; ++i) { if( party->GetMemberByListIndex(i) && party->GetMemberByListIndex(i)->GetMemberPCPtr()) { CPC* pc = party->GetMemberByListIndex(i)->GetMemberPCPtr(); if(pc->m_pZone->m_index != ZONE_COMBO_DUNGEON) { SEND_Q(rmsg, party->GetMemberByListIndex(i)->GetMemberPCPtr()->m_desc); } } } } } void ProcHelperAttackPet( CNetMsg::SP& msg ) { unsigned char type; int charIndex; RefMsg(msg) >> type >> charIndex; CPC* pCh = PCManager::instance()->getPlayerByCharIndex(charIndex); if( !pCh ) return; switch( type ) { case MSG_HELPER_APET_CREATE_OK: { int pet_dbIndex, pet_protoIndex; RefMsg(msg) >> pet_dbIndex >> pet_protoIndex; if(pCh->m_inventory.getEmptyCount() < 1) { // 최소 인벤 1칸 return; } // 펫 생성 CAPet* apet = gserver->m_pApetlist.Create( pCh, pet_dbIndex , pet_protoIndex ); if( !apet ) return; ADD_TO_BILIST(apet,pCh->m_pApetlist,m_pPrevPet,m_pNextPet); // 펫 아이템 지급 CAPetProto* proto = gserver->m_pApetlist.FindProto( pet_protoIndex ); if( proto ) { CItem*petItem = gserver->m_itemProtoList.CreateItem( proto->m_nItemIndex, -1, pet_dbIndex, 0, 1 ); if (pCh->m_inventory.addItem(petItem)) { GAMELOG << init("CREATE APET", pCh) << delim << "APET : " << pet_dbIndex << delim << pet_protoIndex << end; { CNetMsg::SP rmsg(new CNetMsg); HelperAttackPetMsg( rmsg , MSG_HELPER_APET_ACCENPT_REQ, charIndex ); RefMsg(rmsg) << pet_dbIndex; SEND_Q(rmsg, gserver->m_helper ); } } else { delete petItem; // 실패 GAMELOG << init("CREATE APET FAIL", pCh) << delim << "APET : " << pet_dbIndex << delim << pet_protoIndex << end; } } } break; case MSG_HELPER_APET_CREATE_FAILED: { // 아이템 제거 } break; case MSG_HELPER_APET_ACCENPT_OK : { // 펫 마지막 처리 성공 } break; case MSG_HELPER_APET_ACCENPT_FAILED : { // 메모리에서 펫 찾고 삭제 // 헬퍼 에 dbindex 삭제 요청 int pet_dbIndex, item_index ; RefMsg(msg) >> pet_dbIndex >> item_index ; CItem* item = pCh->m_inventory.FindByDBIndex(item_index, pet_dbIndex, 0); if (item) { pCh->m_inventory.decreaseItemCount(item, 1); } { CNetMsg::SP rmsg(new CNetMsg); HelperAttackPetMsg( rmsg , MSG_HELPER_APET_DELETE_REQ, charIndex ); RefMsg(rmsg) << pet_dbIndex << (char) 3; SEND_Q(rmsg, gserver->m_helper); } }break; } } #ifdef EXTREME_CUBE #ifdef EXTREME_CUBE_VER2 void ProcHelperCubeStateRep(CNetMsg::SP& msg) { int charindex; int cubepoint; int selfpoint; char i, count, rank; CPC* ch; CLCString guildname(MAX_GUILD_NAME_LENGTH + 1), guildmaster(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> charindex >> selfpoint >> count; ch = PCManager::instance()->getPlayerByCharIndex(charindex); if(!ch) return ; { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_EXTEND); RefMsg(rmsg) << MSG_EX_EXTREME_CUBE << (char)MSG_EX_EXTREME_CUBE_STATE_REP << selfpoint << count; for(i=0;i<count;i++) { RefMsg(msg) >> rank >> guildname >> guildmaster >> cubepoint; RefMsg(rmsg) << rank << guildname << guildmaster << cubepoint; } RefMsg(msg) >> count; RefMsg(rmsg) << count; for(i=0;i<count;i++) { RefMsg(msg) >> rank >> guildname >> guildmaster >> cubepoint; RefMsg(rmsg) << rank << guildname << guildmaster << cubepoint; } SEND_Q(rmsg, ch->m_desc); } } void ProcHelperCubeStatePersonalRep(CNetMsg::SP& msg) { int charindex; int cubepoint, selfpoint; char i, count, rank; CPC* ch; CLCString guildname(MAX_GUILD_NAME_LENGTH + 1), charname(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> charindex >> selfpoint >>count; ch = PCManager::instance()->getPlayerByCharIndex(charindex); if(!ch) return ; { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_EXTEND); RefMsg(rmsg) << MSG_EX_EXTREME_CUBE << (char)MSG_EX_EXTREME_CUBE_STATE_PERSONAL_REP << selfpoint << count; for(i = 0 ; i < count; ++i) { RefMsg(msg) >> rank >> guildname >> charname >> cubepoint; RefMsg(rmsg) << rank << guildname << charname << cubepoint; } RefMsg(msg) >> count; RefMsg(rmsg) << count; for(i=0;i<count;++i) { RefMsg(msg) >> rank >> guildname >> charname >> cubepoint; RefMsg(rmsg) << rank << guildname << charname << cubepoint; } SEND_Q(rmsg, ch->m_desc); } } void ProcHelperGuildCubeNotice(CNetMsg::SP& msg) { int type; RefMsg(msg) >> type; { CNetMsg::SP rmsg(new CNetMsg); switch(type) { case 0: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_START_NOTICE); break; case 1: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_END_NOTICE); break; case 2: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_START_REMAINTIME); break; case 3: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_END_REMAINTIME); break; default: return ; } PCManager::instance()->sendToAll(rmsg); } } void ProcHelperCubeRewardPersonalRep(CNetMsg::SP& msg) { int charindex, updatetime; char rank; CPC* pc; RefMsg(msg) >> updatetime >> charindex >> rank; pc = PCManager::instance()->getPlayerByCharIndex(charindex); if(!pc) { if (gserver->isRunHelper()) { CNetMsg::SP rmsg(new CNetMsg); HelperCubeRewardPersonalRollBackMsg(rmsg, updatetime, charindex); SEND_Q(rmsg, gserver->m_helper); GAMELOG << init("EXTREME_CUBE_REWARD_PERSONAL_ROLLBACK") << "UPDATE TIME" << delim << updatetime << delim << "CHAR INDEX" << delim << charindex << delim << "RANK" << delim << rank << end; } return ; } static const int rewarditem[][4] = { {6076, 6077, 6078, 6079}, {6076, 6078,}, {6077, 6079,}, }; int itemkind; // int remainWeight, sumWeight; switch(rank) { case 1: itemkind=4; break; case 2: itemkind=2; break; case 3: itemkind=2; break; default: itemkind=0; return ; } /* sumWeight = 0; remainWeight = pc->m_maxWeight * 3 / 2 - pc->m_weight; CItemProto* itemproto; for(i=0; i<itemcount; i++) { itemproto = gserver->m_itemProtoList.FindIndex(rewarditem[rank-1][i]); if(itemproto) sumWeight += itemproto->m_weight; } */ if(/*sumWeight > remainWeight || */ itemkind > pc->m_inventory.getEmptyCount()) { CNetMsg::SP rmsg(new CNetMsg); HelperCubeRewardPersonalRollBackMsg(rmsg, updatetime, charindex); SEND_Q(rmsg, gserver->m_helper); GAMELOG << init("EXTREME_CUBE_REWARD_PERSONAL_ROLLBACK", pc) << "UPDATE TIME" << delim << updatetime << delim << "RANK" << delim << rank << end; return ; } for (int i = 0; i < itemkind; i++) { CItem* item = gserver->m_itemProtoList.CreateItem(rewarditem[rank-1][i], -1, 0, 0, 1); if(item) { if (pc->m_inventory.addItem(item) == false) { delete item; continue; } } } GAMELOG << init("EXTREME_CUBE_REWARD_PERSONAL_OK", pc) << "UPDATE TIME" << delim << updatetime << delim << "RANK" << delim << rank << end; } void ProcHelperExtremeCubeError(CNetMsg::SP& msg) { char errortype; int charindex; RefMsg(msg) >> charindex >> errortype; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if(!pc) return ; { CNetMsg::SP rmsg(new CNetMsg); switch(errortype) { case MSG_HELPER_EXTREME_CUBE_ERROR_REWARD_PERSONAL_CANNOT: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_REWARD_PERSONAL_CANNOT); break; case MSG_HELPER_EXTREME_CUBE_ERROR_REWARD_PERSONAL_ALREADY: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_REWARD_PERSONAL_ALREADY); break; default: return ; } SEND_Q(rmsg, pc->m_desc); } } void ProcHelperCubeRewardGuildPointRep(CNetMsg::SP& msg) { int guildidx, guildpoint; char rank; RefMsg(msg) >> guildidx >> rank >> guildpoint; CGuild* guild = gserver->m_guildlist.findguild(guildidx); if(guild != NULL) { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_EXTEND); RefMsg(rmsg) << MSG_EX_EXTREME_CUBE << (char)MSG_EX_EXTREME_CUBE_REWARD_GUILDPOINT_REP << rank << guildpoint; guild->SendToAll(rmsg); } } #else void ProcHelperCubeStateRep(CNetMsg::SP& msg) { int charindex; int cubepoint; int selfpoint; char i, count, rank; CPC* ch; CLCString guildname(MAX_GUILD_NAME_LENGTH + 1), guildmaster(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> charindex >> selfpoint >> count; ch = PCManager::instance()->getPlayerByCharIndex(charindex); if(!ch) return ; if(count == 0) { // 순위 없음 CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_EXTEND); RefMsg(rmsg) << MSG_EX_EXTREME_CUBE << (char)MSG_EX_EXTREME_CUBE_STATE_REP << selfpoint << (int)0; SEND_Q( rmsg, ch->m_desc ); return ; } if(count > 0) { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_EXTEND); RefMsg(rmsg) << MSG_EX_EXTREME_CUBE << (char)MSG_EX_EXTREME_CUBE_STATE_REP << selfpoint << count; for(i = 0; i < count; ++i) { RefMsg(msg) >> rank >> guildname >> guildmaster >> cubepoint; RefMsg(rmsg) << rank << guildname << guildmaster << cubepoint; } SEND_Q( rmsg, ch->m_desc ); } } void ProcHelperCubeStatePersonalRep(CNetMsg::SP& msg) { int charindex; int cubepoint, selfpoint; char i, count, rank; CPC* ch; CLCString guildname(MAX_GUILD_NAME_LENGTH + 1), charname(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> charindex >> selfpoint >>count; ch = PCManager::instance()->getPlayerByCharIndex(charindex); if(!ch) return ; if(count == 0) { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_EXTEND); RefMsg(rmsg) << MSG_EX_EXTREME_CUBE << (char)MSG_EX_EXTREME_CUBE_STATE_PERSONAL_REP << selfpoint << (int)0; SEND_Q(rmsg, ch->m_desc ); return ; } if(count > 0) { CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_EXTEND); RefMsg(rmsg) << MSG_EX_EXTREME_CUBE << (char)MSG_EX_EXTREME_CUBE_STATE_PERSONAL_REP << selfpoint << count; for(i = 0 ; i < count; ++i) { RefMsg(msg) >> rank >> guildname >> charname >> cubepoint; RefMsg(rmsg) << rank << guildname << charname << cubepoint; } SEND_Q(rmsg, ch->m_desc ); } } void ProcHelperGuildCubeNotice(CNetMsg::SP& msg) { int type; RefMsg(msg) >> type; { CNetMsg::SP rmsg(new CNetMsg); switch(type) { case 0: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_START_NOTICE); break; case 1: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_END_NOTICE); break; case 2: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_START_REMAINTIME); break; case 3: ExtremeCubeErrorMsg(rmsg, MSG_EX_EXTREME_CUBE_ERROR_END_REMAINTIME); break; default: return ; } PCManager::instance()->sendToAll(rmsg); } } #endif // EXTREME_CUBE_VER2 #endif // EXTREME_CUBE void ProcHelperEventPhoenix( CNetMsg::SP& msg ) { unsigned char type; int charindex = 0; RefMsg(msg) >> type >> charindex; CPC* ch = PCManager::instance()->getPlayerByCharIndex(charindex); if( !ch ) { return; } // 케릭터 디비에서 검색했을 때 피닉스 이벤트가 가능하다는 응답이 왔을 경우 if ( (MSG_HELPER_EVENT_PHOENIX_ERROR_TYPE)type == MSG_HELPER_EVENT_PHOENIX_OK ) { CNetMsg::SP rmsg(new CNetMsg); EventPhoenixMsg(rmsg, MSG_EVENT_PHOENIX_OK); SEND_Q(rmsg, ch->m_desc); return; } // 케릭터 디비에서 검색했을 때 레벨이 100을 넘는 것이 없어서 피닉스 이벤트 자격이 안된다는 응답 else if ( (MSG_HELPER_EVENT_PHOENIX_ERROR_TYPE)type == MSG_HELPER_EVENT_PHOENIX_ERROR_REQUIREMENT ) { CNetMsg::SP rmsg(new CNetMsg); EventPhoenixMsg(rmsg, MSG_EVENT_PHOENIX_ERROR_REQUIREMENT); SEND_Q(rmsg, ch->m_desc); return; } } //에러 void ProcHelperExpedErrorRep(CNetMsg::SP& msg) { unsigned char errorType; int nCharIndex = -1; RefMsg(msg) >> errorType >> nCharIndex; CPC* ch = PCManager::instance()->getPlayerByCharIndex(nCharIndex); if(ch == NULL) return; { CNetMsg::SP rmsg(new CNetMsg); ExpedErrorMsg(rmsg, errorType); SEND_Q(rmsg, ch->m_desc); } } //생성 (파티 전환) void ProcHelperExped_CreateRep(CNetMsg::SP& msg) { char cExpedType1,cExpedType2,cExpedType3, cExpedType4, cExpedType5; int nMemberCount, nBossIndex; int nResult=0; //처리 결과 int i, j; CLCString BossName(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> cExpedType1 >> cExpedType2 >> cExpedType3 >> cExpedType4 >> cExpedType5 >> nBossIndex >> BossName >> nMemberCount; GAMELOG << init("EXPED DEBUG HELPER CREATE REP") << "cExpedType1" << delim << cExpedType1 << delim << "cExpedType2" << delim << cExpedType2 << delim << "cExpedType3" << delim << cExpedType3 << delim << "cExpedType4" << delim << cExpedType4 << delim << "cExpedType5" << delim << cExpedType5<< delim << "nMemberCount" << delim << nMemberCount << delim << "nBossIndex" << delim << nBossIndex << delim << "BossName" << delim << BossName << end; int* pCharIndex = new int[nMemberCount]; // 캐릭터 인덱스 CLCString* pCharName = new CLCString[nMemberCount]; // 캐릭터 이름 int* pGroupType = new int[nMemberCount]; // 그룹 타입 int* pMemberType = new int[nMemberCount]; // 멤버 타입 int* pSetLabelType = new int[nMemberCount]; // 표식 int* pQuitType = new int[nMemberCount]; // 정상 ,비정상 for( i=0; i < nMemberCount; i++) { RefMsg(msg) >> pCharIndex[i] >> pCharName[i] >> pGroupType[i] >> pMemberType[i] >> pSetLabelType[i] >> pQuitType[i]; GAMELOG << init("EXPED DEBUG HELPER CREATE REP") << "CharIndex[" << i << "]" << delim << pCharIndex[i] << delim << "CharName[" << i << "]" << delim << pCharName[i] << delim << "GroupType[" << i << "]" << delim << pGroupType[i] << delim << "MemberType[" << i << "]" << delim << pMemberType[i] << delim << "SetLabelType[" << i << "]" << delim << pSetLabelType[i] << delim << "QuitType[" << i << "]" << delim << pQuitType[i] << end; } CExpedition* pExped = NULL; int nJoinCnt = 0; CPC* pBoss = PCManager::instance()->getPlayerByCharIndex(nBossIndex); #ifdef EXTREME_CUBE CParty* party = gserver->FindPartyByBossIndex(nBossIndex); if(party && party->m_cubeUniqueIdx > 0) { nResult = 0; //실패 goto SKIP_EXPEDCREATEREP; } #endif if(!pBoss || pExped ) { nResult = 0; //실패 goto SKIP_EXPEDCREATEREP; } // 신규 원정대 생성 pExped = new CExpedition(cExpedType1, cExpedType2, cExpedType3, cExpedType4, cExpedType5, nBossIndex,(const char*)BossName,MSG_EXPED_GROUP_1,MSG_EXPED_MEMBERTYPE_BOSS,pBoss); if(pExped) { if(pBoss) { //원정대 포인터 지정(보스) pExped->SetMemberPCPtr(pBoss->m_index, pBoss); pBoss->m_Exped = pExped; } CExpedMember* pExpMember = NULL; for( i=0; i < nMemberCount; i++) { CPC* pMember = PCManager::instance()->getPlayerByCharIndex(pCharIndex[i]); if(pMember) { if(nBossIndex != pCharIndex[i]) { //대원 추가 pExpMember = (CExpedMember*) pExped->Join(pCharIndex[i],pCharName[i],MSG_EXPED_MEMBERTYPE_NORMAL,pMember); if(pExpMember) { //원정대 포인터 지정(대원) pExped->SetMemberPCPtr(pMember->m_index, pMember); pMember->m_Exped = pExped; pExpMember->SetLabelType(pSetLabelType[i]); pExpMember->SetQuitType(pQuitType[i]); nJoinCnt++; } } }else //로그아웃 캐릭터 조인 처리 { //대원 추가 pExpMember = (CExpedMember*) pExped->Join(pCharIndex[i],pCharName[i],MSG_EXPED_MEMBERTYPE_NORMAL,pMember); if(pExpMember) { pExpMember->SetLabelType(pSetLabelType[i]); pExpMember->SetQuitType(pQuitType[i]); nJoinCnt++; } } } if((pExped->GetMemberCount() - 1) == nJoinCnt ) { // 기존 파티 리스트 제거 CParty* pParty = gserver->FindPartyByBossIndex(nBossIndex); if (pParty) { // 파티 지우기 gserver->m_listParty.erase(pParty->GetBossIndex()); pParty->SetEndParty(); delete pParty; } { //결과 전송(원정대원 모두) CNetMsg::SP rmsg(new CNetMsg); ExpedCreateRepMsg(rmsg,cExpedType1,cExpedType2,cExpedType3,nBossIndex,BossName,nMemberCount,pCharIndex,pCharName,pGroupType,pMemberType,pSetLabelType,pQuitType); pExped->SendToAllPC(rmsg); } // 성공 (리스트 추가) gserver->m_listExped.insert(map_listexped_t::value_type(pExped->GetBossIndex(), pExped)); for( i = 0; i < MAX_EXPED_GROUP; i++) { for( j = 0; j < MAX_EXPED_GMEMBER; j++) { const CExpedMember* pMember = pExped->GetMemberByListIndex(i,j); // 모두 전송 if (pMember) { //대원들 정보 ==> 나에게 전송 CNetMsg::SP rmsg(new CNetMsg); ExpedAddMsg(rmsg, pMember->GetCharIndex(), pMember->GetCharName(), i, pMember->GetMemberType(), pMember->GetListIndex(), pMember->GetMemberPCPtr()); pExped->SendToAllPC( rmsg, -1 ); if(pMember->GetMemberPCPtr() != NULL) { pMember->GetMemberPCPtr()->CalcStatus(true); } } } } pExped->SetMemberRegister_AfterGoZone(pBoss); nResult = 1; //성공 }else { nResult = 0; //실패 } }else { nResult = 0; //실패 //에러 } SKIP_EXPEDCREATEREP: // 성공후 서버로 요청 결과(파티 제거 Helper)(미구현) { CNetMsg::SP rmsg(new CNetMsg); HelperExpedCreateResultMsg(rmsg, nResult, nBossIndex); SEND_Q(rmsg, gserver->m_helper); } delete[] pCharIndex; delete[] pCharName; delete[] pGroupType; delete[] pMemberType; delete[] pSetLabelType; delete[] pQuitType; } //초대 void ProcHelperExped_InviteRep(CNetMsg::SP& msg) { int nBossIndex; CLCString strBossName(MAX_CHAR_NAME_LENGTH + 1); int nTargetIndex; CLCString strTargetName(MAX_CHAR_NAME_LENGTH + 1); char cExpedType1; char cExpedType2; char cExpedType3; RefMsg(msg) >> nBossIndex >> strBossName >> nTargetIndex >> strTargetName >> cExpedType1 >> cExpedType2 >> cExpedType3; GAMELOG << init("EXPED DEBUG HELPER INVITE REP") << "nBossIndex" << delim << nBossIndex << delim << "strBossName" << delim << strBossName << delim << "nTargetIndex" << delim << nTargetIndex << delim << "strTargetName" << delim << strTargetName << delim << "cExpedType1" << delim << cExpedType1<< delim << "cExpedType2" << delim << cExpedType2 << delim << "cExpedType3" << delim << cExpedType3 << end; CPC* pBossPC = PCManager::instance()->getPlayerByCharIndex(nBossIndex); CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); if( pTargetPC && ( pTargetPC->IsParty() || pTargetPC->IsExped() ) ) { CNetMsg::SP rmsg(new CNetMsg); PartyErrorMsg(rmsg, MSG_PARTY_ERROR_ALREADY_TARGET); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); return; } CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if (pExped) { // 기존 원정대 초대 상태로 pExped->SetRequest(nTargetIndex, strTargetName); if (pTargetPC) pTargetPC->m_Exped = pExped; } { //초대 메세지 CNetMsg::SP rmsg(new CNetMsg); ExpedInviteRepMsg(rmsg, cExpedType1, cExpedType2, cExpedType3, nBossIndex, strBossName); if (pBossPC) SEND_Q(rmsg, pBossPC->m_desc); if (pTargetPC) SEND_Q(rmsg, pTargetPC->m_desc); } } //초대 수락 void ProcHelperExped_AllowRep(CNetMsg::SP& msg) { int nBossIndex; int nTargetIndex,nTargetGroup,nTargetMember,nTargetListIndex; CLCString strTargetName(MAX_CHAR_NAME_LENGTH + 1); int nErrorCode; RefMsg(msg) >> nBossIndex >> nTargetIndex >> strTargetName >> nTargetGroup >> nTargetMember >> nTargetListIndex >> nErrorCode; GAMELOG << init("EXPED DEBUG HELPER INVITE ALLOW REP") << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "strTargetName" << delim << strTargetName << delim << "nTargetGroup" << delim << nTargetGroup << delim << "nTargetMember" << delim << nTargetMember << delim << "nTargetListIndex" << delim << nTargetListIndex << delim << "nErrorCode" << delim << nErrorCode << delim << end; CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); if( !pTargetPC ) { return; } if( pTargetPC->IsParty() || pTargetPC->IsExped() ) { return; } CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if (pExped == NULL ) { return ; } CExpedMember* pMember = NULL; pMember = (CExpedMember*)pExped->JoinRequest(strTargetName, nTargetMember, pTargetPC); if (pMember==NULL) { return; } int i,j; if(nErrorCode == MSG_EXPED_ERROR_ALLOW_OK) { //새로운 타겟 => 원정대원 CNetMsg::SP rmsg(new CNetMsg); ExpedAddMsg(rmsg, nTargetIndex, strTargetName, nTargetGroup, nTargetMember, nTargetListIndex, pTargetPC); CNetMsg::SP addmsg(new CNetMsg); ExpedAddSysMsg(addmsg, strTargetName); for ( i = 0; i < MAX_EXPED_GROUP; i++) { for( j=0; j < MAX_EXPED_GMEMBER; j++) { const CExpedMember* pMember = pExped->GetMemberByListIndex(i,j); if (pMember) { if (pMember->GetMemberPCPtr()) { SEND_Q(rmsg, pMember->GetMemberPCPtr()->m_desc); SEND_Q(addmsg, pMember->GetMemberPCPtr()->m_desc); } } } } //원정대원 정보 => 새로운 타겟 for ( i = 0; i < MAX_EXPED_GROUP; i++) { for( j=0; j < MAX_EXPED_GMEMBER; j++) { const CExpedMember* pMember = pExped->GetMemberByListIndex(i,j); if (pMember) { // target에게는 타인을 추가 CNetMsg::SP rmsg(new CNetMsg); ExpedAddMsg(rmsg, pMember->GetCharIndex(), pMember->GetCharName(), pMember->GetGroupType(), pMember->GetMemberType(),pMember->GetListIndex(), pMember->GetMemberPCPtr()); SEND_Q(rmsg, pTargetPC->m_desc); } } } #ifdef BUGFIX_ALLOW_EXPED_TYPE_SET { CNetMsg::SP rmsg(new CNetMsg); ExpedChangeType(rmsg, 0, pExped->GetExpedType(0)); SEND_Q(rmsg, pTargetPC->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); ExpedChangeType(rmsg, 1, pExped->GetExpedType(1)); SEND_Q(rmsg, pTargetPC->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); ExpedChangeType(rmsg, 2, pExped->GetExpedType(2)); SEND_Q(rmsg, pTargetPC->m_desc); } #endif } } //초대 거절 void ProcHelperExped_RejectRep(CNetMsg::SP& msg) { int nBossIndex; int nTargetIndex; int nErrorCode; RefMsg(msg) >> nBossIndex >> nTargetIndex >> nErrorCode; GAMELOG << init("EXPED DEBUG HELPER INVITE REJECT REP") << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "nErrorCode" << delim << nErrorCode << end; CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if (!pExped) { return ; } if (pExped->GetRequestIndex() < 1) { return ; } CExpedMember *member= pExped->GetMemberByCharIndex( pExped->GetBossIndex() ); if( !member ) { return; } CPC* pBossPC = member->GetMemberPCPtr(); CPC* pRequestPC = PCManager::instance()->getPlayerByCharIndex(pExped->GetRequestIndex()); if(nErrorCode == MSG_EXPED_ERROR_REJECT_OK) { { CNetMsg::SP rmsg(new CNetMsg); if (pExped->GetRequestIndex() == nTargetIndex) ExpedMsg(rmsg, MSG_REJECT_DEST); else if (pExped->GetBossIndex() == nTargetIndex) ExpedMsg(rmsg, MSG_REJECT_SRC); else { return ; } if (pBossPC) { SEND_Q(rmsg, pBossPC->m_desc); } if (pRequestPC) { SEND_Q(rmsg, pRequestPC->m_desc); pRequestPC->m_Exped = NULL; } } pExped->SetRequest(-1, ""); if (pExped->GetMemberCount() < 2) { // 원정대 종료 gserver->m_listExped.erase(pExped->GetBossIndex()); pExped->SetEndExped(); delete pExped; } } } //탈퇴(나감) void ProcHelperExped_QuitRep(CNetMsg::SP& msg) { int nBossIndex; int nTargetIndex; int nErrorCode; int nQuitMode; // 정상,비정상 구분 CLCString strOldBossName(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> nBossIndex >> nTargetIndex >> nQuitMode >> nErrorCode; GAMELOG << init("EXPED DEBUG HELPER QUIT REP") << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "nQuitMode" << delim << nQuitMode << delim << "nErrorCode" << delim << nErrorCode << end; CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if (!pExped) return; if (nErrorCode == MSG_EXPED_ERROR_QUIT_END) { // 원정대 종료 gserver->m_listExped.erase(pExped->GetBossIndex()); pExped->SetEndExped(); delete pExped; } else { { // 원정대원 나감 CNetMsg::SP rmsg(new CNetMsg); ExpedQuitRepMsg(rmsg, nTargetIndex, nQuitMode); pExped->SendToAllPC(rmsg); } if(nQuitMode == MSG_EXPED_QUITMODE_NORMAL) { pExped->SetMemberPCPtr(nTargetIndex, NULL); pExped->DeleteMember(nTargetIndex); } // 보스 변경 알림(보스 변경 처리:자동 위임 처리 필요) if (nBossIndex == nTargetIndex) { //나가는 캐릭터가 보스이면 위임할 보스를 획득 함 CExpedMember* pNewBossMember = (CExpedMember*) pExped->FindNextBoss(); if(pNewBossMember) { pNewBossMember->SetMemberType(MSG_EXPED_MEMBERTYPE_BOSS); gserver->m_listExped.erase(nBossIndex); gserver->m_listExped.insert(map_listexped_t::value_type(pNewBossMember->GetCharIndex(), pExped)); if( pExped->m_nRaidAreaNum > -1 ) { CNetMsg::SP rmsg(new CNetMsg); HelperRaidInzoneSetNo( rmsg , pNewBossMember->GetCharIndex() , nBossIndex, pExped->m_nRaidZoneNum, MSG_JOINTYPE_EXPED, pExped->m_nDifficulty ); SEND_Q(rmsg, gserver->m_helper); } { CNetMsg::SP rmsg(new CNetMsg); ExpedChangeBoss(rmsg, nBossIndex , pNewBossMember->GetCharIndex(),MSG_EXPED_CHANGEBOSS_AUTO); pExped->SendToAllPC(rmsg); } } } } } //강퇴 void ProcHelperExped_KickRep(CNetMsg::SP& msg) { int nBossIndex; int nTargetIndex; int nErrorCode; RefMsg(msg) >> nBossIndex >> nTargetIndex >> nErrorCode; GAMELOG << init("EXPED DEBUG HELPER KICK REP") << "nBossIndex" << delim << nBossIndex << delim << "nTargetIndex" << delim << nTargetIndex << delim << "nErrorCode" << delim << nErrorCode << end; CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if (!pExped) { return ; } CPC* pTargetPC = PCManager::instance()->getPlayerByCharIndex(nTargetIndex); if (pTargetPC && pTargetPC->m_Exped && pTargetPC->m_Exped == pExped) { pTargetPC->CancelDamageLink(); pTargetPC->m_Exped = NULL; // 인존에 있는 PC 파티 탈퇴하면 인존을 나감(멤버) if(pTargetPC->m_nJoinInzone_ZoneNo >=0 && pTargetPC->m_nJoinInzone_RoomNo >= 0) { CNetMsg::SP rmsg(new CNetMsg); RaidInzoneQuitReq(rmsg,1,0); do_Raid(pTargetPC, rmsg); } } pExped->SetMemberPCPtr(nTargetIndex, NULL); pExped->DeleteMember(nTargetIndex); if(pTargetPC) pTargetPC->SetExpedLabel(-1); // 라벨을 초기화 해준다. bool bAllMsgSend= true; if (nErrorCode == MSG_EXPED_ERROR_KICK_END) { // 원정대 종료 gserver->m_listExped.erase(pExped->GetBossIndex()); pExped->SetEndExped(); delete pExped; bAllMsgSend= false; } { // 파티원 나감 CNetMsg::SP rmsg(new CNetMsg); ExpedKickMsg(rmsg, nTargetIndex); if (pTargetPC) SEND_Q(rmsg, pTargetPC->m_desc); if( bAllMsgSend ) pExped->SendToAllPC(rmsg, nTargetIndex); } } //대장 위임 void ProcHelperExped_ChangeBossRep(CNetMsg::SP& msg) { int nBossIndex; int nNewBossIndex,nChangeMode; RefMsg(msg) >> nBossIndex >> nNewBossIndex >> nChangeMode; GAMELOG << init("EXPED DEBUG HELPER CHANGEBOSS REP") << "nBossIndex" << delim << nBossIndex << delim << "nNewBossIndex" << delim << nNewBossIndex << delim << "nChangeMode" << delim << nChangeMode << end; CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if(!pExped) { return ; } pExped->ChangeBoss(nNewBossIndex,nBossIndex); if( pExped->m_nRaidAreaNum > -1 ) { CNetMsg::SP rmsg(new CNetMsg); HelperRaidInzoneSetNo( rmsg , nNewBossIndex , nBossIndex, pExped->m_nRaidZoneNum, MSG_JOINTYPE_EXPED, pExped->m_nDifficulty ); SEND_Q(rmsg, gserver->m_helper); } { CNetMsg::SP rmsg(new CNetMsg); ExpedChangeBoss(rmsg, nBossIndex, nNewBossIndex, nChangeMode); pExped->SendToAllPC(rmsg); } } //타입변경 void ProcHelperExped_ChangeTypeRep(CNetMsg::SP& msg) { int nBossIndex; char cDiviType,cExpedType; RefMsg(msg) >> nBossIndex >> cExpedType >> cDiviType; GAMELOG << init("EXPED DEBUG HELPER CHANGETYPE REP") << "nBossIndex" << delim << nBossIndex << delim << "cExpedType" << delim << cExpedType << delim << "cDiviType" << delim << cDiviType << end; CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if (!pExped) { return ; } // pExped->SetExpedType(cDiviType,cExpedType); pExped->SetExpedType(cExpedType,cDiviType); { CNetMsg::SP rmsg(new CNetMsg); ExpedChangeType(rmsg, cExpedType, cDiviType); pExped->SendToAllPC(rmsg); } } //부대장 임명 void ProcHelperExped_SetMBossRep(CNetMsg::SP& msg) { int nBossIndex, nNewMBossIndex; RefMsg(msg) >> nBossIndex >> nNewMBossIndex; GAMELOG << init("EXPED DEBUG HELPER SET MBOSS REP") << "nBossIndex" << delim << nBossIndex << delim << "nNewMBossIndex" << delim << nNewMBossIndex << end; CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if(!pExped) return ; CExpedMember* pMember = NULL; int nGroup, nListindex; nGroup = pExped->FindMemberGroupIndex(nNewMBossIndex); nListindex = pExped->FindMemberListIndex(nNewMBossIndex); if(nGroup < 0 || nListindex < 0 ) return; pMember = (CExpedMember*)pExped->GetMemberByListIndex(nGroup, nListindex); if(pMember) { //부대장 수 체크 if(pExped->GetGroupMembertypeCount(pMember->GetGroupType(),MSG_EXPED_MEMBERTYPE_MBOSS) >= 1) { //에러:한 그룹에 부대장 수 초과 return; } if (pExped->SetMBoss(nNewMBossIndex)) { CNetMsg::SP rmsg(new CNetMsg); ExpedSetMbossMsg(rmsg, nNewMBossIndex); pExped->SendToAllPC(rmsg); } } } //부대장 해임 void ProcHelperExped_ResetMBossRep(CNetMsg::SP& msg) { int nBossIndex, nNewMBossIndex; RefMsg(msg) >> nBossIndex >> nNewMBossIndex; GAMELOG << init("EXPED DEBUG HELPER RESET MBOSS REP") << "nBossIndex" << delim << nBossIndex << delim << "nNewMBossIndex" << delim << nNewMBossIndex << end; CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if(!pExped) return ; CExpedMember* pMember = NULL; int nGroup, nListindex; nGroup = pExped->FindMemberGroupIndex(nNewMBossIndex); nListindex = pExped->FindMemberListIndex(nNewMBossIndex); if(nGroup < 0 || nListindex < 0 ) return; pMember = (CExpedMember*)pExped->GetMemberByListIndex(nGroup, nListindex); if(pMember) { if(pMember->GetMemberType() != MSG_EXPED_MEMBERTYPE_MBOSS) { //에러: 부대장아 아님 return; } if (pExped->ResetMBoss(nNewMBossIndex)) { CNetMsg::SP rmsg(new CNetMsg); ExpedResetMbossMsg(rmsg, nNewMBossIndex); pExped->SendToAllPC(rmsg); } } } //원정대 해체 void ProcHelperExped_EndExpedRep(CNetMsg::SP& msg) { int nBossIndex; RefMsg(msg) >> nBossIndex; GAMELOG << init("EXPED DEBUG HELPER ENDEXPED REP") << "nBossIndex" << delim << nBossIndex << end; CExpedition* pExped = gserver->FindExpedByBossIndex(nBossIndex); if (!pExped) return; //삭제 gserver->m_listExped.erase(pExped->GetBossIndex()); pExped->SetEndExped(); delete pExped; } //그룹 이동 void ProcHelperExped_MoveGroupRep(CNetMsg::SP& msg) { int nBossIndex, nSourceGroup, nMoveCharIndex, nTargetGroup, nTargetListindex; RefMsg(msg) >> nBossIndex >> nSourceGroup >> nMoveCharIndex >> nTargetGroup >> nTargetListindex; GAMELOG << init("EXPED DEBUG HELPER MOVEGROUP REP") << "nBossIndex" << delim << nBossIndex << delim << "nSourceGroup" << delim << nSourceGroup << delim << "nMoveCharIndex" << delim << nMoveCharIndex << delim << "nTargetGroup" << delim << nTargetGroup << delim << "nTargetListindex" << delim << nTargetListindex << delim << end; CExpedition* pExped = gserver->FindExpedByBossIndex( nBossIndex); if (!pExped) return ; if(pExped->MoveGroup(nSourceGroup,nMoveCharIndex,nTargetGroup,nTargetListindex)) { //성공 CNetMsg::SP rmsg(new CNetMsg); ExpedMoveGroupRepMsg(rmsg, nSourceGroup, nMoveCharIndex, nTargetGroup, nTargetListindex); pExped->SendToAllPC(rmsg, -1); } } //에러 void ProcHelperRaidErrorRep(CNetMsg::SP& msg) { unsigned char errorType; int nCharIndex = -1; int nErrData1 = -1; int nErrData2 = -1; RefMsg(msg) >> errorType >> nCharIndex >> nErrData1 >> nErrData2; CPC* ch = PCManager::instance()->getPlayerByCharIndex(nCharIndex); if(!ch) return; { CNetMsg::SP rmsg(new CNetMsg); RaidErrorMsg(rmsg, errorType, nErrData1, nErrData2); SEND_Q(rmsg, ch->m_desc); } } //룸번호 획득 후 처리(개별적 처리) void ProcHelperInzoneGetRoomnoRep( CNetMsg::SP& msg) { int nCharIndex, nZoneNo, nRoomNo, nBossIndex, nBossRoomNo; RefMsg(msg) >> nCharIndex >> nZoneNo >> nRoomNo >> nBossIndex //파티 원정대 보스 인덱스 >> nBossRoomNo; int nDifficulty = -1; RefMsg(msg) >> nDifficulty; GAMELOG << init("RAID DEBUG HELPER GET INZONE ROOMNO REP") << "nCharIndex" << delim << nCharIndex << delim << "nZoneNo" << delim << nZoneNo << delim << "nRoomNo" << delim << nRoomNo << delim << "nBossIndex" << delim << nBossIndex << delim << "nDifficulty" << delim << nDifficulty << delim << end; CPC* ch = PCManager::instance()->getPlayerByCharIndex(nCharIndex); if(!ch) return; if(nZoneNo < 0) return; CZone* pZone=NULL; //int nCurrentZoneNo = ch->m_nJoinInzone_ZoneNo; 34번존에서 33번존으로 이동 시 입구로 이동시킴. int nCurrentZoneNo = ch->m_pZone->m_index; if((nZoneNo==ZONE_ALTER_OF_DARK || nZoneNo==ZONE_AKAN_TEMPLE || nZoneNo == ZONE_TARIAN_DUNGEON ) && nRoomNo != nBossRoomNo) { //에러: 귀속된 인존 정보가 원정대장 달라 접속 불가 CNetMsg::SP rmsg(new CNetMsg); RaidErrorMsg(rmsg, MSG_RAID_ERROR_INZONE_JOIN_NOTSAMEBOSSROOMNO); SEND_Q(rmsg, ch->m_desc); goto ERROR_RETURN; } pZone = gserver->FindZone(nZoneNo); if(pZone && pZone->m_area && pZone->m_zonePos) { CArea* area = NULL; // 원정대를 찾는다. if (ch->IsExped()) { // 들어가려는 존의 정보가 기존 레이드 정보의 존이 아니면 에러메시지를 출력 if(ch->m_Exped->m_nRaidZoneNum != -1 && ch->m_Exped->m_nRaidZoneNum != nZoneNo) { CNetMsg::SP rmsg(new CNetMsg); RaidErrorMsg(rmsg, MSG_RAID_ERROR_INZONE_JOIN_NOTSAMEBOSSROOMNO); SEND_Q(rmsg, ch->m_desc); goto ERROR_RETURN; } // 다른 맴버가 이미 들어가 있으면 따라 간다. if(ch->m_Exped->m_nRaidAreaNum != -1) { area = pZone->m_area + ch->m_Exped->m_nRaidAreaNum; if(area->m_nRaidRoomNo != nRoomNo) { CNetMsg::SP rmsg(new CNetMsg); RaidErrorMsg(rmsg, MSG_RAID_ERROR_INZONE_JOIN_NOTSAMEBOSSROOMNO); SEND_Q(rmsg, ch->m_desc); goto ERROR_RETURN; } } } // 파티 레이드이면 파티를 찾는다. else if(ch->IsParty()) { // 다른 맴버가 이미 들어가 있으면 따라 간다. if(ch->m_party->m_nRaidAreaNum != -1) area = pZone->m_area + ch->m_party->m_nRaidAreaNum; } // 파티와 레이드 중 아무것도 아니면 에러 메세지 else { CNetMsg::SP rmsg(new CNetMsg); RaidErrorMsg(rmsg, MSG_RAID_ERROR_INZONE_JOIN_NOTJOIN_PARTYOREXPED); SEND_Q(rmsg, ch->m_desc); goto ERROR_RETURN; } // area에 값을 못 넣었으면, 처음 입장하는 것이므로 빈 area로 간다. if(!area) { int a = pZone->FindEmptyArea(); if(a == -1) { //에러: 현재 인스턴스 너무 많아 더이상 생성 불가 CNetMsg::SP rmsg(new CNetMsg); RaidErrorMsg(rmsg, MSG_RAID_ERROR_INZONE_JOIN_ROOMCOUNT_FULL); SEND_Q(rmsg, ch->m_desc); goto ERROR_RETURN; } area = pZone->m_area + a; if(!area) goto ERROR_RETURN; // 다른 맴버들을 위해 area 넘버를 저장해둔다. if(ch->IsParty()) { ch->m_party->m_nRaidZoneNum = nZoneNo; ch->m_party->m_nRaidAreaNum = a; } else if(ch->IsExped()) { ch->m_Exped->m_nRaidAreaNum = a; } } if(ch->IsExped() && ch->m_index == nBossIndex) { ch->m_Exped->m_nRaidZoneNum = nZoneNo; ch->m_Exped->m_nDifficulty = nDifficulty; } int extra = 0; if(ch->IsExped() && pZone->IsExpedRaidZone()) { //현재 들어온 존, 룸번호 획득 ch->m_nJoinInzone_ZoneNo = nZoneNo; ch->m_nJoinInzone_RoomNo = nRoomNo; ch->m_nJoinInzone_AreaNo = area->m_index; if( (area->m_zone->m_index == ZONE_AKAN_TEMPLE || area->m_zone->m_index == ZONE_TARIAN_DUNGEON ) && area->GetPCCount() >= 8) { CNetMsg::SP rmsg(new CNetMsg); RaidErrorMsg(rmsg, MSG_RAID_ERROR_INZONE_JOIN_MEMBER_FULL); SEND_Q(rmsg, ch->m_desc); goto ERROR_RETURN; } GoZone(ch, nZoneNo, pZone->m_zonePos[extra][0], GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); GAMELOG << init("RAID DEBUG HELPER GET INZONE ROOMNO REP - STEP 1") << "JOIN INZONE SUCESS" << end; } // 원정대 레이드 존이 아니면 파티 레이드이다. else if(ch->IsParty() && pZone->IsPartyRaidZone()) { if(nCurrentZoneNo == ZONE_CAPPELLA_2 && nZoneNo == ZONE_CAPPELLA_1) { extra = 2; } //현재 들어온 존, 룸번호 획득 ch->m_nJoinInzone_ZoneNo = nZoneNo; ch->m_nJoinInzone_RoomNo = nRoomNo; ch->m_nJoinInzone_AreaNo = area->m_index; GoZone(ch, nZoneNo, pZone->m_zonePos[extra][0], GetRandom(pZone->m_zonePos[extra][1], pZone->m_zonePos[extra][3]) / 2.0f, GetRandom(pZone->m_zonePos[extra][2], pZone->m_zonePos[extra][4]) / 2.0f); GAMELOG << init("RAID DEBUG HELPER GET INZONE ROOMNO REP - STEP 1") << "JOIN INZONE SUCESS" << end; } else { //에러 GAMELOG << init("RAID DEBUG HELPER GET INZONE ROOMNO REP - STEP 2") << "JOIN INZONE FAIL" << end; goto ERROR_RETURN; } } // if ERROR_RETURN: ch->ResetPlayerState(PLAYER_STATE_WARP); return; } void ProcHelperDeleteRaidCharacterRep(CNetMsg::SP& msg) { int nCharIndex = 0, nSuccess = 0; RefMsg(msg) >> nCharIndex >> nSuccess; CPC* ch = PCManager::instance()->getPlayerByCharIndex(nCharIndex); if(!ch || !ch->m_desc) return; // DB 삭제 실패 시 if (nSuccess == 0) return; // DB 삭제 성공 시 else if (nSuccess == 1) { { // 귀속된 레이드 존 정보 창 비어있는 것으로 보여준다. CNetMsg::SP rmsg(new CNetMsg); RaidInfoMsg(rmsg, 0, NULL, NULL); SEND_Q(rmsg, ch->m_desc); } // 레이드 초기화 아이템을 삭제한다. CItem* item = ch->m_inventory.FindByDBIndex(4911, 0, 0); if( item ) { ch->m_inventory.decreaseItemCount(item, 1); } } return; } void ProcHelperRaidInfoRep(CNetMsg::SP& msg) { int nCharIndex = 0, nRaidCount = 0; RefMsg(msg) >> nCharIndex >> nRaidCount; CPC* ch = PCManager::instance()->getPlayerByCharIndex(nCharIndex); if(!ch || !ch->m_desc) return; int* nZoneNum = new int[nRaidCount]; int* nRoomNum = new int[nRaidCount]; for (int i=0; i < nRaidCount; i++) { RefMsg(msg) >> nZoneNum[i] >> nRoomNum[i]; } { CNetMsg::SP rmsg(new CNetMsg); if (nRaidCount >= 1) RaidInfoMsg(rmsg, nRaidCount, nZoneNum, nRoomNum); else RaidInfoMsg(rmsg, nRaidCount, NULL, NULL); SEND_Q(rmsg, ch->m_desc); } nZoneNum = NULL; nRoomNum = NULL; return; } void ProcHelperNSCreateCard(CNetMsg::SP& msg) { CDescriptor * desc; unsigned char subtype; int userindex, charindex, itemindex; RefMsg(msg) >> subtype >> userindex >> charindex; desc = DescManager::instance()->getDescByUserIndex(userindex); if(!desc) { if(subtype == MSG_HELPER_NS_CARD_ERROR_USE_OK) { // 아이템 사용 취소 메시지 보내기 GAMELOG << init("NS_CREATE_CARD_ERROR DESC NOTFOUND") << "USERINDEX" << delim << userindex << delim << "CHARINDEX" << delim << charindex << end; { CNetMsg::SP rmsg(new CNetMsg); HelperNSCreateCardUse(rmsg, MSG_HELPER_NS_CARD_USE_CANCEL, userindex, charindex); SEND_Q(rmsg, gserver->m_helper); } } return ; } switch(subtype) { case MSG_HELPER_NS_CARD_ERROR_USE_OK: { RefMsg(msg) >> itemindex; CItem* item; int row, col; CPC* pc = desc->m_pChar; if(!pc) { // 아이템 사용 취소 메시지 보내기 GAMELOG << init("NS_CREATE_CARD_ERROR PC NOTFOUND") << "USERINDEX" << delim << userindex << delim << "CHARINDEX" << delim << charindex << end; { CNetMsg::SP rmsg(new CNetMsg); HelperNSCreateCardUse(rmsg, MSG_HELPER_NS_CARD_USE_CANCEL, userindex, charindex); SEND_Q(rmsg, gserver->m_helper); } return ; } // 인벤에서 아이템 하나 제거시키기 item = pc->m_inventory.FindByVirtualIndex(itemindex); if (item == NULL) { GAMELOG << init("NS_CREATE_CARD_ERROR ITEM NOTFOUND") << "USERINDEX" << delim << userindex << delim << "CHARINDEX" << delim << charindex << end; { CNetMsg::SP rmsg(new CNetMsg); HelperNSCreateCardUse(rmsg, MSG_HELPER_NS_CARD_USE_CANCEL, userindex, charindex); SEND_Q(rmsg, gserver->m_helper); } return ; } pc->m_inventory.decreaseItemCount(item, 1); desc->m_bIsNSCreateCardUse = true; { // 클라이언트로 메시지 보내기 CNetMsg::SP rmsg(new CNetMsg); ResponseClient::ItemNotUseMsg(rmsg, MSG_ITEM_USE_ERROR_NS_CARD_USE_OK); SEND_Q(rmsg, pc->m_desc); } } break; case MSG_HELPER_NS_CARD_ERROR_CREATED_NS: case MSG_HELPER_NS_CARD_ERROR_90LV: case MSG_HELPER_NS_CARD_ERROR_ALREADY: case MSG_HELPER_NS_CARD_ERROR_ETC: { CPC* pc = desc->m_pChar; if(pc) { CNetMsg::SP rmsg(new CNetMsg); ResponseClient::ItemNotUseMsg(rmsg, MSG_ITEM_USE_ERROR_NS_CARD_INSUFF); SEND_Q(rmsg, pc->m_desc); } } break; default: break; } } #if defined(EVENT_WORLDCUP_2010) || defined(EVENT_WORLDCUP_2010_TOTO) || defined(EVENT_WORLDCUP_2010_TOTO_STATUS) || defined(EVENT_WORLDCUP_2010_TOTO_GIFT) || defined(EVENT_WORLDCUP_2010_ATTENDANCE) void ProcHelperWorldcup2010(CNetMsg::SP& msg) { unsigned char nSubType; unsigned char nErrType; int charIndex; RefMsg(msg) >> nSubType >> nErrType >> charIndex; CPC* ch = PCManager::instance()->getPlayerByCharIndex(charIndex); if( ch == NULL) return; CNetMsg::SP rmsg(new CNetMsg); switch(nSubType) { case MSG_HELPER_WORLDCUP2010_TOTO_REP: switch(nErrType) { case MSG_HELPER_WORLDCUP2010_TOTO_ERROR_SUC: { int itemidx; RefMsg(msg) >> itemidx; EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_REP, MSG_EVENT_WORLDCUP2010_TOTO_ERROR_SUC); } break; case MSG_HELPER_WORLDCUP2010_TOTO_ERROR_FAIL: { // DB 기록이 실패했당 지운 국기를 다시 지급하자 int Countryitemidx; RefMsg(msg) >> Countryitemidx; CItem * pItem = gserver->m_itemProtoList.CreateItem(Countryitemidx, -1, 0, 0, 1); if( pItem ) { if( ch->m_inventory.addItem(pItem) == false) { // 쓰바 지웠던 국기 지급이 안되었넹. 이를 어쩐다... ㅡㅡ;; // 로고는 찍고 FAIL을 날린다. GAMELOG << init("EVENT_WORLDCUP_2010 : TOTO ERROR", ch) << itemlog(pItem) << end; } } } EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_REP, MSG_EVENT_WORLDCUP2010_TOTO_ERROR_FAIL); break; } break; case MSG_HELPER_WORLDCUP2010_TOTO_STATUS_REP: { int resulttype=-1, itemindex; RefMsg(msg) >> resulttype >> itemindex; switch(nErrType) { case MSG_HELPER_WORLDCUP2010_TOTO_STATUS_ERROR_SUC: EventWorldcup2010TOTOStatusErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_STATUS_ERROR_SUC, resulttype, itemindex); break; case MSG_HELPER_WORLDCUP2010_TOTO_STATUS_ERROR_FAIL: EventWorldcup2010TOTOStatusErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_STATUS_ERROR_FAIL, resulttype); break; } } break; case MSG_HELPER_WORLDCUP2010_TOTO_GIFT_REP: switch(nErrType) { case MSG_HELPER_WORLDCUP2010_TOTO_GIFT_ERROR_SUC: // 선물만 주고 끝~ { int nTableCount = 7; int giftTable[7][2]= { // item_idx, count { 974, 1}, // 1. 행운의 제련석 {4968, 1}, // 2. (이벤트용)악마의 룬 아르 {2849, 1}, // 3. 힘 상승 물약(소) {2850, 1}, // 4. 민첩 상승 물약(소) {2851, 1}, // 5, 체질 상승 물약(소) {2852, 1}, // 6, 지혜 상승 물약(소) {2853, 1} // 7, 버서커 포션(소) }; if( ch->m_inventory.getEmptyCount() < nTableCount ) // 인벤 검사 { HelperWorldcup2010TOTOGiftRepMsg(rmsg, ch->m_index, 1); SEND_Q(rmsg, gserver->m_helper); EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_REP, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_ERROR_INVEN); break; } CItem ** pItem = NULL; pItem = new CItem*[nTableCount]; int i=0; for(i=0; i<nTableCount; i++) // 지급항 아이템을 다 생성하자. { pItem[i] = NULL; pItem[i] = gserver->m_itemProtoList.CreateItem( giftTable[i][0], -1, 0, 0, giftTable[i][1]); if( pItem[i] == NULL ) { int j; for( j=0; j<i; j++ ) { if( pItem[j] ) { delete [] pItem[j]; pItem[j] = NULL; } } delete [] pItem; EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_REP, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_ERROR_FAIL); HelperWorldcup2010TOTOGiftRepMsg(msg, ch->m_index, 1); break; } } for(i=0; i<nTableCount; i++) { if( ch->m_inventory.addItem(pItem[i]) == false ) { GAMELOG << init("EVENT_WORLDCUP_2010 : TOTO GIFT ADD ERROR", ch) << itemlog(pItem[i]) << end; int j=0; for(j=0; j<i; j++) { GAMELOG << init("EVENT_WORLDCUP_2010 : TOTO GIFT DEL", ch) << itemlog(pItem[j]) << end; ch->m_inventory.decreaseItemCount(pItem[j], 1); delete pItem[j]; pItem[j] = NULL; } delete [] pItem; HelperWorldcup2010TOTOGiftRepMsg(rmsg, ch->m_index, 1); SEND_Q(rmsg, gserver->m_helper); EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_REP, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_ERROR_FAIL); break; } } EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_REP, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_ERROR_SUC); } break; case MSG_HELPER_WORLDCUP2010_TOTO_GIFT_ERROR_FAIL: EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_REP, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_ERROR_FAIL); break; case MSG_HELPER_WORLDCUP2010_TOTO_GIFT_ERROR_AREADY: EventErrorMsg(rmsg, MSG_EVENT_ERROR_ALREADY_GIVE); break; } break; case MSG_HELPER_WORLDCUP2010_ATTENDANCE_REP: switch(nErrType) { case MSG_HELPER_WORLDCUP2010_ATTENDANCE_ERROR_SUC: // 응원 카드를 지급하자 { int supportIndex = 19; CItem * pItem = gserver->m_itemProtoList.CreateItem( supportIndex, -1, 0, 0, 1); if( pItem == NULL ) { EventWorldcup2010ErrorMsg(rmsg,MSG_EVENT_WORLDCUP2010_TOTO_GIFT_REP, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_ERROR_FAIL); SEND_Q(rmsg, ch->m_desc); break; } // 인벤 검사 if ( ch->m_inventory.getEmptyCount() < 1 ) { EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_REP, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_ERROR_INVEN); break; } if( ch->m_inventory.addItem(pItem) == false ) { EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_REP, MSG_EVENT_WORLDCUP2010_TOTO_GIFT_ERROR_FAIL); break; } } EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_ATTENDANCE_REP, MSG_EVENT_WORLDCUP2010_ATTENDANCE_ERROR_SUC); break; case MSG_HELPER_WORLDCUP2010_ATTENDANCE_ERROR_ALREADY: EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_ATTENDANCE_REP, MSG_EVENT_WORLDCUP2010_ATTENDANCE_ERROR_ALREADY); break; case MSG_HELPER_WORLDCUP2010_ATTENDANCE_ERROR_FAIL: EventWorldcup2010ErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_ATTENDANCE_REP, MSG_EVENT_WORLDCUP2010_ATTENDANCE_ERROR_FAIL); break; } break; case MSG_HELPER_WORLDCUP2010_KOREA_REP: { int item[7][5] = { {5819, 5820, 5821, 5822, 5823}, // 타이탄 {5824, 5825, 5826, 5827, 5828}, // 나이트 {5804, 5805, 5806, 5807, 5808}, // 힐러 {5809, 5810, 5811, 5812, 5813}, // 메이지 {5814, 5815, 5816, 5817, 5818}, // 로그 {5829, 5830, 5831, 5832, 5833}, // 소서러 {5834, 5835, 5836, 5837, 5838} // 나이트쉐도우 }; int i, j; switch(nErrType) { case MSG_HELPER_WORLDCUP2010_KOREA_ERROR_EMPTY: { // 일반 슬롯 체크 if( ch->m_inventory.getEmptyCount() < 5) { EventErrorMsg(rmsg, MSG_EVENT_ERROR_FULLINVENTORY); SEND_Q(rmsg, ch->m_desc); return; } HelperWorldcup2010KoreaRepMsg(rmsg, ch->m_index, 1); // 지급 완료 요청 SEND_Q(rmsg, gserver->m_helper); return; } break; case MSG_HELPER_WORLDCUP2010_KOREA_ERROR_SUC: { CItem* pItem[5]; for( i = 0; i < 5; i++ ) // 지급할 아이템 모두 생성 { pItem[i] = gserver->m_itemProtoList.CreateItem(item[ch->m_job][i], -1, 0, 0, 1); if( pItem[i] == NULL ) { for( j = 0; j < i; j++ ) { if( pItem[j] ) { delete pItem[j]; pItem[j] = NULL; } } EventErrorMsg(rmsg, MSG_EVENT_ERROR_INSUFF_CONDITION); SEND_Q(rmsg, ch->m_desc); return; } } for( i = 0; i < 5; i++ ) { if( ch->m_inventory.addItem(pItem[i]) == false) { GAMELOG << init("EVENT_WORLDCUP_2010 : KOREA 16 GIFT ADD ERROR", ch) << itemlog(pItem[i]) << end; HelperWorldcup2010KoreaRepMsg(rmsg, ch->m_index, 2); // 지급 실패 요청 SEND_Q(rmsg, gserver->m_helper); return; } else { GAMELOG << init("EVENT_WORLDCUP_2010 : KOREA 16 GIFT ADD", ch) << itemlog(pItem[i]) << end; } } EventWorldcup2010KoreaErrorMsg(rmsg, MSG_EVENT_WORLDCUP2010_KOREA_ERROR_SUC); } break; case MSG_HELPER_WORLDCUP2010_KOREA_ERROR_ALREADY: EventErrorMsg(rmsg, MSG_EVENT_ERROR_ALREADY_GIVE); break; case MSG_HELPER_WORLDCUP2010_KOREA_ERROR_FAIL: EventErrorMsg(rmsg, MSG_EVENT_ERROR_INSUFF_CONDITION); break; } break; } } SEND_Q(rmsg, ch->m_desc); } #endif // defined(EVENT_WORLDCUP_2010) || defined(EVENT_WORLDCUP_2010_TOTO_STATUS) || defined(EVENT_WORLDCUP_2010_TOTO_GIFT) || defined(EVENT_WORLDCUP_2010_ATTENDANCE) void ProcHelperTeachRenewer(CNetMsg::SP& msg) { unsigned char subtype; RefMsg(msg) >> subtype; switch( subtype ) { case MSG_HELPER_TEACH_RENEWER_TIME_LIMIT_REP: ProcHelperTeachRenewerTimeLimit(msg); break; case MSG_HELPER_TEACH_RENEWER_TEACHER_GIFT_REP: ProcHelperTeachRenewerGift(msg); break; } } void ProcHelperTeachRenewerTimeLimit(CNetMsg::SP& msg) { int teacherIDX; int cnt, i; int studentIDX; RefMsg(msg) >> teacherIDX >> cnt; CPC * ch = PCManager::instance()->getPlayerByCharIndex(teacherIDX); if( ch == NULL ) return; for(i=0; i<cnt; i++) { RefMsg(msg) >> studentIDX; int j; for(j=0; j<TEACH_MAX_STUDENTS; j++) { if( ch->m_teachIdx[j] != -1 && studentIDX == ch->m_teachIdx[j] ) { CPC * pStudentPc = PCManager::instance()->getPlayerByCharIndex(studentIDX); if( pStudentPc ) continue; ch->m_cntFailStudent++; ch->m_cntTeachingStudent--; if( ch->m_cntTeachingStudent < 0) ch->m_cntTeachingStudent = 0; { CNetMsg::SP rmsg(new CNetMsg); TeachEndMsg(rmsg, ch->m_index, ch->GetName(), ch->m_teachIdx[j], ch->m_teachName[j], MSG_TEACH_END_FAIL); RefMsg(rmsg) << ch->m_cntTeachingStudent << ch->m_cntCompleteStudent << ch->m_cntFailStudent; SEND_Q(rmsg, ch->m_desc); } { CNetMsg::SP rmsg(new CNetMsg); HelperTeachTimeover(rmsg, CANCELTEACHER | CANCELSTUDENT , ch->m_index, ch->m_teachIdx[j]); SEND_Q(rmsg, gserver->m_helper); } GAMELOG << init("TEACH_FAIL_TIMEOVER") << "STU_INDEX" << delim << ch->m_teachIdx[j] << delim << "STU_NAME" << delim << ch->m_teachName[j] << delim << ch->m_name << delim << ch->m_nick << delim << ch->m_desc->m_idname << delim << ch->m_fame << end; // 혼자 셋팅해제 ch->m_teachIdx[j] = -1; ch->m_teachJob[j] = -1; ch->m_teachJob2[j] = 0; ch->m_teachLevel[j] = 0; ch->m_teachName[j][0] = '\0'; //0627 } } // teachType 검사 bool bTeacher = false; int i; for (i=0; i<TEACH_MAX_STUDENTS; i++) { if (ch->m_teachIdx[i] != -1) { bTeacher = true; break; } } if (!bTeacher) ch->m_teachType = MSG_TEACH_NO_TYPE; } } void ProcHelperTeachRenewerGift(CNetMsg::SP& msg) { unsigned char errorType; int charindex; RefMsg(msg) >> errorType >> charindex; CPC * ch = PCManager::instance()->getPlayerByCharIndex(charindex); if( ch == NULL ) return; switch( errorType ) { case MSG_HELPER_TEACH_RENEWER_GIFT_ERROR: case MSG_HELPER_TEACH_RENEWER_GIFT_DB: { CNetMsg::SP rmsg(new CNetMsg); TeachTeacherGiftMsg(rmsg, MSG_TEACH_GIFT_ERROR, ch); SEND_Q(rmsg, ch->m_desc); } break; case MSG_HELPER_TEACH_RENEWER_GIFT_NOMORE: { CNetMsg::SP rmsg(new CNetMsg); TeachTeacherGiftMsg(rmsg, MSG_TEACH_GIFT_NOMORE, ch); SEND_Q(rmsg, ch->m_desc); } break; case MSG_HELPER_TEACH_RENEWER_GIFT_SUC: { int nCount; RefMsg(msg) >> nCount; int itemIndex = 5952; // 후견인의 증표 if( false == ch->GiveItem(itemIndex, 0, 0, (LONGLONG)nCount, false, false) ) { { CNetMsg::SP rmsg(new CNetMsg); HelperTeacherGiftAddReqMsg(rmsg, ch->m_index, nCount); SEND_Q(rmsg, gserver->m_helper); } { CNetMsg::SP rmsg(new CNetMsg); TeachTeacherGiftMsg(rmsg, MSG_TEACH_GIFT_ERROR, ch); SEND_Q(rmsg, ch->m_desc); } } else { CNetMsg::SP rmsg(new CNetMsg); TeachTeacherGiftMsg(rmsg, MSG_TEACH_GIFT_SUC, ch, nCount); SEND_Q(rmsg, ch->m_desc); } } break; } } void ProcHelperFaceOff(CNetMsg::SP& msg) { int charIndex; char hairStyle, faceStyle; unsigned char errorType; RefMsg(msg) >> errorType >> charIndex >> hairStyle >> faceStyle; switch( errorType ) { case MSG_EX_FACEOFF_ERROR_SUC: GAMELOG << init("FACE OFF SUC - DB"); break; case MSG_EX_FACEOFF_ERROR_FAIL: GAMELOG << init("FACE OFF FAIL - DB "); break; } GAMELOG << charIndex << delim << hairStyle << delim << faceStyle << end; } #ifdef EVENT_CHAR_BIRTHDAY void ProcHelperCharBirthday(CNetMsg::SP& msg) { unsigned char subtype; int charindex;; RefMsg(msg) >> subtype >> charindex; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charindex); if( pc == NULL ) return; switch( (int)subtype ) { case MSG_EVENT_CHAR_BIRTHDAY_GIFT_REP: { unsigned char errortype; RefMsg(msg) >> errortype; switch( (MSG_EVENT_CHAR_BIRTHDAY_ERROR_TYPE)errortype ) { case MSG_EVENT_CHAR_BIRTHDAY_ERROR_SUC: { int years; RefMsg(msg) >> years; if( pc->m_inventory.getEmptyCount() < 1 ) { CNetMsg::SP rmsg(new CNetMsg); SysFullInventoryMsg(rmsg, 0); SEND_Q(rmsg, pc->m_desc); return; } if( years > 10 ) // 10년이 넘어가면 10년 짜리 아이템으로 준다. years = 10; int giftindex= 6717 + years; // 보상품은 6718 ~ 6727 (1주년부터 10주년까지) if( !pc->GiveItem(giftindex, 0, 0, 1) ) { GAMELOG << init("EVENT_CHAR_BIRTHDAY : ITEM GIVE FAIL", pc) << giftindex << end; CNetMsg::SP rmsg(new CNetMsg); EventCharBirthdayErrorMsg(rmsg, MSG_EVENT_CHAR_BIRTHDAY_ERROR_FAIL ); SEND_Q(rmsg, pc->m_desc); return; } { GAMELOG << init("EVENT_CHAR_BIRTHDAY : ITEM GIVE SUC", pc) << giftindex << end; CNetMsg::SP rmsg(new CNetMsg); EventCharBirthdayErrorMsg(rmsg, MSG_EVENT_CHAR_BIRTHDAY_ERROR_SUC); SEND_Q(rmsg, pc->m_desc); } } break; case MSG_EVENT_CHAR_BIRTHDAY_ERROR_FAIL: { CNetMsg::SP rmsg(new CNetMsg); EventCharBirthdayErrorMsg(rmsg, MSG_EVENT_CHAR_BIRTHDAY_ERROR_FAIL); SEND_Q(rmsg, pc->m_desc); } break; } } break; case MSG_EVENT_CHAR_BIRTHDAY_BDAY_REP: { int yy; char mm, dd; RefMsg(msg) >> yy >> mm >> dd; CNetMsg::SP rmsg(new CNetMsg); rmsg->Init(MSG_EVENT); RefMsg(rmsg) << (unsigned char) MSG_EVENT_CHAR_BIRTHDAY << (unsigned char) MSG_EVENT_CHAR_BIRTHDAY_BDAY_REP << yy; if( yy > 0 ) { RefMsg(rmsg) << mm << dd ; } SEND_Q(rmsg, pc->m_desc); } break; } } #endif #ifdef DEV_GUILD_MARK void ProcHelperGuildMarkExpire(CNetMsg::SP& msg) { // helper에서 길드마크 시간을 계산하고 만료가 되었으면 게임서버가 받아서 클라이언트에게 뿌려준다. unsigned char command; int GuildIndex = 0; RefMsg(msg) >> command >> GuildIndex; // if(command == -1) // return ; if(GuildIndex == 0) return ; if(command == 0) { CGuild* pGuild = NULL; pGuild = gserver->m_guildlist.findguild(GuildIndex); if(pGuild) { CNetMsg::SP rmsg(new CNetMsg); pGuild->SetGuildMark(-1, -1, -1, -1, -1); GuildMarkExpireMsg(rmsg); pGuild->SendToAll(rmsg, true); } } } void ProcHelperGuildMarkRegist(CNetMsg::SP& msg) { int GuildIndex = 0; int CharIndex = 0; char command = -1; char gm_row = -1; char gm_col = -1; char bg_row = -1; char bg_col = -1; unsigned short tab = -1; unsigned short invenIndex = -1; int markTime = -1; CLCString serial; bool bRollback = false; RefMsg(msg) >> GuildIndex >> CharIndex >> command >> gm_row >> gm_col >> bg_row >> bg_col >> tab >> invenIndex >> markTime >> serial; CPC* pc = NULL; pc = PCManager::instance()->getPlayerByCharIndex(CharIndex); CGuild* pGuild = NULL; pGuild = gserver->m_guildlist.findguild(GuildIndex); switch((int)command) { case 0: { if(pGuild) { pGuild->SetGuildMark(gm_row, gm_col, bg_row, bg_col, markTime); if(pc) { CItem* pItem = pc->m_inventory.getItem(tab, invenIndex); if (pItem == NULL) { bRollback = true; } else if(pItem->m_serial != (const char *)serial) { bRollback = true; } else if(pItem->m_itemProto->getItemTypeIdx() == ITYPE_ETC && pItem->m_itemProto->getItemSubTypeIdx() == IETC_GUILD_MARK) { // 아이템이 있고, 찾았으니까..하나를 줄어들게 한다. pc->m_inventory.decreaseItemCount(pItem, 1); } } { CNetMsg::SP rmsg(new CNetMsg); GuildMarkEditFinMsg(rmsg, pGuild->GetGuildMarkRow(), pGuild->GetGuildMarkCol(), pGuild->GetBackgroundRow(), pGuild->GetBackgroundCol(), pGuild->GetMarkTimeConvertGameTime()); pGuild->SendToAll(rmsg, true); } if(bRollback == true) { // DB에 저장된 정보를 롤백 시킨다. CNetMsg::SP rmsg(new CNetMsg); HelperGuildMarkRegistReqMsg(rmsg, GuildIndex, CharIndex, -1, -1, -1, -1, -1, -1, -1, NULL); SEND_Q(rmsg, gserver->m_helper); } } } break; case 1: { if(pc) { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_GUILD_ERROR_NOGUILD); SEND_Q(rmsg, pc->m_desc); return ; } } break; case 2: // MSG_NEW_GUILD_ERROR_SYSTEM { if(pc) { CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, MSG_NEW_GUILD_ERROR_SYSTEM); SEND_Q(rmsg, pc->m_desc); return ; } } break; case 3: { // 롤백 되었으니 모든 서버에 있는 길드원들에게 알려준다. if(pGuild) { pGuild->SetGuildMark(-1, -1, -1, -1, -1); CNetMsg::SP rmsg(new CNetMsg); GuildMarkEditFinMsg(rmsg, pGuild->GetGuildMarkRow(), pGuild->GetGuildMarkCol(), pGuild->GetBackgroundRow(), pGuild->GetBackgroundCol(), pGuild->GetMarkTimeConvertGameTime()); pGuild->SendToAll(rmsg, true); } } break; default: break; } } #endif #ifdef WARCASTLE_STATE_CHANNEL_CYNC void ProcHelperCastleStateCync(CNetMsg::SP& msg) { int mercState; RefMsg(msg) >> mercState; CWarCastle* pMercWar = CWarCastle::GetCastleObject(ZONE_MERAC); if( pMercWar ) { if( gserver->m_subno != WAR_CASTLE_SUBNUMBER_MERAC) // 공성 채널은 갱신해줄 필요가 없다. pMercWar->SetStateChannelCync( mercState ); } int dratanState; RefMsg(msg) >> dratanState; CWarCastle * pDratanWar = CWarCastle::GetCastleObject(ZONE_DRATAN); if( pDratanWar ) { if( gserver->m_subno != WAR_CASTLE_SUBNUMBER_DRATAN) // 공성 채널은 갱신해줄 필요가 없다. pDratanWar->SetStateChannelCync(dratanState); } } #endif // WARCASTLE_STATE_CHANNEL_CYNC #ifdef DEV_GUILD_STASH void LogGuildStash(CItem* pItem, const LONGLONG count, const unsigned char type, CPC* pc) { /* if type is 0 keep item to stash if type is 1 take item to stash */ char tmpBuf[MAX_STRING_LENGTH] = {0,}; if ( type == GUILD_STASH_KEEP_LOG ) strcpy(tmpBuf, "SUCCESS KEEP ITEM TO GUILD STASH"); else if ( type == GUILD_STASH_TAKE_LOG ) strcpy(tmpBuf, "SUCCESS TAKE ITEM TO GUILD STASH"); else return ; GAMELOG << init(tmpBuf, pc); if (pItem->IsRareItem() == true && pItem->m_pRareOptionProto != NULL && pItem->m_pRareOptionProto->GetIndex() > 0) { GAMELOG << "[rare index: " << pItem->m_pRareOptionProto->GetIndex() << delim << "rare bit: " << pItem->m_nRareOptionBit << "] " ; } GAMELOG << pItem->getDBIndex() << delim << pItem->m_itemProto->getItemName() << delim << pItem->m_serial.c_str() << delim << pItem->getWearPos() << delim << pItem->getPlus() << delim << pItem->getFlag() << delim << pItem->getUsed() << delim << pItem->getUsed_2() << delim << count << delim << "OPTION" << delim << pItem->m_nOption << delim; for (int i = 0; i < pItem->m_nOption; i++) { GAMELOG << pItem->m_option[i].m_type << delim << pItem->m_option[i].m_value << delim; } GAMELOG << "SOCKET" << delim; for (int i = 0; i < MAX_SOCKET_COUNT; i++) { GAMELOG << pItem->m_socketList.GetJewelAt(i) << delim; } GAMELOG << end; } //XX 길드창고 - 리스트 (3) void ProcHelperGuildStashList(CNetMsg::SP& msg) { int charIndex = 0; int totalPage = 0; int curPage = 0; int itemCount = 0; int i = 0; int isNas = 0; GoldType_t money = 0; CLCString timeStamp(32); int capacity = 0; int subtype; GoldType_t moneyCount = 0; int nasStashIndex; msg->MoveFirst(); RefMsg(msg) >> subtype >> charIndex >> timeStamp >> capacity >> money >> itemCount; CPC* pc = NULL; pc = PCManager::instance()->getPlayerByCharIndex(charIndex); if( pc == NULL ) // 그런사람 없습니다. { return; } CNetMsg::SP rmsg(new CNetMsg); GuildStashListMsg( rmsg , timeStamp, capacity, money, itemCount ); CItem** ppDummyItem = new CItem*[itemCount]; for( i=0 ; i< itemCount ; i++ ) { int stashIndex = 0; int index = 0; int plus = 0; int flag = 0; int used = -1; int used2 = -1; LONGLONG count = 0; short option[MAX_ITEM_OPTION]; CLCString socket(1024); int itemOrigin[MAX_VARIATION_COUNT]; int now_dur = 0; int max_dur = 0; RefMsg(msg) >> stashIndex >> index >> plus >> flag >> used >> used2 >> now_dur >> max_dur >> count; for ( int idx = 0 ; idx < MAX_ITEM_OPTION ; ++idx ) RefMsg(msg) >> option[idx]; RefMsg(msg) >> socket ; RefMsg(msg) >> itemOrigin[0] >> itemOrigin[1] >> itemOrigin[2] >> itemOrigin[3] >> itemOrigin[4] >> itemOrigin[5] ; // 더미로 하나 만들고 MSG 만들어서 지워? ppDummyItem[i] = gserver->m_itemProtoList.CreateDBItem_2( index, -1, plus, flag, used, used2, "DUMMY", count, option, socket, itemOrigin ); if( ppDummyItem[i] ) { ppDummyItem[i]->setNowDurability(now_dur); ppDummyItem[i]->setMaxDurability(max_dur); RefMsg(rmsg) << stashIndex << ppDummyItem[i]->getDBIndex() << ppDummyItem[i]->getPlus() << ppDummyItem[i]->getFlag() << ppDummyItem[i]->getUsed() << ppDummyItem[i]->getUsed_2() << ppDummyItem[i]->getNowDurability() << ppDummyItem[i]->getMaxDurability() << ppDummyItem[i]->Count(); ItemPublicMsg(rmsg, ppDummyItem[i]); ItemSocketMsg(rmsg, ppDummyItem[i]); } else { LOG_ERROR("Invalid Item Index. index[%d], count[%d]", index, count); } } SEND_Q( rmsg, pc->m_desc ); for( i = 0 ; i < itemCount ; ++i ) { if( ppDummyItem[i] ) delete ppDummyItem[i]; } delete [] ppDummyItem; } //XX 길드창고 - 보관 (3) void ProcHelperGuildStashKeep(CNetMsg::SP& msg) { int charIndex = 0; int guildIndex = 0; char error = 0; // 0: 성공 , 1:길드 없음 , 2:인벤부족, 3:무게초과 4: 다른 길드원이 사용중 RefMsg(msg) >> charIndex >> guildIndex >> error; // PC 찾고 CPC* pc = PCManager::instance()->getPlayerByCharIndex(charIndex); if( !pc ) { // Helper 로 UnLock 요청 CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 1 ); SEND_Q( rmsg, gserver->m_helper ); return; } pc->m_guildStashLock = false; // Helper 에서 온 error 처리 // 1,2,3 인경우 에만 Helper 에 Unlock 하고, 4 인경우는 보내지 않음 // error 1,2,3,4 는 클라에 전달 switch ( error ) { case 0: // 성공 break; case 1: case 2: case 3: { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 1 ); // 1. 실패 SEND_Q( rmsg, gserver->m_helper ); } case 4: // 다른 누군가 사용중 case 9: // 길드 창고 공간 없음 { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_KEEP , error ); SEND_Q( rmsg, pc->m_desc ); } break; default : // 무슨일이 생겼다!!! Unlock 해주자 { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 1 ); // 1. 실패 SEND_Q( rmsg, gserver->m_helper ); } break; } // Helper 에서 넘어온 에러가 있으면 여기까지 if( error > 0 ) return; // 혹시나 길드 확인 if( !pc->m_guildInfo || !pc->m_guildInfo->guild() || pc->m_guildInfo->guild()->index() != guildIndex ) { { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 1 ); SEND_Q( rmsg, gserver->m_helper ); } { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_KEEP , 1 ); SEND_Q( rmsg, pc->m_desc ); } return; } // 아이템 및 돈 차감 bool bCanKeep = true; LONGLONG keepMoney = 0; int nItemCount = 0; CLCString serial(MAX_SERIAL_LENGTH + 1); RefMsg(msg) >> keepMoney >> nItemCount; if (keepMoney > 0) { GoldType_t oldNas = pc->m_inventory.getMoney(); pc->m_inventory.decreaseMoney(keepMoney); { CNetMsg::SP rmsg(new CNetMsg); UpdateClient::makeUpdateMoneyDescReason(rmsg, NAS_DESC_REASON_GUILD_KEEP, keepMoney); SEND_Q(rmsg, pc->m_desc); } GAMELOG << init("SUCCESS KEEP NAS TO GUILD STASH", pc) << "CHAR INDEX : " << pc->m_index << delim << "BEFORE NAS : " << oldNas << delim << "KEEP NAS : " << keepMoney << delim << "AFTER NAS : " << pc->m_inventory.getMoney() << end; } // Memory 할당후 Delete 하지 않고 Return 되지 않도록 주의 CItem** pKeepItem = new CItem*[nItemCount]; LONGLONG* pKeepItemCount = new LONGLONG[nItemCount]; int dbIndex; int vIndex; // msg 뽑으면서 아이템을 확인 for( int i = 0 ; i < nItemCount ; ++i ) { RefMsg(msg) >> serial >> pKeepItemCount[i] >> dbIndex >> vIndex; pKeepItem[i] = pc->m_inventory.FindByVirtualIndex(vIndex); if(pKeepItem[i]) { if( pKeepItem[i]->Count() >= pKeepItemCount[i] ) continue; else{ bCanKeep = false; break; } } else { bCanKeep = false; } } if( bCanKeep ) { for( int i = 0 ; i < nItemCount ; ++i ) { LogGuildStash(pKeepItem[i], pKeepItemCount[i], GUILD_STASH_KEEP_LOG, pc); pc->m_inventory.decreaseItemCount(pKeepItem[i], pKeepItemCount[i]); pKeepItem[i] = NULL; pKeepItemCount[i] = 0; } { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 0, keepMoney ); SEND_Q( rmsg, gserver->m_helper ); } { // 성공 CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_KEEP , 0 ); SEND_Q( rmsg, pc->m_desc ); } // 실시간 저장 DBManager::instance()->SaveCharacterInfo(pc->m_desc, false); } else { { // 실패 CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 1 ); SEND_Q( rmsg, gserver->m_helper ); } { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_KEEP , 1 ); SEND_Q( rmsg, pc->m_desc ); } } delete [] pKeepItem; delete [] pKeepItemCount; return; } //XX 길드창고 - 찾기 (3) void ProcHelperGuildStashTake(CNetMsg::SP& msg) { int charIndex = 0; int guildIndex = 0; char error = 0; RefMsg(msg) >> charIndex >> guildIndex >> error; // 0: 성공 , 1:길드 없음 , 2:인벤부족, 3:무게초과 4: 다른 길드원이 사용중 5: 찾을수 없는 아이템 // PC 찾고 CPC* pc = PCManager::instance()->getPlayerByCharIndex(charIndex); if( !pc ) { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 1 ); // Helper 로 UnLock 요청 SEND_Q( rmsg, gserver->m_helper ); return; } pc->m_guildStashLock = false; // Helper 에서 온 error 처리 // 1,2,3,5 인경우 에만 Helper 에 Unlock 하고, 4 인경우는 보내지 않음 // error 1,2,3,4 는 클라에 전달 switch ( error ) { case 0: // 성공 break; case 1: case 2: case 3: case 5: { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 1 ); // 1. 실패 SEND_Q( rmsg, gserver->m_helper ); } case 4: // 다른 누군가 사용중 { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_TAKE , error ); SEND_Q( rmsg, pc->m_desc ); } break; default : // 무슨일이 생겼다!!! Unlock 해주자 { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashKeepErrorMsg( rmsg, charIndex, guildIndex, 1 ); // 1. 실패 SEND_Q( rmsg, gserver->m_helper ); } break; } // Helper 에서 넘어온 에러가 있으면 여기까지 if( error > 0 ) return; // 혹시나 길드 확인 if( !pc->m_guildInfo || !pc->m_guildInfo->guild() || pc->m_guildInfo->guild()->index() != guildIndex ) { { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashTakeErrorMsg( rmsg, charIndex, guildIndex, 1 ); SEND_Q( rmsg, gserver->m_helper ); } { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_TAKE , 1 ); SEND_Q( rmsg, pc->m_desc ); } return; } // 메세지 뽑고 LONGLONG takeMoney = 0; int itemCount = 0; int index = 0; int plus = 0; int flag = 0; int used = -1; int used2 = -1; LONGLONG count = 0; short option[MAX_ITEM_OPTION] = {0,}; CLCString serial(MAX_SERIAL_LENGTH + 1); CLCString socket(1024); int itemOrigin[MAX_VARIATION_COUNT] = {0,}; RefMsg(msg) >> takeMoney >> itemCount; if( pc->m_inventory.getEmptyCount() < itemCount ) // 2: 인벤 부족 { { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashTakeErrorMsg( rmsg, charIndex, guildIndex, 2 ); SEND_Q( rmsg , gserver->m_helper ); } { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_TAKE , 2 ); SEND_Q( rmsg, pc->m_desc ); } return; } bool bGiveGuildItem = true; int errorIndex = 0; int now_dur = 0; int max_dur = 0; // Memory 할당후 Delete 하지 않고 Return 되지 않도록 주의 CItem** ppGuildItem = new CItem*[itemCount]; for( int i=0 ; i<itemCount ; ++i ) { RefMsg(msg) >> index >> plus >> flag >> used >> used2 >> now_dur >> max_dur >> count ; for ( int idx = 0 ; idx < MAX_ITEM_OPTION ; ++idx ) RefMsg(msg) >> option[idx]; RefMsg(msg) >> serial >> socket; RefMsg(msg) >> itemOrigin[0] >> itemOrigin[1] >> itemOrigin[2] >> itemOrigin[3] >> itemOrigin[4] >> itemOrigin[5]; ppGuildItem[i] = gserver->m_itemProtoList.CreateDBItem_2( index, -1, plus, flag, used, used2, (const char*) serial, count, option, socket, itemOrigin ); ppGuildItem[i]->setNowDurability(now_dur); ppGuildItem[i]->setMaxDurability(max_dur); // 아이템 생성 확인 및 무개 검사 if( !ppGuildItem[i] ) { // 하나라도 아이템 생성 실패 bGiveGuildItem = false; errorIndex = i; break; } } if( bGiveGuildItem ) // 이정도 검사했는데 다 들어가겠지... { if (takeMoney > 0) { GoldType_t oldNas = pc->m_inventory.getMoney(); pc->m_inventory.increaseMoney(takeMoney); GAMELOG << init("SUCCESS TAKE NAS TO GUILD STASH", pc) << "CHAR INDEX : " << pc->m_index << delim << "BEFORE NAS : " << oldNas << delim << "TAKE NAS : " << takeMoney << delim << "AFTER NAS : " << pc->m_inventory.getMoney() << end; } for( int i = 0 ; i < itemCount ; ++i ) { if (pc->m_inventory.addItem(ppGuildItem[i])) { LogGuildStash(ppGuildItem[i], ppGuildItem[i]->Count(), GUILD_STASH_TAKE_LOG, pc); } } { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashTakeErrorMsg( rmsg, charIndex, guildIndex, 0, takeMoney ); // 0: 정상처리 SEND_Q( rmsg , gserver->m_helper ); } { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_TAKE , 0 ); // 0: 정상처리 SEND_Q( rmsg, pc->m_desc ); } } else // 정리 합시다. { for( int delIdx=0 ; delIdx<errorIndex ; ++delIdx ) delete ppGuildItem[delIdx]; // Create 한 Item 삭제 { CNetMsg::SP rmsg(new CNetMsg); HelperGuildStashTakeErrorMsg( rmsg, charIndex, guildIndex, 3 ); // 3: 지급 실패 ( 무게 초과 ) SEND_Q( rmsg , gserver->m_helper ); } { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_TAKE , 3 ); // 3: 인벤 무게 초과 SEND_Q( rmsg, pc->m_desc ); } } if( ppGuildItem ) delete [] ppGuildItem; return; } void ProcHelperGuildStashLog(CNetMsg::SP& msg) { int charIndex = 0; int guildIndex = 0; int logCount = 0; RefMsg(msg) >> charIndex >> guildIndex >> logCount; // PC 찾고 CPC* pc = PCManager::instance()->getPlayerByCharIndex(charIndex); if( !pc ) return; if( logCount < 1 ) return; { CNetMsg::SP rmsg(new CNetMsg); GuildStashLogMsg( rmsg, logCount ); for( int i=0; i<logCount; ++i ) { int logIndex = 0; CLCString date(32); CLCString nick(45); char cState = -1; int itemIndex = 0; int itemPlus = 0; LONGLONG itemCount = 0; RefMsg(msg) >> logIndex >> date >> nick >> cState >> itemIndex >> itemPlus >> itemCount ; int realPlus = (itemPlus & 0x0000ffff); RefMsg(rmsg) << logIndex << date << nick << cState << itemIndex << realPlus << itemCount; } SEND_Q( rmsg, pc->m_desc ); } } // 길드 창고에 대한 전반적인 알림 에러 처리 void ProcHelperGuildStashError(CNetMsg::SP& msg) { int charIndex = 0; char error = 0; RefMsg(msg) >> charIndex >> error; CPC* pc = PCManager::instance()->getPlayerByCharIndex(charIndex); if( !pc ) return; { CNetMsg::SP rmsg(new CNetMsg); GuildStashErrorMsg( rmsg, MSG_NEW_GUILD_STASH_ERROR, error ); // 핼퍼에서 받은 그대로 보내주자 SEND_Q( rmsg, pc->m_desc ); } } #endif // DEV_GUILD_STASH void ProcHelperStudentListRefresh(CNetMsg::SP& msg) { int teacherIndex; RefMsg(msg) >> teacherIndex; CPC* pc = PCManager::instance()->getPlayerByCharIndex(teacherIndex); if( !pc ) return; { CNetMsg::SP rmsg(new CNetMsg); HelperTeacherStudentListCyncReq(rmsg, pc); SEND_Q(rmsg, gserver->m_helper); } } void ProcHelperTeacherStudentLsitCync(CNetMsg::SP& msg) { CLCString idname(MAX_ID_NAME_LENGTH + 1); int teacherIndex; RefMsg(msg) >> idname >> teacherIndex; CPC * pc = PCManager::instance()->getPlayerByCharIndex( teacherIndex ); if( !pc ) return; char bteacher; RefMsg(msg) >> pc->m_cntTeachingStudent >> pc->m_guardian >> pc->m_superstone >> pc->m_cntFailStudent >> pc->m_cntCompleteStudent >> pc->m_teachType >> pc->m_fame >> bteacher; if( bteacher ) pc->m_bTeacher = true; else pc->m_bTeacher = false; if( pc->m_teachType != MSG_TEACH_TEACHER_TYPE ) return; ProcHelperTeacherInfoSet( pc, msg ); { CNetMsg::SP rmsg(new CNetMsg); TeachInfoMsg(rmsg, pc); SEND_Q(rmsg, pc->m_desc); } } void ProcHelperTeacherInfoSet( CPC * pc, CNetMsg::SP& msg ) { RefMsg(msg) >> pc->m_teachTime[0] >> pc->m_teachTime[1]; CLCString teachName(MAX_CHAR_NAME_LENGTH + 1); for(int i = 0; i < TEACH_MAX_STUDENTS; i++) { RefMsg(msg) >> pc->m_teachIdx[i] >> pc->m_teachJob[i] >> pc->m_teachJob2[i] >> pc->m_teachLevel[i] >> teachName; strcpy(pc->m_teachName[i], teachName); if( pc->m_teachIdx[i] != -1 ) { CPC* student = PCManager::instance()->getPlayerByCharIndex(pc->m_teachIdx[i]); if( student ) { pc->m_teachIdx[i] = student->m_index; pc->m_teachJob[i] = student->m_job; pc->m_teachJob2[i] = student->m_job2; pc->m_teachLevel[i] = student->m_level; strcpy(pc->m_teachName[i], student->GetName()); } } } } //#endif void ProcHelperGuildMasterKickRep(CNetMsg::SP& msg) { int _guildIndex = -1, _requestCharIndex = -1, _result = -1, _requestTime; CLCString _currentBoss(MAX_CHAR_NAME_LENGTH + 1); RefMsg(msg) >> _guildIndex >> _requestCharIndex >> _result >> _requestTime; CPC* _pc = PCManager::instance()->getPlayerByCharIndex(_requestCharIndex); // 결과 처리 CGuild* _guild = gserver->m_guildlist.findguild(_guildIndex); if ( _guild ) { _currentBoss = _guild->boss()->GetName(); if ( _result == 0 ) { // 추방 예약 성공 : 길드원 전체에게 뿌린다 CNetMsg::SP rmsg(new CNetMsg); GuildMasterKickRep(rmsg, _guildIndex, _currentBoss); _guild->SendToAll(rmsg); // 추방 관련 정보 설정 _guild->getGuildKick()->setKickReuestChar(_requestCharIndex); _guild->getGuildKick()->setKickRequestTime(_requestTime); } else if ( _pc ) { // 추방 예약 실패 : 신청자에게만 뿌린다 CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)_result); SEND_Q(rmsg, _pc->m_desc); } } } void ProcHelperGuildMasterKickCancelRep(CNetMsg::SP& msg) { int _guildIndex = -1, _requestCharIndex = -1, _result = -1; RefMsg(msg) >> _guildIndex >> _requestCharIndex >> _result; CPC* _pc = PCManager::instance()->getPlayerByCharIndex(_requestCharIndex); // 결과 처리 CGuild* _guild = gserver->m_guildlist.findguild(_guildIndex); if ( _guild ) { if ( _result == 0 ) { // 추방 취소 성공 : 길드원 전체에 뿌린다 CNetMsg::SP rmsg(new CNetMsg); GuildMasterKickCancelRep(rmsg, _guildIndex); _guild->SendToAll(rmsg); // 추방 관련 정보 설정 _guild->getGuildKick()->setKickReuestChar(_requestCharIndex); } else if ( _pc ) { // 추방 취소 실패 : 신청자에게만 뿌린다 CNetMsg::SP rmsg(new CNetMsg); GuildErrorMsg(rmsg, (MSG_GUILD_ERROR_TYPE)_result); SEND_Q(rmsg, _pc->m_desc); } } } void ProcHelperGuildMasterKickStatus(CNetMsg::SP& msg) { int _guildIndex = -1, _status = -1; RefMsg(msg) >> _guildIndex >> _status; CGuild* _guild = gserver->m_guildlist.findguild(_guildIndex); if ( _guild ) { _guild->getGuildKick()->setKickStatus(_status); CNetMsg::SP rmsg(new CNetMsg); GuildMasterKickStatus(rmsg, _guildIndex, _status); _guild->SendToAll(rmsg); } } void ProcHelperGuildMasaterKickReset(CNetMsg::SP& msg) { int charIndex = -1, reset = -1; RefMsg(msg) >> charIndex >> reset; CPC* ch = PCManager::instance()->getPlayerByCharIndex(charIndex); if ( ch == NULL ) return; CLCString message(128); if ( reset ) message = "Reset Complete"; else message = "Reset Fail, Try again"; { CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", message); SEND_Q(rmsg, ch->m_desc); } } //RVR void ProcHelperRVRInfoUpdate(CNetMsg::SP& msg) { UpdateServer::SyndicateInfo* p = reinterpret_cast<UpdateServer::SyndicateInfo*>(msg->m_buf); SyndicateInfoDataManager::instance()->setJewelPoint(SYNDICATE::eSYNDICATE_KAILUX, p->jewelCount_k); SyndicateInfoDataManager::instance()->setJewelPoint(SYNDICATE::eSYNDICATE_DEALERMOON, p->jewelCount_d); SyndicateInfoDataManager::instance()->setJoinCount(SYNDICATE::eSYNDICATE_KAILUX, p->userCount_k); SyndicateInfoDataManager::instance()->setJoinCount(SYNDICATE::eSYNDICATE_DEALERMOON, p->userCount_d); } void ProcHelperRvRUpdateKingInfo( CNetMsg::SP& msg ) { UpdateServer::SyndicateUpdateKingInfoAll* p = reinterpret_cast<UpdateServer::SyndicateUpdateKingInfoAll*>(msg->m_buf); //왕이 바뀐 경우 if(p->kingIndex_d != SyndicateInfoDataManager::instance()->getKingIndex(SYNDICATE::eSYNDICATE_DEALERMOON)) { CPC* pChar = PCManager::instance()->getPlayerByCharIndex(p->kingIndex_d); if (pChar != NULL) { pChar->m_syndicateManager.setSyndicateGrade(SYNDICATE::eSYNDICATE_DEALERMOON, SYNDICATE::IPSISSIMUS); pChar->m_syndicateManager.historyManager_.promotionHistory(SYNDICATE::eSYNDICATE_DEALERMOON, SYNDICATE::IPSISSIMUS); pChar->m_syndicateManager.historyManager_.sendHistory(SYNDICATE::eSYNDICATE_DEALERMOON); pChar->m_syndicateManager.send(); pChar->m_syndicateManager.applySyndicateSkill(SYNDICATE::eSYNDICATE_DEALERMOON); } } SyndicateInfoDataManager::instance()->setKingName(SYNDICATE::eSYNDICATE_DEALERMOON, p->kingName_d); SyndicateInfoDataManager::instance()->setKingPoint(SYNDICATE::eSYNDICATE_DEALERMOON, p->kingPoint_d); SyndicateInfoDataManager::instance()->setKingIndex(SYNDICATE::eSYNDICATE_DEALERMOON, p->kingIndex_d); //왕이 바뀐 경우 if(p->kingIndex_k != SyndicateInfoDataManager::instance()->getKingIndex(SYNDICATE::eSYNDICATE_KAILUX)) { CPC* pChar = PCManager::instance()->getPlayerByCharIndex(p->kingIndex_k); if(pChar != NULL) { pChar->m_syndicateManager.syndicateData_.syndicate_grade_k = SYNDICATE::PRINCIPE; pChar->m_syndicateManager.historyManager_.promotionHistory(SYNDICATE::eSYNDICATE_KAILUX, SYNDICATE::PRINCIPE); pChar->m_syndicateManager.historyManager_.sendHistory(SYNDICATE::eSYNDICATE_KAILUX); pChar->m_syndicateManager.send(); pChar->m_syndicateManager.applySyndicateSkill(SYNDICATE::eSYNDICATE_KAILUX); } } SyndicateInfoDataManager::instance()->setKingName(SYNDICATE::eSYNDICATE_KAILUX, p->kingName_k); SyndicateInfoDataManager::instance()->setKingPoint(SYNDICATE::eSYNDICATE_KAILUX, p->kingPoint_k); SyndicateInfoDataManager::instance()->setKingIndex(SYNDICATE::eSYNDICATE_KAILUX, p->kingIndex_k); } void ProcHelperRvRKingDownGrade( CNetMsg::SP& msg ) { UpdateServer::SyndicateKingDownGrade* p = reinterpret_cast<UpdateServer::SyndicateKingDownGrade*>(msg->m_buf); CPC* pChar = PCManager::instance()->getPlayerByCharIndex(p->charIndex); int downgrade; if(pChar != NULL) { downgrade = SYNDICATE::getSyndicateGrade(p->syndicateType, pChar->m_syndicateManager.getSyndicatePoint(p->syndicateType)); pChar->m_syndicateManager.setSyndicateGrade(p->syndicateType, downgrade); pChar->m_syndicateManager.historyManager_.degradeHistory(p->syndicateType, downgrade); pChar->m_syndicateManager.historyManager_.sendHistory(p->syndicateType); pChar->m_syndicateManager.send(); pChar->m_syndicateManager.applySyndicateSkill(p->syndicateType); } else { if(p->syndicateType == SYNDICATE::eSYNDICATE_KAILUX) downgrade = SYNDICATE::DUKA; else if(p->syndicateType == SYNDICATE::eSYNDICATE_DEALERMOON) downgrade = SYNDICATE::MAGUS; //접속해 있지 않은 경우에는 쿼리문 저장 std::string insertStr = "INSERT INTO t_syndicate_history VALUES"; insertStr.reserve(1024); insertStr += boost::str( boost::format("(%1%, %2%, %3%, %4%, %5%, '', now())") % SyndicateInfoDataManager::instance()->getKingIndex(p->syndicateType) % p->syndicateType % SYNDICATE::DEGRADE % downgrade % SYNDICATE::eSYNDICATE_NONE ); DBManager::instance()->pushQuery(0, insertStr); } } //RVR void ProcHelperKickUser(CNetMsg::SP& msg) { ServerToServerPacket::kickUser* packet = reinterpret_cast<ServerToServerPacket::kickUser*>(msg->m_buf); CPC* kickedch = PCManager::instance()->getPlayerByName(packet->kicked_charName, true); if (kickedch == NULL) { packet->subType = MSG_SUB_SERVERTOSERVER_KICK_ANSER; packet->result = false; SEND_Q(msg, gserver->m_helper); return; } LOG_INFO("KICK : kicked by %d", packet->req_charIndex); kickedch->m_desc->Close("kicked"); { packet->subType = MSG_SUB_SERVERTOSERVER_KICK_ANSER; packet->result = true; SEND_Q(msg, gserver->m_helper); } } void ProcHelperKickUserAnswer(CNetMsg::SP& msg) { ServerToServerPacket::kickUser* packet = reinterpret_cast<ServerToServerPacket::kickUser*>(msg->m_buf); std::string kickName = packet->kicked_charName; CPC* reqUser = PCManager::instance()->getPlayerByCharIndex(packet->req_charIndex); if (reqUser == NULL) { // 요청자(주로 GM)가 logout한 경우 return; } std::string tstr = ""; if (packet->result) { tstr = boost::str(boost::format( "KICK : User(%s) was kicked") % kickName); } else { tstr = boost::str(boost::format( "KICK : Not found User(%s)") % kickName); } { CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", tstr.c_str()); SEND_Q(rmsg, reqUser->m_desc); } } void ProcHelperKickUserByCharIndexAnswer(CNetMsg::SP& msg) { ServerToServerPacket::kickUserByCharIndex* packet = reinterpret_cast<ServerToServerPacket::kickUserByCharIndex*>(msg->m_buf); CPC* reqUser = PCManager::instance()->getPlayerByCharIndex(packet->req_charIndex); if (reqUser == NULL) { // 요청자(주로 GM)가 logout한 경우 return; } std::string tstr = ""; if (packet->result) { tstr = boost::str(boost::format( "KICK : User(charIndex: %d) was kicked") % packet->kicked_charIndex); } else { tstr = boost::str(boost::format( "KICK : Not found User(charIndex : %d)") % packet->kicked_charIndex); } { CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", tstr.c_str()); SEND_Q(rmsg, reqUser->m_desc); } } void ProcHelperKickUserByUserIndexAnswer(CNetMsg::SP& msg) { ServerToServerPacket::kickUserByUserIndex* packet = reinterpret_cast<ServerToServerPacket::kickUserByUserIndex*>(msg->m_buf); CPC* reqUser = PCManager::instance()->getPlayerByCharIndex(packet->req_charIndex); if (reqUser == NULL) { // 요청자(주로 GM)가 logout한 경우 return; } std::string tstr = ""; if (packet->result) { tstr = boost::str(boost::format( "KICK : User(userIndex : %d) was kicked") % packet->kicked_userIndex); } else { tstr = boost::str(boost::format( "KICK : Not found User(userIndex : %d)") % packet->kicked_userIndex); } { CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", tstr.c_str()); SEND_Q(rmsg, reqUser->m_desc); } } void ProcHelperKickUserByUserIdAnswer(CNetMsg::SP& msg) { ServerToServerPacket::kickUserByUserId* packet = reinterpret_cast<ServerToServerPacket::kickUserByUserId*>(msg->m_buf); CPC* reqUser = PCManager::instance()->getPlayerByCharIndex(packet->req_charIndex); std::string kickName = packet->kicked_userId; if (reqUser == NULL) { // 요청자(주로 GM)가 logout한 경우 return; } std::string tstr = ""; if (packet->result) { tstr = boost::str(boost::format( "KICK : User(userId : %s) was kicked") % kickName); } else { tstr = boost::str(boost::format( "KICK : Not found User(userId : %s)") % kickName); } { CNetMsg::SP rmsg(new CNetMsg); SayMsg(rmsg, MSG_CHAT_NOTICE, 0, "", "", tstr.c_str()); SEND_Q(rmsg, reqUser->m_desc); } } void ProcHelperGuildBattleReg(CNetMsg::SP& msg) { ServerToServerPacket::GuildBattleRegToHelper* packet = reinterpret_cast<ServerToServerPacket::GuildBattleRegToHelper*>(msg->m_buf); CGuild* guild = gserver->m_guildlist.findguild(packet->guild_index); CPC* pc = PCManager::instance()->getPlayerByCharIndex(packet->char_index); if(pc == NULL || guild == NULL) { if(guild != NULL) guild->m_isUseTheStashAndSkill = true; CNetMsg::SP rmsg(new CNetMsg); ServerToServerPacket::makeGuildBattleStashLockOff(rmsg, packet->guild_index); SEND_Q(rmsg, gserver->m_helper); return; } CNetMsg::SP rmsg(new CNetMsg); makeGuildBattleErrorMsg(rmsg, packet->error_code); SEND_Q(rmsg, pc->m_desc); if(packet->error_code == GUILD_BATTLE_SUCCESS_REGIST) { GuildBattleManager::instance()->regist(guild, packet->stake_nas, packet->stake_gp, packet->guild_battle_time, packet->ave_level, packet->zone_index); } guild->m_isUseTheStashAndSkill = false; } void ProcHelperGuildBattleChallenge(CNetMsg::SP& msg) { ServerToServerPacket::GuildBattleChallengeToHelper* packet = reinterpret_cast<ServerToServerPacket::GuildBattleChallengeToHelper*>(msg->m_buf); CPC* pc = PCManager::instance()->getPlayerByCharIndex(packet->char_index); CGuild* guild = gserver->m_guildlist.findguild(packet->guild_index); if(pc == NULL || guild == NULL) { if(guild != NULL) guild->m_isUseTheStashAndSkill = true; CNetMsg::SP rmsg(new CNetMsg); ServerToServerPacket::makeGuildBattleStashLockOff(rmsg, packet->guild_index); SEND_Q(rmsg, gserver->m_helper); return; } CPC* target = PCManager::instance()->getPlayerByCharIndex(packet->target_char_index); CGuild* target_guild = gserver->m_guildlist.findguild(packet->target_guild_index); if(target == NULL || target_guild == NULL) { guild->m_isUseTheStashAndSkill = true; CNetMsg::SP rmsg(new CNetMsg); ServerToServerPacket::makeGuildBattleStashLockOff(rmsg, packet->guild_index); SEND_Q(rmsg, gserver->m_helper); return; } if(packet->error_code == GUILD_BATTLE_SUCCESS_CHALLENGE) { st_multi_index* data = GuildBattleManager::instance()->find(packet->target_guild_index); //신청 성공 패킷 전달 { CNetMsg::SP rmsg(new CNetMsg); MakeGuildBattleChallengeMsg(rmsg, data->guild->name(), packet->error_code); SEND_Q(rmsg, pc->m_desc); } pc->m_guildInfo->guild()->m_isUseTheStashAndSkill = false; { //타겟 길드 마스터에게 패킷 전달 CNetMsg::SP rmsg(new CNetMsg); makeGuildBattleChallengeAgreeMsgUpdate(rmsg, target_guild->level(), target_guild->membercount(), data->ave_level, target_guild->m_battle_win_count, target_guild->m_battle_total_count, data->stake_nas, data->stake_gp, pc->m_index, target_guild->name()); SEND_Q(rmsg, target->m_desc); } } else { CNetMsg::SP rmsg(new CNetMsg); makeGuildBattleErrorMsg(rmsg, packet->error_code); SEND_Q(rmsg, pc->m_desc); } }
24.588849
255
0.67614
[ "vector" ]
3a1008c21a8158bcf9d4d1b55759dca4319ba176
3,330
hpp
C++
src/lib/matrix/matrix/Slice.hpp
ximiheheda/acrobatic_firm_new
fc823f4c53cbe969b9b278aff9671385ba19b18f
[ "BSD-3-Clause" ]
null
null
null
src/lib/matrix/matrix/Slice.hpp
ximiheheda/acrobatic_firm_new
fc823f4c53cbe969b9b278aff9671385ba19b18f
[ "BSD-3-Clause" ]
null
null
null
src/lib/matrix/matrix/Slice.hpp
ximiheheda/acrobatic_firm_new
fc823f4c53cbe969b9b278aff9671385ba19b18f
[ "BSD-3-Clause" ]
1
2020-02-17T09:25:07.000Z
2020-02-17T09:25:07.000Z
/** * @file Slice.hpp * * A simple matrix template library. * * @author Julian Kent < julian@auterion.com > */ #pragma once #include "math.hpp" namespace matrix { template<typename Type, size_t M, size_t N> class Matrix; template<typename Type, size_t M> class Vector; template <typename Type, size_t P, size_t Q, size_t M, size_t N> class Slice { public: Slice(size_t x0, size_t y0, const Matrix<Type, M, N>* data) : _x0(x0), _y0(y0), _data(const_cast<Matrix<Type, M, N>*>(data)) { static_assert(P <= M, "Slice rows bigger than backing matrix"); static_assert(Q <= N, "Slice cols bigger than backing matrix"); } Type operator()(size_t i, size_t j) const { return (*_data)(_x0 + i, _y0 + j); } Type &operator()(size_t i, size_t j) { return (*_data)(_x0 + i, _y0 + j); } template<size_t MM, size_t NN> Slice<Type, P, Q, M, N>& operator=(const Slice<Type, P, Q, MM, NN>& other) { Slice<Type, P, Q, M, N>& self = *this; for (size_t i = 0; i < P; i++) { for (size_t j = 0; j < Q; j++) { self(i, j) = other(i, j); } } return self; } Slice<Type, P, Q, M, N>& operator=(const Matrix<Type, P, Q>& other) { Slice<Type, P, Q, M, N>& self = *this; for (size_t i = 0; i < P; i++) { for (size_t j = 0; j < Q; j++) { self(i, j) = other(i, j); } } return self; } // allow assigning vectors to a slice that are in the axis template <size_t DUMMY = 1> // make this a template function since it only exists for some instantiations Slice<Type, 1, Q, M, N>& operator=(const Vector<Type, Q>& other) { Slice<Type, 1, Q, M, N>& self = *this; for (size_t j = 0; j < Q; j++) { self(0, j) = other(j); } return self; } template<size_t R, size_t S> const Slice<Type, R, S, M, N> slice(size_t x0, size_t y0) const { return Slice<Type, R, S, M, N>(x0 + _x0, y0 + _y0, _data); } template<size_t R, size_t S> Slice<Type, R, S, M, N> slice(size_t x0, size_t y0) { return Slice<Type, R, S, M, N>(x0 + _x0, y0 + _y0, _data); } void copyTo(Type dst[M*N]) const { const Slice<Type, P, Q, M, N> &self = *this; for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < N; j++) { dst[i*N+j] = self(i, j); } } } void copyToColumnMajor(Type dst[M*N]) const { const Slice<Type, P, Q, M, N> &self = *this; for (size_t i = 0; i < M; i++) { for (size_t j = 0; j < N; j++) { dst[i+(j*M)] = self(i, j); } } } Type norm_squared() { Slice<Type, P, Q, M, N>& self = *this; Type accum(0); for (size_t i = 0; i < P; i++) { for (size_t j = 0; j < Q; j++) { accum += self(i, j)*self(i, j); } } return accum; } Type norm() { return matrix::sqrt(norm_squared()); } bool longerThan(Type testVal) { return norm_squared() > testVal*testVal; } private: size_t _x0, _y0; Matrix<Type,M,N>* _data; }; }
23.956835
109
0.488889
[ "vector" ]
3a1295c38d04abc897fa4bf5dac0081fdb345d87
2,733
cc
C++
src/vnsw/agent/controller/controller_sandesh.cc
madkiss/contrail-controller
17f622dfe99f8ab4163436399e80f95dd564814c
[ "Apache-2.0" ]
null
null
null
src/vnsw/agent/controller/controller_sandesh.cc
madkiss/contrail-controller
17f622dfe99f8ab4163436399e80f95dd564814c
[ "Apache-2.0" ]
null
null
null
src/vnsw/agent/controller/controller_sandesh.cc
madkiss/contrail-controller
17f622dfe99f8ab4163436399e80f95dd564814c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include <cmn/agent_cmn.h> #include <cmn/agent_db.h> #include <controller/controller_sandesh.h> #include <controller/controller_types.h> #include <controller/controller_peer.h> #include <init/agent_param.h> const char *ControllerSandesh::kAuthTypeNil = "NIL"; const char *ControllerSandesh::kAuthTypeTls = "TLS"; void AgentXmppConnectionStatusReq::HandleRequest() const { uint8_t count = 0; AgentXmppConnectionStatus *resp = new AgentXmppConnectionStatus(); while (count < MAX_XMPP_SERVERS) { if (!Agent::GetInstance()->controller_ifmap_xmpp_server(count).empty()) { AgentXmppData data; data.set_controller_ip(Agent::GetInstance()->controller_ifmap_xmpp_server(count)); AgentXmppChannel *ch = Agent::GetInstance()->controller_xmpp_channel(count); if (ch) { XmppChannel *xc = ch->GetXmppChannel(); if (xc->GetPeerState() == xmps::READY) { data.set_state("Established"); } else { data.set_state("Down"); } if (Agent::GetInstance()->mulitcast_builder() == ch) { data.set_mcast_controller("Yes"); } else { data.set_mcast_controller("No"); } if (Agent::GetInstance()->ifmap_active_xmpp_server().compare(Agent::GetInstance()->controller_ifmap_xmpp_server(count)) == 0) { data.set_cfg_controller("Yes"); } else { data.set_cfg_controller("No"); } if (Agent::GetInstance()->params()->xmpp_auth_enabled()) { data.set_xmpp_auth_enabled(ControllerSandesh::kAuthTypeTls); } else { data.set_xmpp_auth_enabled(ControllerSandesh::kAuthTypeNil); } data.set_last_state(xc->LastStateName()); data.set_last_event(xc->LastEvent()); data.set_last_state_at(xc->LastStateChangeAt()); data.set_flap_count(xc->FlapCount()); data.set_flap_time(xc->LastFlap()); ControllerProtoStats rx_proto_stats; rx_proto_stats.open = xc->rx_open(); rx_proto_stats.keepalive = xc->rx_keepalive(); rx_proto_stats.update = xc->rx_update(); rx_proto_stats.close = xc->rx_close(); ControllerProtoStats tx_proto_stats; tx_proto_stats.open = xc->tx_open(); tx_proto_stats.keepalive = xc->tx_keepalive(); tx_proto_stats.update = xc->tx_update(); tx_proto_stats.close = xc->tx_close(); data.set_rx_proto_stats(rx_proto_stats); data.set_tx_proto_stats(tx_proto_stats); } std::vector<AgentXmppData> &list = const_cast<std::vector<AgentXmppData>&>(resp->get_peer()); list.push_back(data); } count++; } resp->set_context(context()); resp->set_more(false); resp->Response(); }
33.329268
129
0.672521
[ "vector" ]
3a13987efcdf0bfd95688063663b2914715ac653
4,546
cpp
C++
examples/benchmark/bm_nanoflann.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
23
2020-07-19T23:03:01.000Z
2022-03-07T15:06:26.000Z
examples/benchmark/bm_nanoflann.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
1
2021-01-26T16:53:16.000Z
2021-01-26T23:20:54.000Z
examples/benchmark/bm_nanoflann.cpp
Jaybro/pico_tree
c6f7fb798b60452add7d0e940c4a7737cd72a992
[ "MIT" ]
4
2021-03-04T14:03:28.000Z
2021-05-27T05:36:40.000Z
#include "benchmark.hpp" #include "nano_adaptor.hpp" class BmNanoflann : public pico_tree::Benchmark { public: using NanoAdaptorX = NanoAdaptor<Index, PointX>; }; template <typename NanoAdaptor> using NanoKdTreeCt = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor<typename NanoAdaptor::ScalarType, NanoAdaptor>, NanoAdaptor, NanoAdaptor::Dim, typename NanoAdaptor::IndexType>; template <typename NanoAdaptor> using NanoKdTreeRt = nanoflann::KDTreeSingleIndexAdaptor< nanoflann::L2_Simple_Adaptor<typename NanoAdaptor::ScalarType, NanoAdaptor>, NanoAdaptor, -1, typename NanoAdaptor::IndexType>; // **************************************************************************** // Building the tree // **************************************************************************** BENCHMARK_DEFINE_F(BmNanoflann, BuildCt)(benchmark::State& state) { int max_leaf_size = state.range(0); NanoAdaptorX adaptor(points_tree_); for (auto _ : state) { NanoKdTreeCt<NanoAdaptorX> tree( PointX::Dim, adaptor, nanoflann::KDTreeSingleIndexAdaptorParams(max_leaf_size)); tree.buildIndex(); } } BENCHMARK_DEFINE_F(BmNanoflann, BuildRt)(benchmark::State& state) { int max_leaf_size = state.range(0); NanoAdaptorX adaptor(points_tree_); for (auto _ : state) { NanoKdTreeRt<NanoAdaptorX> tree( PointX::Dim, adaptor, nanoflann::KDTreeSingleIndexAdaptorParams(max_leaf_size)); tree.buildIndex(); } } // Argument 1: Maximum leaf size. BENCHMARK_REGISTER_F(BmNanoflann, BuildCt) ->Unit(benchmark::kMillisecond) ->Arg(1) ->DenseRange(6, 14, 2); BENCHMARK_REGISTER_F(BmNanoflann, BuildRt) ->Unit(benchmark::kMillisecond) ->Arg(1) ->DenseRange(6, 14, 2); // **************************************************************************** // Knn // **************************************************************************** BENCHMARK_DEFINE_F(BmNanoflann, KnnCt)(benchmark::State& state) { int max_leaf_size = state.range(0); int knn_count = state.range(1); NanoAdaptorX adaptor(points_tree_); NanoKdTreeCt<NanoAdaptorX> tree( PointX::Dim, adaptor, nanoflann::KDTreeSingleIndexAdaptorParams(max_leaf_size)); tree.buildIndex(); for (auto _ : state) { std::vector<Index> indices(knn_count); std::vector<Scalar> distances(knn_count); std::size_t sum = 0; for (auto const& p : points_test_) { benchmark::DoNotOptimize( sum += tree.knnSearch(p.data, knn_count, indices.data(), distances.data())); } } } // Argument 1: Maximum leaf size. // Argument 2: K nearest neighbors. BENCHMARK_REGISTER_F(BmNanoflann, KnnCt) ->Unit(benchmark::kMillisecond) ->Args({1, 1}) ->Args({6, 1}) ->Args({8, 1}) ->Args({10, 1}) ->Args({12, 1}) ->Args({14, 1}) ->Args({1, 4}) ->Args({6, 4}) ->Args({8, 4}) ->Args({10, 4}) ->Args({12, 4}) ->Args({14, 4}) ->Args({1, 8}) ->Args({6, 8}) ->Args({8, 8}) ->Args({10, 8}) ->Args({12, 8}) ->Args({14, 8}) ->Args({1, 12}) ->Args({6, 12}) ->Args({8, 12}) ->Args({10, 12}) ->Args({12, 12}) ->Args({14, 12}); // **************************************************************************** // Radius // **************************************************************************** BENCHMARK_DEFINE_F(BmNanoflann, RadiusCt)(benchmark::State& state) { int max_leaf_size = state.range(0); Scalar radius = static_cast<Scalar>(state.range(1)) / Scalar(10.0); Scalar squared = radius * radius; NanoAdaptorX adaptor(points_tree_); NanoKdTreeCt<NanoAdaptorX> tree( PointX::Dim, adaptor, nanoflann::KDTreeSingleIndexAdaptorParams(max_leaf_size)); tree.buildIndex(); for (auto _ : state) { std::vector<std::pair<Index, Scalar>> results; std::size_t sum = 0; for (auto const& p : points_test_) { benchmark::DoNotOptimize( sum += tree.radiusSearch( p.data, squared, results, nanoflann::SearchParams{0, 0, false})); } } } // Argument 1: Maximum leaf size. // Argument 2: Search radius (divided by 10.0). BENCHMARK_REGISTER_F(BmNanoflann, RadiusCt) ->Unit(benchmark::kMillisecond) ->Args({1, 15}) ->Args({6, 15}) ->Args({8, 15}) ->Args({10, 15}) ->Args({12, 15}) ->Args({14, 15}) ->Args({1, 30}) ->Args({6, 30}) ->Args({8, 30}) ->Args({10, 30}) ->Args({12, 30}) ->Args({14, 30}); BENCHMARK_MAIN();
28.236025
80
0.569732
[ "vector" ]
3a1403d791f4514fc2d5f4ce8b319c28f75ece3a
1,222
cpp
C++
src/Explosion.cpp
laferenorg/CppGame
622f1fa70005877a4c0a206f6d0c3c70bfdd3125
[ "MIT" ]
1
2021-06-17T11:48:46.000Z
2021-06-17T11:48:46.000Z
src/Explosion.cpp
laferenorg/CppGame
622f1fa70005877a4c0a206f6d0c3c70bfdd3125
[ "MIT" ]
null
null
null
src/Explosion.cpp
laferenorg/CppGame
622f1fa70005877a4c0a206f6d0c3c70bfdd3125
[ "MIT" ]
null
null
null
/* C++ */ #include <iostream> #include <string> #include <cstring> #include <vector> /* SDL2 */ #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> /* Header */ #include <header/Load.hpp> #include <header/Settings.hpp> #include <header/Explosion.hpp> Explosion::Explosion(int x, int y, float scale, SDL_Renderer* renderer) { /* Intialize variable */ DestR.x = x; DestR.y = y; for(int i = 1; i < 6; i++) { std::string path = "assets/img/explosion/exp" + std::to_string(i) + ".png"; images.push_back(Load::LoadTexture(path, renderer)); DestR.w = Load::get_width(path) * scale; DestR.h = Load::get_height(path) * scale; } image = images[frame_index]; } void Explosion::update(bool& replace) { unsigned int EXPLOSION_SPEED = 4; /* Update explosion animation */ counter += 1; if(counter >= EXPLOSION_SPEED) { counter = 0; frame_index += 1; /* If the animation is complete then delete the explosion */ if(frame_index >= ((int)images.size())) { delts = true; replace = true; } else { image = images[frame_index]; } } } void Explosion::draw(SDL_Renderer* renderer) { SDL_RenderCopy(renderer, image, NULL, &DestR); }
24.938776
77
0.625205
[ "vector" ]
3a141ec2906170daa26361a97bd50702a17d224c
17,235
cpp
C++
src/stream/MarketDefinition.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
5
2019-06-30T06:29:46.000Z
2021-12-17T12:41:23.000Z
src/stream/MarketDefinition.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
2
2018-01-09T17:14:45.000Z
2020-03-23T00:16:50.000Z
src/stream/MarketDefinition.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
7
2015-09-13T18:40:58.000Z
2020-01-24T10:57:56.000Z
/** * Copyright 2017 Colin Doig. Distributed under the MIT license. */ #include "greentop/stream/MarketDefinition.h" namespace greentop { namespace stream { MarketDefinition::MarketDefinition(const std::string& venue, const std::string& raceType, const std::string& settledTime, const std::string& timezone, const Optional<double>& eachWayDivisor, const std::set<std::string>& regulators, const std::string& marketType, const Optional<double>& marketBaseRate, const Optional<int32_t>& numberOfWinners, const std::string& countryCode, const Optional<double>& lineMaxUnit, const Optional<bool>& inPlay, const Optional<int32_t>& betDelay, const Optional<bool>& bspMarket, const std::string& bettingType, const Optional<int32_t>& numberOfActiveRunners, const Optional<double>& lineMinUnit, const std::string& eventId, const Optional<bool>& crossMatching, const Optional<bool>& runnersVoidable, const Optional<bool>& turnInPlayEnabled, const PriceLadderDefinition& priceLadderDefinition, const KeyLineDefinition& keyLineDefinition, const std::string& suspendTime, const Optional<bool>& discountAllowed, const Optional<bool>& persistenceEnabled, const std::vector<RunnerDefinition>& runners, const Optional<int64_t>& version, const std::string& eventTypeId, const Optional<bool>& complete, const std::string& openDate, const std::string& marketTime, const Optional<bool>& bspReconciled, const Optional<double>& lineInterval, const std::string& status) : venue(venue), raceType(raceType), settledTime(settledTime), timezone(timezone), eachWayDivisor(eachWayDivisor), regulators(regulators), marketType(marketType), marketBaseRate(marketBaseRate), numberOfWinners(numberOfWinners), countryCode(countryCode), lineMaxUnit(lineMaxUnit), inPlay(inPlay), betDelay(betDelay), bspMarket(bspMarket), bettingType(bettingType), numberOfActiveRunners(numberOfActiveRunners), lineMinUnit(lineMinUnit), eventId(eventId), crossMatching(crossMatching), runnersVoidable(runnersVoidable), turnInPlayEnabled(turnInPlayEnabled), priceLadderDefinition(priceLadderDefinition), keyLineDefinition(keyLineDefinition), suspendTime(suspendTime), discountAllowed(discountAllowed), persistenceEnabled(persistenceEnabled), runners(runners), version(version), eventTypeId(eventTypeId), complete(complete), openDate(openDate), marketTime(marketTime), bspReconciled(bspReconciled), lineInterval(lineInterval), status(status) { } void MarketDefinition::fromJson(const Json::Value& json) { if (json.isMember("venue")) { venue = json["venue"].asString(); } if (json.isMember("raceType")) { raceType = json["raceType"].asString(); } if (json.isMember("settledTime")) { settledTime = json["settledTime"].asString(); } if (json.isMember("timezone")) { timezone = json["timezone"].asString(); } if (json.isMember("eachWayDivisor")) { eachWayDivisor = json["eachWayDivisor"].asDouble(); } if (json.isMember("regulators")) { for (unsigned i = 0; i < json["regulators"].size(); ++i) { regulators.insert(json["regulators"][i].asString()); } } if (json.isMember("marketType")) { marketType = json["marketType"].asString(); } if (json.isMember("marketBaseRate")) { marketBaseRate = json["marketBaseRate"].asDouble(); } if (json.isMember("numberOfWinners")) { numberOfWinners = json["numberOfWinners"].asInt(); } if (json.isMember("countryCode")) { countryCode = json["countryCode"].asString(); } if (json.isMember("lineMaxUnit")) { lineMaxUnit = json["lineMaxUnit"].asDouble(); } if (json.isMember("inPlay")) { inPlay = json["inPlay"].asBool(); } if (json.isMember("betDelay")) { betDelay = json["betDelay"].asInt(); } if (json.isMember("bspMarket")) { bspMarket = json["bspMarket"].asBool(); } if (json.isMember("bettingType")) { bettingType = json["bettingType"].asString(); } if (json.isMember("numberOfActiveRunners")) { numberOfActiveRunners = json["numberOfActiveRunners"].asInt(); } if (json.isMember("lineMinUnit")) { lineMinUnit = json["lineMinUnit"].asDouble(); } if (json.isMember("eventId")) { eventId = json["eventId"].asString(); } if (json.isMember("crossMatching")) { crossMatching = json["crossMatching"].asBool(); } if (json.isMember("runnersVoidable")) { runnersVoidable = json["runnersVoidable"].asBool(); } if (json.isMember("turnInPlayEnabled")) { turnInPlayEnabled = json["turnInPlayEnabled"].asBool(); } if (json.isMember("priceLadderDefinition")) { priceLadderDefinition.fromJson(json["priceLadderDefinition"]); } if (json.isMember("keyLineDefinition")) { keyLineDefinition.fromJson(json["keyLineDefinition"]); } if (json.isMember("suspendTime")) { suspendTime = json["suspendTime"].asString(); } if (json.isMember("discountAllowed")) { discountAllowed = json["discountAllowed"].asBool(); } if (json.isMember("persistenceEnabled")) { persistenceEnabled = json["persistenceEnabled"].asBool(); } if (json.isMember("runners")) { for (unsigned i = 0; i < json["runners"].size(); ++i) { RunnerDefinition runner; runner.fromJson(json["runners"][i]); runners.push_back(runner); } } if (json.isMember("version")) { version = json["version"].asInt64(); } if (json.isMember("eventTypeId")) { eventTypeId = json["eventTypeId"].asString(); } if (json.isMember("complete")) { complete = json["complete"].asBool(); } if (json.isMember("openDate")) { openDate = json["openDate"].asString(); } if (json.isMember("marketTime")) { marketTime = json["marketTime"].asString(); } if (json.isMember("bspReconciled")) { bspReconciled = json["bspReconciled"].asBool(); } if (json.isMember("lineInterval")) { lineInterval = json["lineInterval"].asDouble(); } if (json.isMember("status")) { status = json["status"].asString(); } } Json::Value MarketDefinition::toJson() const { Json::Value json(Json::objectValue); if (venue != "") { json["venue"] = venue; } if (raceType != "") { json["raceType"] = raceType; } if (settledTime != "") { json["settledTime"] = settledTime; } if (timezone != "") { json["timezone"] = timezone; } if (eachWayDivisor.isValid()) { json["eachWayDivisor"] = eachWayDivisor.toJson(); } if (regulators.size() > 0) { for (std::set<std::string>::const_iterator it = regulators.begin(); it != regulators.end(); ++it) { json["regulators"].append(*it); } } if (marketType != "") { json["marketType"] = marketType; } if (marketBaseRate.isValid()) { json["marketBaseRate"] = marketBaseRate.toJson(); } if (numberOfWinners.isValid()) { json["numberOfWinners"] = numberOfWinners.toJson(); } if (countryCode != "") { json["countryCode"] = countryCode; } if (lineMaxUnit.isValid()) { json["lineMaxUnit"] = lineMaxUnit.toJson(); } if (inPlay.isValid()) { json["inPlay"] = inPlay.toJson(); } if (betDelay.isValid()) { json["betDelay"] = betDelay.toJson(); } if (bspMarket.isValid()) { json["bspMarket"] = bspMarket.toJson(); } if (bettingType != "") { json["bettingType"] = bettingType; } if (numberOfActiveRunners.isValid()) { json["numberOfActiveRunners"] = numberOfActiveRunners.toJson(); } if (lineMinUnit.isValid()) { json["lineMinUnit"] = lineMinUnit.toJson(); } if (eventId != "") { json["eventId"] = eventId; } if (crossMatching.isValid()) { json["crossMatching"] = crossMatching.toJson(); } if (runnersVoidable.isValid()) { json["runnersVoidable"] = runnersVoidable.toJson(); } if (turnInPlayEnabled.isValid()) { json["turnInPlayEnabled"] = turnInPlayEnabled.toJson(); } if (priceLadderDefinition.isValid()) { json["priceLadderDefinition"] = priceLadderDefinition.toJson(); } if (keyLineDefinition.isValid()) { json["keyLineDefinition"] = keyLineDefinition.toJson(); } if (suspendTime != "") { json["suspendTime"] = suspendTime; } if (discountAllowed.isValid()) { json["discountAllowed"] = discountAllowed.toJson(); } if (persistenceEnabled.isValid()) { json["persistenceEnabled"] = persistenceEnabled.toJson(); } if (runners.size() > 0) { for (unsigned i = 0; i < runners.size(); ++i) { json["runners"].append(runners[i].toJson()); } } if (version.isValid()) { json["version"] = version.toJson(); } if (eventTypeId != "") { json["eventTypeId"] = eventTypeId; } if (complete.isValid()) { json["complete"] = complete.toJson(); } if (openDate != "") { json["openDate"] = openDate; } if (marketTime != "") { json["marketTime"] = marketTime; } if (bspReconciled.isValid()) { json["bspReconciled"] = bspReconciled.toJson(); } if (lineInterval.isValid()) { json["lineInterval"] = lineInterval.toJson(); } if (status != "") { json["status"] = status; } return json; } bool MarketDefinition::isValid() const { return true; } const std::string& MarketDefinition::getVenue() const { return venue; } void MarketDefinition::setVenue(const std::string& venue) { this->venue = venue; } const std::string& MarketDefinition::getRaceType() const { return raceType; } void MarketDefinition::setRaceType(const std::string& raceType) { this->raceType = raceType; } const std::string& MarketDefinition::getSettledTime() const { return settledTime; } void MarketDefinition::setSettledTime(const std::string& settledTime) { this->settledTime = settledTime; } const std::string& MarketDefinition::getTimezone() const { return timezone; } void MarketDefinition::setTimezone(const std::string& timezone) { this->timezone = timezone; } const Optional<double>& MarketDefinition::getEachWayDivisor() const { return eachWayDivisor; } void MarketDefinition::setEachWayDivisor(const Optional<double>& eachWayDivisor) { this->eachWayDivisor = eachWayDivisor; } const std::set<std::string>& MarketDefinition::getRegulators() const { return regulators; } void MarketDefinition::setRegulators(const std::set<std::string>& regulators) { this->regulators = regulators; } const std::string& MarketDefinition::getMarketType() const { return marketType; } void MarketDefinition::setMarketType(const std::string& marketType) { this->marketType = marketType; } const Optional<double>& MarketDefinition::getMarketBaseRate() const { return marketBaseRate; } void MarketDefinition::setMarketBaseRate(const Optional<double>& marketBaseRate) { this->marketBaseRate = marketBaseRate; } const Optional<int32_t>& MarketDefinition::getNumberOfWinners() const { return numberOfWinners; } void MarketDefinition::setNumberOfWinners(const Optional<int32_t>& numberOfWinners) { this->numberOfWinners = numberOfWinners; } const std::string& MarketDefinition::getCountryCode() const { return countryCode; } void MarketDefinition::setCountryCode(const std::string& countryCode) { this->countryCode = countryCode; } const Optional<double>& MarketDefinition::getLineMaxUnit() const { return lineMaxUnit; } void MarketDefinition::setLineMaxUnit(const Optional<double>& lineMaxUnit) { this->lineMaxUnit = lineMaxUnit; } const Optional<bool>& MarketDefinition::getInPlay() const { return inPlay; } void MarketDefinition::setInPlay(const Optional<bool>& inPlay) { this->inPlay = inPlay; } const Optional<int32_t>& MarketDefinition::getBetDelay() const { return betDelay; } void MarketDefinition::setBetDelay(const Optional<int32_t>& betDelay) { this->betDelay = betDelay; } const Optional<bool>& MarketDefinition::getBspMarket() const { return bspMarket; } void MarketDefinition::setBspMarket(const Optional<bool>& bspMarket) { this->bspMarket = bspMarket; } const std::string& MarketDefinition::getBettingType() const { return bettingType; } void MarketDefinition::setBettingType(const std::string& bettingType) { this->bettingType = bettingType; } const Optional<int32_t>& MarketDefinition::getNumberOfActiveRunners() const { return numberOfActiveRunners; } void MarketDefinition::setNumberOfActiveRunners(const Optional<int32_t>& numberOfActiveRunners) { this->numberOfActiveRunners = numberOfActiveRunners; } const Optional<double>& MarketDefinition::getLineMinUnit() const { return lineMinUnit; } void MarketDefinition::setLineMinUnit(const Optional<double>& lineMinUnit) { this->lineMinUnit = lineMinUnit; } const std::string& MarketDefinition::getEventId() const { return eventId; } void MarketDefinition::setEventId(const std::string& eventId) { this->eventId = eventId; } const Optional<bool>& MarketDefinition::getCrossMatching() const { return crossMatching; } void MarketDefinition::setCrossMatching(const Optional<bool>& crossMatching) { this->crossMatching = crossMatching; } const Optional<bool>& MarketDefinition::getRunnersVoidable() const { return runnersVoidable; } void MarketDefinition::setRunnersVoidable(const Optional<bool>& runnersVoidable) { this->runnersVoidable = runnersVoidable; } const Optional<bool>& MarketDefinition::getTurnInPlayEnabled() const { return turnInPlayEnabled; } void MarketDefinition::setTurnInPlayEnabled(const Optional<bool>& turnInPlayEnabled) { this->turnInPlayEnabled = turnInPlayEnabled; } const PriceLadderDefinition& MarketDefinition::getPriceLadderDefinition() const { return priceLadderDefinition; } void MarketDefinition::setPriceLadderDefinition(const PriceLadderDefinition& priceLadderDefinition) { this->priceLadderDefinition = priceLadderDefinition; } const KeyLineDefinition& MarketDefinition::getKeyLineDefinition() const { return keyLineDefinition; } void MarketDefinition::setKeyLineDefinition(const KeyLineDefinition& keyLineDefinition) { this->keyLineDefinition = keyLineDefinition; } const std::string& MarketDefinition::getSuspendTime() const { return suspendTime; } void MarketDefinition::setSuspendTime(const std::string& suspendTime) { this->suspendTime = suspendTime; } const Optional<bool>& MarketDefinition::getDiscountAllowed() const { return discountAllowed; } void MarketDefinition::setDiscountAllowed(const Optional<bool>& discountAllowed) { this->discountAllowed = discountAllowed; } const Optional<bool>& MarketDefinition::getPersistenceEnabled() const { return persistenceEnabled; } void MarketDefinition::setPersistenceEnabled(const Optional<bool>& persistenceEnabled) { this->persistenceEnabled = persistenceEnabled; } const std::vector<RunnerDefinition>& MarketDefinition::getRunners() const { return runners; } void MarketDefinition::setRunners(const std::vector<RunnerDefinition>& runners) { this->runners = runners; } const Optional<int64_t>& MarketDefinition::getVersion() const { return version; } void MarketDefinition::setVersion(const Optional<int64_t>& version) { this->version = version; } const std::string& MarketDefinition::getEventTypeId() const { return eventTypeId; } void MarketDefinition::setEventTypeId(const std::string& eventTypeId) { this->eventTypeId = eventTypeId; } const Optional<bool>& MarketDefinition::getComplete() const { return complete; } void MarketDefinition::setComplete(const Optional<bool>& complete) { this->complete = complete; } const std::string& MarketDefinition::getOpenDate() const { return openDate; } void MarketDefinition::setOpenDate(const std::string& openDate) { this->openDate = openDate; } const std::string& MarketDefinition::getMarketTime() const { return marketTime; } void MarketDefinition::setMarketTime(const std::string& marketTime) { this->marketTime = marketTime; } const Optional<bool>& MarketDefinition::getBspReconciled() const { return bspReconciled; } void MarketDefinition::setBspReconciled(const Optional<bool>& bspReconciled) { this->bspReconciled = bspReconciled; } const Optional<double>& MarketDefinition::getLineInterval() const { return lineInterval; } void MarketDefinition::setLineInterval(const Optional<double>& lineInterval) { this->lineInterval = lineInterval; } const std::string& MarketDefinition::getStatus() const { return status; } void MarketDefinition::setStatus(const std::string& status) { this->status = status; } } }
30.612789
107
0.678735
[ "vector" ]
3a16269e0a24f195121199c79037a54258df6f3a
550
cpp
C++
Algorithms/22.Generate-Parentheses/solution.cpp
moranzcw/LeetCode_Solutions
49a7e33b83d8d9ce449c758717f74a69e72f808e
[ "MIT" ]
178
2017-07-09T23:13:11.000Z
2022-02-26T13:35:06.000Z
Algorithms/22.Generate-Parentheses/solution.cpp
cfhyxxj/LeetCode-NOTES
455d33aae54d065635d28ebf37f815dc4ace7e63
[ "MIT" ]
1
2020-10-10T16:38:03.000Z
2020-10-10T16:38:03.000Z
Algorithms/22.Generate-Parentheses/solution.cpp
cfhyxxj/LeetCode-NOTES
455d33aae54d065635d28ebf37f815dc4ace7e63
[ "MIT" ]
82
2017-08-19T07:14:39.000Z
2022-02-17T14:07:55.000Z
class Solution { public: void generate(vector<string> &strList, string str, int k, int length) { if(str.size() == length) { if(k==0) strList.push_back(str); return; } if(k>0) { generate(strList, str+')', k-1, length); } generate(strList, str+'(', k+1, length); } vector<string> generateParenthesis(int n) { vector<string> strList; string str; generate(strList, str, 0, n*2); return strList; } };
22
73
0.489091
[ "vector" ]
3a1b0ae9604dcdd171c91ef1b6f9c7cf06455d57
2,305
cpp
C++
recipes-clp/clp/clp/src/AbcPrimalColumnPivot.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-clp/clp/clp/src/AbcPrimalColumnPivot.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-clp/clp/clp/src/AbcPrimalColumnPivot.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
// Copyright (C) 2002, International Business Machines // Corporation and others, Copyright (C) 2012, FasterCoin. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #include "CoinPragma.hpp" #include "AbcSimplex.hpp" #include "AbcPrimalColumnPivot.hpp" //############################################################################# // Constructors / Destructor / Assignment //############################################################################# //------------------------------------------------------------------- // Default Constructor //------------------------------------------------------------------- AbcPrimalColumnPivot::AbcPrimalColumnPivot() : model_(NULL) , type_(-1) , looksOptimal_(false) { } //------------------------------------------------------------------- // Copy constructor //------------------------------------------------------------------- AbcPrimalColumnPivot::AbcPrimalColumnPivot(const AbcPrimalColumnPivot &source) : model_(source.model_) , type_(source.type_) , looksOptimal_(source.looksOptimal_) { } //------------------------------------------------------------------- // Destructor //------------------------------------------------------------------- AbcPrimalColumnPivot::~AbcPrimalColumnPivot() { } //---------------------------------------------------------------- // Assignment operator //------------------------------------------------------------------- AbcPrimalColumnPivot & AbcPrimalColumnPivot::operator=(const AbcPrimalColumnPivot &rhs) { if (this != &rhs) { type_ = rhs.type_; model_ = rhs.model_; looksOptimal_ = rhs.looksOptimal_; } return *this; } void AbcPrimalColumnPivot::saveWeights(AbcSimplex *model, int) { model_ = model; } // checks accuracy and may re-initialize (may be empty) void AbcPrimalColumnPivot::updateWeights(CoinIndexedVector *) { } // Gets rid of all arrays void AbcPrimalColumnPivot::clearArrays() { } /* Returns number of extra columns for sprint algorithm - 0 means off. Also number of iterations before recompute */ int AbcPrimalColumnPivot::numberSprintColumns(int &) const { return 0; } // Switch off sprint idea void AbcPrimalColumnPivot::switchOffSprint() { } /* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2 */
28.109756
80
0.516269
[ "model" ]
3a1be4c816924273b181901e193203160046c8ae
13,405
cpp
C++
src/test/cpp/loggertestcase.cpp
Blaxar/log4cxxNG
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
[ "Apache-2.0" ]
null
null
null
src/test/cpp/loggertestcase.cpp
Blaxar/log4cxxNG
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
[ "Apache-2.0" ]
null
null
null
src/test/cpp/loggertestcase.cpp
Blaxar/log4cxxNG
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 <log4cxxNG/logger.h> #include <log4cxxNG/fileappender.h> #include <log4cxxNG/appenderskeleton.h> #include <log4cxxNG/basicconfigurator.h> #include <log4cxxNG/logmanager.h> #include <log4cxxNG/level.h> #include <log4cxxNG/hierarchy.h> #include <log4cxxNG/spi/rootlogger.h> #include <log4cxxNG/helpers/propertyresourcebundle.h> #include "insertwide.h" #include "testchar.h" #include "logunit.h" #include <log4cxxNG/helpers/locale.h> #include "vectorappender.h" using namespace log4cxxng; using namespace log4cxxng::spi; using namespace log4cxxng::helpers; class CountingAppender; typedef helpers::ObjectPtrT<CountingAppender> CountingAppenderPtr; class CountingAppender : public AppenderSkeleton { public: int counter; CountingAppender() : counter(0) {} void close() {} void append(const spi::LoggingEventPtr& /*event*/, Pool& /*p*/) { counter++; } bool requiresLayout() const { return true; } }; LOGUNIT_CLASS(LoggerTestCase) { LOGUNIT_TEST_SUITE(LoggerTestCase); LOGUNIT_TEST(testAppender1); LOGUNIT_TEST(testAppender2); LOGUNIT_TEST(testAdditivity1); LOGUNIT_TEST(testAdditivity2); LOGUNIT_TEST(testAdditivity3); LOGUNIT_TEST(testDisable1); // LOGUNIT_TEST(testRB1); // LOGUNIT_TEST(testRB2); //TODO restore // LOGUNIT_TEST(testRB3); LOGUNIT_TEST(testExists); LOGUNIT_TEST(testHierarchy1); LOGUNIT_TEST(testTrace); LOGUNIT_TEST(testIsTraceEnabled); LOGUNIT_TEST_SUITE_END(); public: void setUp() { } void tearDown() { BasicConfigurator::resetConfiguration(); a1 = 0; a2 = 0; logger = 0; } /** Add an appender and see if it can be retrieved. */ void testAppender1() { logger = Logger::getLogger(LOG4CXXNG_TEST_STR("test")); a1 = new FileAppender(); a1->setName(LOG4CXXNG_STR("testAppender1")); logger->addAppender(a1); AppenderList list = logger->getAllAppenders(); AppenderPtr aHat = list.front(); LOGUNIT_ASSERT_EQUAL(a1, aHat); } /** Add an appender X, Y, remove X and check if Y is the only remaining appender. */ void testAppender2() { a1 = new FileAppender(); a1->setName(LOG4CXXNG_STR("testAppender2.1")); a2 = new FileAppender(); a2->setName(LOG4CXXNG_STR("testAppender2.2")); logger = Logger::getLogger(LOG4CXXNG_TEST_STR("test")); logger->addAppender(a1); logger->addAppender(a2); logger->removeAppender((LogString) LOG4CXXNG_STR("testAppender2.1")); AppenderList list = logger->getAllAppenders(); AppenderPtr aHat = list.front(); LOGUNIT_ASSERT_EQUAL(a2, aHat); LOGUNIT_ASSERT(list.size() == 1); } /** Test if LoggerPtr a.b inherits its appender from a. */ void testAdditivity1() { LoggerPtr a = Logger::getLogger(LOG4CXXNG_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXXNG_TEST_STR("a.b")); CountingAppenderPtr ca = new CountingAppender(); a->addAppender(ca); LOGUNIT_ASSERT_EQUAL(ca->counter, 0); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 1); ab->info(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 2); ab->warn(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 3); ab->error(MSG); LOGUNIT_ASSERT_EQUAL(ca->counter, 4); } /** Test multiple additivity. */ void testAdditivity2() { LoggerPtr a = Logger::getLogger(LOG4CXXNG_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXXNG_TEST_STR("a.b")); LoggerPtr abc = Logger::getLogger(LOG4CXXNG_TEST_STR("a.b.c")); LoggerPtr x = Logger::getLogger(LOG4CXXNG_TEST_STR("x")); CountingAppenderPtr ca1 = new CountingAppender(); CountingAppenderPtr ca2 = new CountingAppender(); a->addAppender(ca1); abc->addAppender(ca2); LOGUNIT_ASSERT_EQUAL(ca1->counter, 0); LOGUNIT_ASSERT_EQUAL(ca2->counter, 0); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 1); LOGUNIT_ASSERT_EQUAL(ca2->counter, 0); abc->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 2); LOGUNIT_ASSERT_EQUAL(ca2->counter, 1); x->debug(MSG); LOGUNIT_ASSERT_EQUAL(ca1->counter, 2); LOGUNIT_ASSERT_EQUAL(ca2->counter, 1); } /** Test additivity flag. */ void testAdditivity3() { LoggerPtr root = Logger::getRootLogger(); LoggerPtr a = Logger::getLogger(LOG4CXXNG_TEST_STR("a")); LoggerPtr ab = Logger::getLogger(LOG4CXXNG_TEST_STR("a.b")); LoggerPtr abc = Logger::getLogger(LOG4CXXNG_TEST_STR("a.b.c")); LoggerPtr x = Logger::getLogger(LOG4CXXNG_TEST_STR("x")); CountingAppenderPtr caRoot = new CountingAppender(); CountingAppenderPtr caA = new CountingAppender(); CountingAppenderPtr caABC = new CountingAppender(); root->addAppender(caRoot); a->addAppender(caA); abc->addAppender(caABC); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); LOGUNIT_ASSERT_EQUAL(caA->counter, 0); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); ab->setAdditivity(false); a->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); ab->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 0); abc->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); LOGUNIT_ASSERT_EQUAL(caA->counter, 1); LOGUNIT_ASSERT_EQUAL(caABC->counter, 1); } void testDisable1() { CountingAppenderPtr caRoot = new CountingAppender(); LoggerPtr root = Logger::getRootLogger(); root->addAppender(caRoot); LoggerRepositoryPtr h = LogManager::getLoggerRepository(); //h.disableDebug(); h->setThreshold(Level::getInfo()); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 0); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 1); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 2); root->warn(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); //h.disableInfo(); h->setThreshold(Level::getWarn()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 3); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 4); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 5); root->log(Level::getError(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); //h.disableAll(); h->setThreshold(Level::getOff()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); //h.disable(Level::getFatalLevel()); h->setThreshold(Level::getOff()); root->debug(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->info(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->error(MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getWarn(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); root->log(Level::getFatal(), MSG); LOGUNIT_ASSERT_EQUAL(caRoot->counter, 6); } ResourceBundlePtr getBundle(const LogString & lang, const LogString & region) { Locale l(lang, region); ResourceBundlePtr bundle( PropertyResourceBundle::getBundle(LOG4CXXNG_STR("L7D"), l)); LOGUNIT_ASSERT(bundle != 0); return bundle; } void testRB1() { ResourceBundlePtr rbUS(getBundle(LOG4CXXNG_STR("en"), LOG4CXXNG_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXXNG_STR("fr"), LOG4CXXNG_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXXNG_STR("fr"), LOG4CXXNG_STR("CH"))); LoggerPtr root = Logger::getRootLogger(); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXXNG_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXXNG_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXXNG_TEST_STR("x.y.z")); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); } void testRB2() { LoggerPtr root = Logger::getRootLogger(); ResourceBundlePtr rbUS(getBundle(LOG4CXXNG_STR("en"), LOG4CXXNG_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXXNG_STR("fr"), LOG4CXXNG_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXXNG_STR("fr"), LOG4CXXNG_STR("CH"))); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXXNG_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXXNG_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXXNG_TEST_STR("x.y.z")); x_y->setResourceBundle(rbFR); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); } void testRB3() { ResourceBundlePtr rbUS(getBundle(LOG4CXXNG_STR("en"), LOG4CXXNG_STR("US"))); ResourceBundlePtr rbFR(getBundle(LOG4CXXNG_STR("fr"), LOG4CXXNG_STR("FR"))); ResourceBundlePtr rbCH(getBundle(LOG4CXXNG_STR("fr"), LOG4CXXNG_STR("CH"))); LoggerPtr root = Logger::getRootLogger(); root->setResourceBundle(rbUS); ResourceBundlePtr t = root->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); LoggerPtr x = Logger::getLogger(LOG4CXXNG_TEST_STR("x")); LoggerPtr x_y = Logger::getLogger(LOG4CXXNG_TEST_STR("x.y")); LoggerPtr x_y_z = Logger::getLogger(LOG4CXXNG_TEST_STR("x.y.z")); x_y->setResourceBundle(rbFR); x_y_z->setResourceBundle(rbCH); t = x->getResourceBundle(); LOGUNIT_ASSERT(t == rbUS); t = x_y->getResourceBundle(); LOGUNIT_ASSERT(t == rbFR); t = x_y_z->getResourceBundle(); LOGUNIT_ASSERT(t == rbCH); } void testExists() { LoggerPtr a = Logger::getLogger(LOG4CXXNG_TEST_STR("a")); LoggerPtr a_b = Logger::getLogger(LOG4CXXNG_TEST_STR("a.b")); LoggerPtr a_b_c = Logger::getLogger(LOG4CXXNG_TEST_STR("a.b.c")); LoggerPtr t; t = LogManager::exists(LOG4CXXNG_TEST_STR("xx")); LOGUNIT_ASSERT(t == 0); t = LogManager::exists(LOG4CXXNG_TEST_STR("a")); LOGUNIT_ASSERT_EQUAL(a, t); t = LogManager::exists(LOG4CXXNG_TEST_STR("a.b")); LOGUNIT_ASSERT_EQUAL(a_b, t); t = LogManager::exists(LOG4CXXNG_TEST_STR("a.b.c")); LOGUNIT_ASSERT_EQUAL(a_b_c, t); } void testHierarchy1() { LoggerRepositoryPtr h = new Hierarchy(); LoggerPtr root(h->getRootLogger()); root->setLevel(Level::getError()); LoggerPtr a0 = h->getLogger(LOG4CXXNG_STR("a")); LOGUNIT_ASSERT_EQUAL((LogString) LOG4CXXNG_STR("a"), a0->getName()); LOGUNIT_ASSERT(a0->getLevel() == 0); LOGUNIT_ASSERT(Level::getError() == a0->getEffectiveLevel()); LoggerPtr a11 = h->getLogger(LOG4CXXNG_STR("a")); LOGUNIT_ASSERT_EQUAL(a0, a11); } void compileTestForLOGCXX202() const { // // prior to fix, these line would compile. // (*logger).info("Hello, World."); ((Logger*) logger)->info("Hello, World."); // // this one would not. // logger->info("Hello, World."); } /** * Tests logger.trace(Object). * */ void testTrace() { VectorAppenderPtr appender = new VectorAppender(); LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); root->setLevel(Level::getInfo()); LoggerPtr tracer = Logger::getLogger("com.example.Tracer"); tracer->setLevel(Level::getTrace()); LOG4CXXNG_TRACE(tracer, "Message 1"); LOG4CXXNG_TRACE(root, "Discarded Message"); LOG4CXXNG_TRACE(root, "Discarded Message"); std::vector<LoggingEventPtr> msgs(appender->vector); LOGUNIT_ASSERT_EQUAL((size_t) 1, msgs.size()); LoggingEventPtr event = msgs[0]; LOGUNIT_ASSERT_EQUAL((int) Level::TRACE_INT, event->getLevel()->toInt()); LOGUNIT_ASSERT_EQUAL(LogString(LOG4CXXNG_STR("Message 1")), event->getMessage()); } /** * Tests isTraceEnabled. * */ void testIsTraceEnabled() { VectorAppenderPtr appender = new VectorAppender(); LoggerPtr root = Logger::getRootLogger(); root->addAppender(appender); root->setLevel(Level::getInfo()); LoggerPtr tracer = Logger::getLogger("com.example.Tracer"); tracer->setLevel(Level::getTrace()); LOGUNIT_ASSERT_EQUAL(true, tracer->isTraceEnabled()); LOGUNIT_ASSERT_EQUAL(false, root->isTraceEnabled()); } protected: static LogString MSG; LoggerPtr logger; AppenderPtr a1; AppenderPtr a2; }; LogString LoggerTestCase::MSG(LOG4CXXNG_STR("M")); LOGUNIT_TEST_SUITE_REGISTRATION(LoggerTestCase);
28.340381
83
0.717568
[ "object", "vector" ]
3a1ee5ac6870ee4f57efaedd7b27d431c9039a15
4,302
cpp
C++
compiler/sir/transform/manager.cpp
fabbondanza/seq
cb3c0f73ea0f78db69f19022bec0f7a196c8f7a3
[ "Apache-2.0" ]
null
null
null
compiler/sir/transform/manager.cpp
fabbondanza/seq
cb3c0f73ea0f78db69f19022bec0f7a196c8f7a3
[ "Apache-2.0" ]
null
null
null
compiler/sir/transform/manager.cpp
fabbondanza/seq
cb3c0f73ea0f78db69f19022bec0f7a196c8f7a3
[ "Apache-2.0" ]
null
null
null
#include "manager.h" #include <cassert> #include <unordered_set> #include "pass.h" #include "sir/analyze/analysis.h" #include "sir/analyze/dataflow/cfg.h" #include "sir/analyze/dataflow/reaching.h" #include "sir/analyze/module/global_vars.h" #include "sir/transform/folding/folding.h" #include "sir/transform/lowering/imperative.h" #include "sir/transform/manager.h" #include "sir/transform/pythonic/dict.h" #include "sir/transform/pythonic/io.h" #include "sir/transform/pythonic/str.h" #include "util/common.h" namespace seq { namespace ir { namespace transform { const int PassManager::PASS_IT_MAX = 5; std::string PassManager::KeyManager::getUniqueKey(const std::string &key) { // make sure we can't ever produce duplicate "unique'd" keys seqassert(key.find(':') == std::string::npos, "pass key '{}' contains invalid character ':'", key); auto it = keys.find(key); if (it == keys.end()) { keys.emplace(key, 1); return key; } else { auto id = ++(it->second); return key + ":" + std::to_string(id); } } std::string PassManager::registerPass(std::unique_ptr<Pass> pass, std::vector<std::string> reqs, std::vector<std::string> invalidates) { std::string key = pass->getKey(); if (isDisabled(key)) return ""; key = km.getUniqueKey(key); for (const auto &req : reqs) { assert(deps.find(req) != deps.end()); deps[req].push_back(key); } passes.insert(std::make_pair( key, PassMetadata(std::move(pass), std::move(reqs), std::move(invalidates)))); passes[key].pass->setManager(this); executionOrder.push_back(key); return key; } std::string PassManager::registerAnalysis(std::unique_ptr<analyze::Analysis> analysis, std::vector<std::string> reqs) { std::string key = analysis->getKey(); if (isDisabled(key)) return ""; for (const auto &req : reqs) { assert(deps.find(req) != deps.end()); deps[req].push_back(key); } key = km.getUniqueKey(key); analyses.insert( std::make_pair(key, AnalysisMetadata(std::move(analysis), std::move(reqs)))); analyses[key].analysis->setManager(this); deps[key] = {}; return key; } void PassManager::run(Module *module) { for (auto &p : executionOrder) { runPass(module, p); } } void PassManager::runPass(Module *module, const std::string &name) { auto &meta = passes[name]; auto run = true; auto it = 0; while (run && it < PASS_IT_MAX) { for (auto &dep : meta.reqs) { runAnalysis(module, dep); } meta.pass->run(module); for (auto &inv : meta.invalidates) invalidate(inv); ++it; run = meta.pass->shouldRepeat(); } } void PassManager::runAnalysis(Module *module, const std::string &name) { if (results.find(name) != results.end()) return; auto &meta = analyses[name]; for (auto &dep : meta.reqs) { runAnalysis(module, dep); } results[name] = meta.analysis->run(module); } void PassManager::invalidate(const std::string &key) { std::unordered_set<std::string> open = {key}; while (!open.empty()) { std::unordered_set<std::string> newOpen; for (const auto &k : open) { if (results.find(k) != results.end()) { results.erase(k); newOpen.insert(deps[k].begin(), deps[k].end()); } } open = std::move(newOpen); } } void PassManager::registerStandardPasses() { // Pythonic registerPass(std::make_unique<pythonic::DictArithmeticOptimization>()); registerPass(std::make_unique<pythonic::StrAdditionOptimization>()); registerPass(std::make_unique<pythonic::IOCatOptimization>()); // lowering registerPass(std::make_unique<lowering::ImperativeForFlowLowering>()); // folding auto cfgKey = registerAnalysis(std::make_unique<analyze::dataflow::CFAnalysis>()); auto rdKey = registerAnalysis(std::make_unique<analyze::dataflow::RDAnalysis>(cfgKey), {cfgKey}); auto globalKey = registerAnalysis(std::make_unique<analyze::module::GlobalVarsAnalyses>()); registerPass(std::make_unique<folding::FoldingPassGroup>(rdKey, globalKey), {rdKey, globalKey}, {rdKey, cfgKey, globalKey}); } } // namespace transform } // namespace ir } // namespace seq
27.576923
88
0.645049
[ "vector", "transform" ]
3a204817bba64307fbd591816b5b4d072bca7574
5,106
cpp
C++
oi/bzoj/P2286/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
3
2018-08-30T09:43:20.000Z
2019-12-03T04:53:43.000Z
oi/bzoj/P2286/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
oi/bzoj/P2286/main.cpp
Riteme/test
b511d6616a25f4ae8c3861e2029789b8ee4dcb8d
[ "BSD-Source-Code" ]
null
null
null
#define NDEBUG #include <cassert> #include <cctype> #include <cstdio> #include <climits> #include <cstring> #include <vector> #include <algorithm> using namespace std; #define BUFFERSIZE 65536 static size_t pos = BUFFERSIZE; static char buffer[BUFFERSIZE]; inline char _getchar() { if (pos == BUFFERSIZE) { pos = 0; fread(buffer, 1, BUFFERSIZE, stdin); } return buffer[pos++]; } inline int readint() { int x = 0; char c = _getchar(); while (!isdigit(c)) c = _getchar(); while (isdigit(c)) { x = x * 10 + (c - '0'); c = _getchar(); } return x; } #define NMAX 250000 #define LOGN 18 typedef long long int64; struct Edge { Edge (int _u, int _v, int64 _w) : u(_u), v(_v), w(_w) {} int u, v; int64 w; int either(int x) const { return u == x ? v : u; } }; static int n, q; static vector<Edge *> G[NMAX + 10]; static int f[LOGN + 1][NMAX + 10]; static int64 minv[LOGN + 1][NMAX + 10]; static int timestamp; static int dfn[NMAX + 10]; static int dist[NMAX + 10]; static bool marked[NMAX + 10]; static void dfs(int x) { marked[x] = true; dfn[x] = timestamp++; for (size_t i = 0; i < G[x].size(); i++) { Edge *e = G[x][i]; int v = e->either(x); if (!marked[v]) { f[0][v] = x; minv[0][v] = e->w; dist[v] = dist[x] + 1; dfs(v); } } } static void initialize() { // scanf("%d", &n); n = readint(); for (int i = 0; i < n - 1; i++) { int u, v; int64 w; // scanf("%d%d%lld", &u, &v, &w); u = readint(); v = readint(); w = readint(); Edge *e = new Edge(u, v, w); G[u].push_back(e); G[v].push_back(e); } // scanf("%d", &q); q = readint(); dfs(1); for (int j = 1; j <= LOGN; j++) { for (int i = 1; i <= n; i++) { f[j][i] = f[j - 1][f[j - 1][i]]; minv[j][i] = min(minv[j - 1][i], minv[j - 1][f[j - 1][i]]); } } memset(marked, 0, sizeof(marked)); } inline int evaluate_lca(int u, int v) { if (dist[u] < dist[v]) swap(u, v); int delta = dist[u] - dist[v]; for (int i = LOGN; i >= 0; i--) { if ((delta >> i) & 1) { u = f[i][u]; } } if (u == v) return u; for (int i = LOGN; i >= 0; i--) { if (f[i][u] != f[i][v]) { u = f[i][u]; v = f[i][v]; } } return f[0][u]; } inline int64 query_min(int x, int p) { int delta = dist[x] - dist[p]; int64 answer = LLONG_MAX; for (int i = LOGN; i >= 0; i--) { if ((delta >> i) & 1) { answer = min(answer, minv[i][x]); x = f[i][x]; } } return answer; } static int len; static int P[NMAX + 10]; static bool cmp(const int &a, const int &b) { return dfn[a] < dfn[b]; } #define LAST(s) (s[s.size() - 1]) struct Node { Node (int _u) : u(_u), dist(0) {} int u; int64 dist; vector<Node *> children; }; static Node *construct() { sort(P + 1, P + len + 1, cmp); vector<Node *> stk; stk.push_back(new Node(1)); for (int i = 1; i <= len; i++) { int p = P[i]; if (!stk.empty()) { int lca = evaluate_lca(LAST(stk)->u, p); assert(lca != p); while (stk.size() >= 2) { Node *x = LAST(stk); stk.pop_back(); if (dfn[LAST(stk)->u] < dfn[lca]) { Node *nw = new Node(lca); nw->children.push_back(x); stk.push_back(nw); x->dist = query_min(x->u, lca); break; } else { LAST(stk)->children.push_back(x); x->dist = query_min(x->u, LAST(stk)->u); if (LAST(stk)->u == lca) break; } } } stk.push_back(new Node(p)); } while (stk.size() >= 2) { Node *x = LAST(stk); stk.pop_back(); LAST(stk)->children.push_back(x); x->dist = query_min(x->u, LAST(stk)->u); } stk[0]->dist = LLONG_MAX; return stk[0]; } static int64 dp(Node *x) { if (marked[x->u]) return x->dist; int64 sum = 0; for (size_t i = 0; i < x->children.size(); i++) { Node *v = x->children[i]; sum += dp(v); } return min(x->dist, sum); } static int64 query() { for (int i = 1; i <= len; i++) { marked[P[i]] = true; } int64 answer = dp(construct()); for (int i = 1; i <= len; i++) { marked[P[i]] = false; } return answer; } int main() { // freopen("data.in", "r", stdin); initialize(); while (q--) { // scanf("%d", &len); len = readint(); for (int i = 1; i <= len; i++) { // scanf("%d", P + i); P[i] = readint(); } printf("%lld\n", query()); } return 0; }
19.267925
71
0.433803
[ "vector" ]
3a206cc88314204c0ffff306480d9a70523d777a
3,026
cpp
C++
generator/isolines_generator.cpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
1
2022-02-18T17:26:50.000Z
2022-02-18T17:26:50.000Z
generator/isolines_generator.cpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
null
null
null
generator/isolines_generator.cpp
dbf256/organicmaps
1b20d277200dd5444443cf10c6b43cbabf59f3d8
[ "Apache-2.0" ]
null
null
null
#include "generator/isolines_generator.hpp" #include "topography_generator/isolines_utils.hpp" #include "topography_generator/utils/contours_serdes.hpp" #include "indexer/classificator.hpp" namespace generator { namespace { std::vector<int> const kAltClasses = {1000, 500, 100, 50, 10}; int const kNamedAltStep = 50; int const kNamedAltRange = 150; std::string_view const kIsoline = "isoline"; std::string const kTypePrefix = "step_"; std::string_view const kTypeZero = "zero"; std::string GetIsolineName(int altitude, int step, int minAltitude, int maxAltitude) { if (step > 10 || abs(altitude) % kNamedAltStep == 0 || maxAltitude - minAltitude <= kNamedAltRange) { return strings::to_string(altitude); } return ""; } } // namespace IsolineFeaturesGenerator::IsolineFeaturesGenerator(std::string const & isolinesDir) : m_isolinesDir(isolinesDir) { ASSERT(std::is_sorted(kAltClasses.cbegin(), kAltClasses.cend(), std::greater<int>()), ()); Classificator const & c = classif(); for (auto alt : kAltClasses) { auto const type = kTypePrefix + strings::to_string(alt); m_altClassToType[alt] = c.GetTypeByPath({kIsoline, type}); } m_altClassToType[0] = c.GetTypeByPath({kIsoline, kTypeZero}); } uint32_t IsolineFeaturesGenerator::GetIsolineType(int altitude) const { if (altitude == 0) return m_altClassToType.at(0); for (auto altStep : kAltClasses) { if (abs(altitude) % altStep == 0) return m_altClassToType.at(altStep); } return ftype::GetEmptyValue(); } void IsolineFeaturesGenerator::GenerateIsolines(std::string const & countryName, FeaturesCollectFn const & fn) const { auto const isolinesPath = topography_generator::GetIsolinesFilePath(countryName, m_isolinesDir); topography_generator::Contours<topography_generator::Altitude> countryIsolines; if (!topography_generator::LoadContours(isolinesPath, countryIsolines)) { LOG(LWARNING, ("Can't load contours", isolinesPath)); return; } LOG(LINFO, ("Generating isolines for", countryName)); for (auto const & levelIsolines : countryIsolines.m_contours) { auto const altitude = levelIsolines.first; auto const isolineName = GetIsolineName(altitude, countryIsolines.m_valueStep, countryIsolines.m_minValue, countryIsolines.m_maxValue); auto const isolineType = GetIsolineType(altitude); if (isolineType == ftype::GetEmptyValue()) { LOG(LWARNING, ("Skip unsupported altitudes level", altitude, "in", countryName)); continue; } for (auto const & isoline : levelIsolines.second) { feature::FeatureBuilder fb; for (auto const & pt : isoline) fb.AddPoint(pt); fb.AddType(isolineType); if (!isolineName.empty()) fb.AddName("default", isolineName); fb.SetLinear(); fn(std::move(fb)); } } } } // namespace generator
31.520833
100
0.674818
[ "vector" ]
3a20f3b68eb6eb5467b297f405fbcb83e0fa64b9
9,208
cc
C++
lib/kahypar/tests/partition/initial_partitioning/bfs_partitioner_test.cc
sjkelly/LSOracle
21688c5d542740dfc8577349fa615ee655acd92c
[ "MIT" ]
null
null
null
lib/kahypar/tests/partition/initial_partitioning/bfs_partitioner_test.cc
sjkelly/LSOracle
21688c5d542740dfc8577349fa615ee655acd92c
[ "MIT" ]
1
2021-07-26T22:09:49.000Z
2021-07-26T22:09:49.000Z
lib/kahypar/tests/partition/initial_partitioning/bfs_partitioner_test.cc
sjkelly/LSOracle
21688c5d542740dfc8577349fa615ee655acd92c
[ "MIT" ]
2
2021-07-26T14:46:51.000Z
2021-11-09T11:32:09.000Z
/******************************************************************************* * This file is part of KaHyPar. * * Copyright (C) 2015 Tobias Heuer <tobias.heuer@gmx.net> * * KaHyPar 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. * * KaHyPar 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 KaHyPar. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include <memory> #include <queue> #include <unordered_map> #include <vector> #include "gmock/gmock.h" #include "kahypar/io/hypergraph_io.h" #include "kahypar/partition/initial_partitioning/bfs_initial_partitioner.h" #include "kahypar/partition/initial_partitioning/initial_partitioner_base.h" #include "kahypar/partition/initial_partitioning/policies/ip_start_node_selection_policy.h" #include "kahypar/partition/metrics.h" using ::testing::Eq; using ::testing::Test; namespace kahypar { using TestStartNodeSelectionPolicy = BFSStartNodeSelectionPolicy<false>; void initializeContext(Context& context, PartitionID k, HypernodeWeight hypergraph_weight) { context.initial_partitioning.k = k; context.partition.k = k; context.partition.epsilon = 0.05; context.initial_partitioning.unassigned_part = 1; context.initial_partitioning.refinement = false; context.initial_partitioning.nruns = 20; context.initial_partitioning.upper_allowed_partition_weight.resize( context.initial_partitioning.k); context.initial_partitioning.perfect_balance_partition_weight.resize( context.initial_partitioning.k); context.partition.max_part_weights.resize(context.partition.k); context.partition.perfect_balance_part_weights.resize(context.partition.k); for (int i = 0; i < context.initial_partitioning.k; i++) { context.initial_partitioning.perfect_balance_partition_weight[i] = ceil( hypergraph_weight / static_cast<double>(context.initial_partitioning.k)); context.initial_partitioning.upper_allowed_partition_weight[i] = ceil( hypergraph_weight / static_cast<double>(context.initial_partitioning.k)) * (1.0 + context.partition.epsilon); } for (int i = 0; i < context.initial_partitioning.k; ++i) { context.partition.perfect_balance_part_weights[i] = context.initial_partitioning.perfect_balance_partition_weight[i]; context.partition.max_part_weights[i] = context.initial_partitioning.upper_allowed_partition_weight[i]; } } void generateRandomFixedVertices(Hypergraph& hypergraph, const double fixed_vertices_percentage, const PartitionID k) { for (const HypernodeID& hn : hypergraph.nodes()) { int p = Randomize::instance().getRandomInt(0, 100); if (p < fixed_vertices_percentage * 100) { PartitionID part = Randomize::instance().getRandomInt(0, k - 1); hypergraph.setFixedVertex(hn, part); } } } class ABFSBisectionInitialPartioner : public Test { public: ABFSBisectionInitialPartioner() : partitioner(nullptr), hypergraph(7, 4, HyperedgeIndexVector { 0, 2, 6, 9, 12 }, HyperedgeVector { 0, 2, 0, 1, 3, 4, 3, 4, 6, 2, 5, 6 }), context() { PartitionID k = 2; initializeContext(context, k, 7); partitioner = std::make_shared<BFSInitialPartitioner<TestStartNodeSelectionPolicy> >( hypergraph, context); } std::shared_ptr<BFSInitialPartitioner<TestStartNodeSelectionPolicy> > partitioner; Hypergraph hypergraph; Context context; }; class AKWayBFSInitialPartitioner : public Test { public: AKWayBFSInitialPartitioner() : partitioner(nullptr), hypergraph(nullptr), context() { std::string coarse_graph_filename = "test_instances/test_instance.hgr"; HypernodeID num_hypernodes; HyperedgeID num_hyperedges; HyperedgeIndexVector index_vector; HyperedgeVector edge_vector; HyperedgeWeightVector hyperedge_weights; HypernodeWeightVector hypernode_weights; PartitionID k = 4; io::readHypergraphFile( coarse_graph_filename, num_hypernodes, num_hyperedges, index_vector, edge_vector, &hyperedge_weights, &hypernode_weights); hypergraph = std::make_shared<Hypergraph>(num_hypernodes, num_hyperedges, index_vector, edge_vector, k, &hyperedge_weights, &hypernode_weights); HypernodeWeight hypergraph_weight = 0; for (const HypernodeID& hn : hypergraph->nodes()) { hypergraph_weight += hypergraph->nodeWeight(hn); } initializeContext(context, k, hypergraph_weight); partitioner = std::make_shared<BFSInitialPartitioner<TestStartNodeSelectionPolicy> >( *hypergraph, context); } std::shared_ptr<BFSInitialPartitioner<TestStartNodeSelectionPolicy> > partitioner; std::shared_ptr<Hypergraph> hypergraph; Context context; }; TEST_F(ABFSBisectionInitialPartioner, ChecksCorrectBisectionCut) { partitioner->partition(); std::vector<HypernodeID> partition_zero { 0, 1, 2, 3 }; std::vector<HypernodeID> partition_one { 4, 5, 6 }; for (unsigned int i = 0; i < partition_zero.size(); i++) { ASSERT_EQ(hypergraph.partID(partition_zero[i]), 0); } for (unsigned int i = 0; i < partition_one.size(); i++) { ASSERT_EQ(hypergraph.partID(partition_one[i]), 1); } } TEST_F(ABFSBisectionInitialPartioner, LeavesNoHypernodeUnassigned) { partitioner->partition(); for (const HypernodeID& hn : hypergraph.nodes()) { ASSERT_NE(hypergraph.partID(hn), -1); } } TEST_F(ABFSBisectionInitialPartioner, HasCorrectInQueueMapValuesAfterPushingIncidentHypernodesNodesIntoQueue) { std::queue<HypernodeID> q; partitioner->_hypernode_in_queue.set(0, true); q.push(0); hypergraph.setNodePart(0, 0); context.initial_partitioning.unassigned_part = -1; partitioner->pushIncidentHypernodesIntoQueue(q, 0); for (HypernodeID hn = 0; hn < 5; hn++) { ASSERT_TRUE(partitioner->_hypernode_in_queue[hn]); } for (HypernodeID hn = 5; hn < 7; hn++) { ASSERT_FALSE(partitioner->_hypernode_in_queue[hn]); } } TEST_F(ABFSBisectionInitialPartioner, HasCorrectHypernodesInQueueAfterPushingIncidentHypernodesIntoQueue) { std::queue<HypernodeID> q; partitioner->_hypernode_in_queue.set(0, true); q.push(0); hypergraph.setNodePart(0, 0); context.initial_partitioning.unassigned_part = -1; partitioner->pushIncidentHypernodesIntoQueue(q, 0); std::vector<HypernodeID> expected_in_queue { 0, 2, 1, 3, 4 }; for (unsigned int i = 0; i < expected_in_queue.size(); i++) { HypernodeID hn = q.front(); q.pop(); ASSERT_EQ(hn, expected_in_queue[i]); } ASSERT_TRUE(q.empty()); } TEST_F(ABFSBisectionInitialPartioner, SetCorrectFixedVertexPart) { generateRandomFixedVertices(hypergraph, 0.1, 2); partitioner->partition(); for (const HypernodeID& hn : hypergraph.fixedVertices()) { ASSERT_EQ(hypergraph.partID(hn), hypergraph.fixedVertexPartID(hn)); } } TEST_F(AKWayBFSInitialPartitioner, HasValidImbalance) { partitioner->partition(); ASSERT_LE(metrics::imbalance(*hypergraph, context), context.partition.epsilon); } TEST_F(AKWayBFSInitialPartitioner, HasNoSignificantLowPartitionWeights) { partitioner->partition(); // Upper bounds of maximum partition weight should not be exceeded. HypernodeWeight heaviest_part = 0; for (PartitionID k = 0; k < context.initial_partitioning.k; k++) { if (heaviest_part < hypergraph->partWeight(k)) { heaviest_part = hypergraph->partWeight(k); } } // No partition weight should fall below under "lower_bound_factor" // percent of the heaviest partition weight. double lower_bound_factor = 50.0; for (PartitionID k = 0; k < context.initial_partitioning.k; k++) { ASSERT_GE(hypergraph->partWeight(k), (lower_bound_factor / 100.0) * heaviest_part); } } TEST_F(AKWayBFSInitialPartitioner, LeavesNoHypernodeUnassigned) { partitioner->partition(); for (const HypernodeID& hn : hypergraph->nodes()) { ASSERT_NE(hypergraph->partID(hn), -1); } } TEST_F(AKWayBFSInitialPartitioner, GrowPartitionOnPartitionMinus1) { context.initial_partitioning.unassigned_part = -1; partitioner->partition(); for (const HypernodeID& hn : hypergraph->nodes()) { ASSERT_NE(hypergraph->partID(hn), -1); } } TEST_F(AKWayBFSInitialPartitioner, SetCorrectFixedVertexPart) { generateRandomFixedVertices(*hypergraph, 0.1, 4); ASSERT_GE(hypergraph->numFixedVertices(), 0); partitioner->partition(); for (const HypernodeID& hn : hypergraph->fixedVertices()) { ASSERT_EQ(hypergraph->partID(hn), hypergraph->fixedVertexPartID(hn)); } } } // namespace kahypar
35.552124
107
0.711772
[ "vector" ]
3a2af2be48dbed661df84bf036dae5482d2af1a1
4,412
cpp
C++
src/game/server/entities/rope/CRopeSegment.cpp
JoelTroch/halflife-unified-sdk
0ebf7fbde22c346e202fdb26445d7470395eda2a
[ "Unlicense" ]
31
2021-12-04T20:42:48.000Z
2022-03-11T14:16:50.000Z
src/game/server/entities/rope/CRopeSegment.cpp
JoelTroch/halflife-unified-sdk
0ebf7fbde22c346e202fdb26445d7470395eda2a
[ "Unlicense" ]
79
2021-12-11T10:07:30.000Z
2022-03-28T10:09:44.000Z
src/game/server/entities/rope/CRopeSegment.cpp
JoelTroch/halflife-unified-sdk
0ebf7fbde22c346e202fdb26445d7470395eda2a
[ "Unlicense" ]
8
2021-12-10T18:19:10.000Z
2022-03-16T07:49:20.000Z
/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ #include "cbase.h" #include "CRopeSample.h" #include "CRope.h" #include "CRopeSegment.h" TYPEDESCRIPTION CRopeSegment::m_SaveData[] = { DEFINE_FIELD(CRopeSegment, m_pSample, FIELD_CLASSPTR), DEFINE_FIELD(CRopeSegment, m_iszModelName, FIELD_STRING), DEFINE_FIELD(CRopeSegment, m_flDefaultMass, FIELD_FLOAT), DEFINE_FIELD(CRopeSegment, m_bCauseDamage, FIELD_BOOLEAN), DEFINE_FIELD(CRopeSegment, m_bCanBeGrabbed, FIELD_BOOLEAN), }; LINK_ENTITY_TO_CLASS(rope_segment, CRopeSegment); IMPLEMENT_SAVERESTORE(CRopeSegment, CRopeSegment::BaseClass); CRopeSegment::CRopeSegment() { m_iszModelName = MAKE_STRING("models/rope16.mdl"); } void CRopeSegment::Precache() { BaseClass::Precache(); PrecacheModel(STRING(m_iszModelName)); PRECACHE_SOUND("items/grab_rope.wav"); } void CRopeSegment::Spawn() { Precache(); SetModel(STRING(m_iszModelName)); pev->movetype = MOVETYPE_NOCLIP; pev->solid = SOLID_TRIGGER; pev->flags |= FL_ALWAYSTHINK; pev->effects = EF_NODRAW; UTIL_SetOrigin(pev, pev->origin); UTIL_SetSize(pev, Vector(-30, -30, -30), Vector(30, 30, 30)); pev->nextthink = gpGlobals->time + 0.5; } void CRopeSegment::Think() { //Do nothing. } void CRopeSegment::Touch(CBaseEntity* pOther) { if (pOther->IsPlayer()) { auto pPlayer = static_cast<CBasePlayer*>(pOther); //Electrified wires deal damage. - Solokiller if (m_bCauseDamage) { pOther->TakeDamage(pev, pev, 1, DMG_SHOCK); } if (m_pSample->GetMasterRope()->IsAcceptingAttachment() && !pPlayer->IsOnRope()) { if (m_bCanBeGrabbed) { auto& data = m_pSample->GetData(); UTIL_SetOrigin(pOther->pev, data.mPosition); pPlayer->SetOnRopeState(true); pPlayer->SetRope(m_pSample->GetMasterRope()); m_pSample->GetMasterRope()->AttachObjectToSegment(this); const Vector& vecVelocity = pOther->pev->velocity; if (vecVelocity.Length() > 0.5) { //Apply some external force to move the rope. - Solokiller data.mApplyExternalForce = true; data.mExternalForce = data.mExternalForce + vecVelocity * 750; } if (m_pSample->GetMasterRope()->IsSoundAllowed()) { EMIT_SOUND(edict(), CHAN_BODY, "items/grab_rope.wav", 1.0, ATTN_NORM); } } else { //This segment cannot be grabbed, so grab the highest one if possible. - Solokiller auto pRope = m_pSample->GetMasterRope(); CRopeSegment* pSegment; if (pRope->GetNumSegments() <= 4) { //Fewer than 5 segments exist, so allow grabbing the last one. - Solokiller pSegment = pRope->GetSegments()[pRope->GetNumSegments() - 1]; pSegment->SetCanBeGrabbed(true); } else { pSegment = pRope->GetSegments()[4]; } pSegment->Touch(pOther); } } } } CRopeSegment* CRopeSegment::CreateSegment(CRopeSample* pSample, string_t iszModelName) { auto pSegment = GetClassPtr(reinterpret_cast<CRopeSegment*>(VARS(CREATE_NAMED_ENTITY(MAKE_STRING("rope_segment"))))); pSegment->m_iszModelName = iszModelName; pSegment->Spawn(); pSegment->m_pSample = pSample; pSegment->m_bCauseDamage = false; pSegment->m_bCanBeGrabbed = true; pSegment->m_flDefaultMass = pSample->GetData().mMassReciprocal; return pSegment; } void CRopeSegment::ApplyExternalForce(const Vector& vecForce) { m_pSample->GetData().mApplyExternalForce = true; m_pSample->GetData().mExternalForce = m_pSample->GetData().mExternalForce + vecForce; } void CRopeSegment::SetMassToDefault() { m_pSample->GetData().mMassReciprocal = m_flDefaultMass; } void CRopeSegment::SetDefaultMass(const float flDefaultMass) { m_flDefaultMass = flDefaultMass; } void CRopeSegment::SetMass(const float flMass) { m_pSample->GetData().mMassReciprocal = flMass; } void CRopeSegment::SetCauseDamageOnTouch(const bool bCauseDamage) { m_bCauseDamage = bCauseDamage; } void CRopeSegment::SetCanBeGrabbed(const bool bCanBeGrabbed) { m_bCanBeGrabbed = bCanBeGrabbed; }
24.375691
118
0.725748
[ "object", "vector", "solid" ]
3a2b245459558ee729658e7ba7229e355bb69ba4
2,204
cpp
C++
code/components/citizen-server-impl/src/ServerNucleus.cpp
FRDamianDev/fivem
1cb0eea119585a2fa519f353fb5b80047b381fce
[ "MIT" ]
1
2021-09-12T02:53:13.000Z
2021-09-12T02:53:13.000Z
code/components/citizen-server-impl/src/ServerNucleus.cpp
FRDamianDev/fivem
1cb0eea119585a2fa519f353fb5b80047b381fce
[ "MIT" ]
1
2021-09-10T21:44:58.000Z
2021-09-10T21:44:58.000Z
code/components/citizen-server-impl/src/ServerNucleus.cpp
tabarra/fivem
e39292eff3e830887175bb3bbb2fe6d0c8859453
[ "MIT" ]
2
2021-02-04T05:55:47.000Z
2021-02-10T18:35:50.000Z
#include <StdInc.h> #include <CoreConsole.h> #include <GameServer.h> #include <HttpClient.h> #include <ServerInstanceBase.h> #include <ServerInstanceBaseRef.h> #include <ServerLicensingComponent.h> #include <TcpListenManager.h> #include <ReverseTcpServer.h> #include <json.hpp> static InitFunction initFunction([]() { static auto httpClient = new HttpClient(); fx::ServerInstanceBase::OnServerCreate.Connect([](fx::ServerInstanceBase* instance) { static bool setNucleus = false; instance->GetComponent<fx::GameServer>()->OnTick.Connect([instance]() { if (!setNucleus) { auto var = instance->GetComponent<console::Context>()->GetVariableManager()->FindEntryRaw("sv_licenseKeyToken"); if (var && !var->GetValue().empty()) { auto licensingComponent = instance->GetComponent<ServerLicensingComponent>(); auto nucleusToken = licensingComponent->GetNucleusToken(); if (!nucleusToken.empty()) { auto tlm = instance->GetComponent<fx::TcpListenManager>(); auto jsonData = nlohmann::json::object({ { "token", nucleusToken }, { "port", fmt::sprintf("%d", tlm->GetPrimaryPort()) } }); trace("^3Authenticating with Nucleus...^7\n"); httpClient->DoPostRequest("https://cfx.re/api/register/?v=2", jsonData.dump(), [tlm](bool success, const char* data, size_t length) { if (!success) { trace("^1Authenticating with Nucleus failed! That's bad.^7\n"); } else { auto jsonData = nlohmann::json::parse(std::string(data, length)); trace("^1 fff \n cccc ff xx xx rr rr eee \ncc ffff xx rrr r ee e \ncc ff xx ... rr eeeee \n ccccc ff xx xx ... rr eeeee \n ^7\n"); trace("^2Authenticated with cfx.re Nucleus: ^7https://%s/\n", jsonData.value("host", "")); fwRefContainer<net::ReverseTcpServer> rts = new net::ReverseTcpServer(); rts->Listen("cfx.re:30130", jsonData.value("rpToken", "")); tlm->AddExternalServer(rts); } }); } setNucleus = true; } } }); }, INT32_MAX); });
29.386667
256
0.602541
[ "object" ]
3a345c45d079ae2f52a5f77ece35afad02046172
2,902
cpp
C++
llvm/lib/Analysis/LibCallSemantics.cpp
impedimentToProgress/ratchet
4a0f4994ee7e16819849fc0a1a1dbb04921a25fd
[ "MIT" ]
4
2018-12-31T04:46:13.000Z
2021-02-04T15:11:03.000Z
llvm/lib/Analysis/LibCallSemantics.cpp
impedimentToProgress/ratchet
4a0f4994ee7e16819849fc0a1a1dbb04921a25fd
[ "MIT" ]
null
null
null
llvm/lib/Analysis/LibCallSemantics.cpp
impedimentToProgress/ratchet
4a0f4994ee7e16819849fc0a1a1dbb04921a25fd
[ "MIT" ]
3
2017-10-28T16:15:33.000Z
2021-11-16T05:11:43.000Z
//===- LibCallSemantics.cpp - Describe library semantics ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements interfaces that can be used to describe language // specific runtime library interfaces (e.g. libc, libm, etc) to LLVM // optimizers. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/LibCallSemantics.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/IR/Function.h" using namespace llvm; /// This impl pointer in ~LibCallInfo is actually a StringMap. This /// helper does the cast. static StringMap<const LibCallFunctionInfo*> *getMap(void *Ptr) { return static_cast<StringMap<const LibCallFunctionInfo*> *>(Ptr); } LibCallInfo::~LibCallInfo() { delete getMap(Impl); } const LibCallLocationInfo &LibCallInfo::getLocationInfo(unsigned LocID) const { // Get location info on the first call. if (NumLocations == 0) NumLocations = getLocationInfo(Locations); assert(LocID < NumLocations && "Invalid location ID!"); return Locations[LocID]; } /// Return the LibCallFunctionInfo object corresponding to /// the specified function if we have it. If not, return null. const LibCallFunctionInfo * LibCallInfo::getFunctionInfo(const Function *F) const { StringMap<const LibCallFunctionInfo*> *Map = getMap(Impl); /// If this is the first time we are querying for this info, lazily construct /// the StringMap to index it. if (!Map) { Impl = Map = new StringMap<const LibCallFunctionInfo*>(); const LibCallFunctionInfo *Array = getFunctionInfoArray(); if (!Array) return nullptr; // We now have the array of entries. Populate the StringMap. for (unsigned i = 0; Array[i].Name; ++i) (*Map)[Array[i].Name] = Array+i; } // Look up this function in the string map. return Map->lookup(F->getName()); } /// See if the given exception handling personality function is one that we /// understand. If so, return a description of it; otherwise return Unknown. EHPersonality llvm::ClassifyEHPersonality(Value *Pers) { Function *F = dyn_cast<Function>(Pers->stripPointerCasts()); if (!F) return EHPersonality::Unknown; return StringSwitch<EHPersonality>(F->getName()) .Case("__gnat_eh_personality", EHPersonality::GNU_Ada) .Case("__gxx_personality_v0", EHPersonality::GNU_CXX) .Case("__gcc_personality_v0", EHPersonality::GNU_C) .Case("__objc_personality_v0", EHPersonality::GNU_ObjC) .Case("__C_specific_handler", EHPersonality::MSVC_Win64SEH) .Case("__CxxFrameHandler3", EHPersonality::MSVC_CXX) .Default(EHPersonality::Unknown); }
36.275
80
0.673329
[ "object" ]
3a362e4d6a87b71ada81bd3a052c82e71d68d2a1
364
hpp
C++
Plugins/Events/Events/ResourceEvents.hpp
GideonCrawle/unified
2a310e0012badfcc9675bd8c8554613b5354e21a
[ "MIT" ]
null
null
null
Plugins/Events/Events/ResourceEvents.hpp
GideonCrawle/unified
2a310e0012badfcc9675bd8c8554613b5354e21a
[ "MIT" ]
null
null
null
Plugins/Events/Events/ResourceEvents.hpp
GideonCrawle/unified
2a310e0012badfcc9675bd8c8554613b5354e21a
[ "MIT" ]
null
null
null
#pragma once #include "API/Vector.hpp" #include "Common.hpp" #include "Services/Hooks/Hooks.hpp" #include "Services/Tasks/Tasks.hpp" #include <thread> namespace Events { class ResourceEvents { public: ResourceEvents(NWNXLib::Services::TasksProxy* tasks); virtual ~ResourceEvents(); private: static std::unique_ptr<std::thread> m_pollThread; }; }
15.826087
57
0.730769
[ "vector" ]
3a367a73160119ff16cd57db48fa9a3d0c122c9a
52,000
cpp
C++
Source/Urho3D/AngelScript/Generated_Members_HighPriority.cpp
nikolaynedelchev/Urho3D
f6c59d90e982c93bedf2e337b5cdb55d53ff02e0
[ "MIT" ]
null
null
null
Source/Urho3D/AngelScript/Generated_Members_HighPriority.cpp
nikolaynedelchev/Urho3D
f6c59d90e982c93bedf2e337b5cdb55d53ff02e0
[ "MIT" ]
null
null
null
Source/Urho3D/AngelScript/Generated_Members_HighPriority.cpp
nikolaynedelchev/Urho3D
f6c59d90e982c93bedf2e337b5cdb55d53ff02e0
[ "MIT" ]
null
null
null
// DO NOT EDIT. This file is generated // We need register default constructors before any members to allow using in Array<type> #include "../Precompiled.h" #include "../AngelScript/APITemplates.h" #include "../Container/Allocator.h" #include "../Container/HashBase.h" #include "../Container/LinkedList.h" #include "../Container/ListBase.h" #include "../Container/RefCounted.h" #include "../Container/Str.h" #include "../Container/VectorBase.h" #include "../Core/Attribute.h" #include "../Core/Condition.h" #include "../Core/Mutex.h" #include "../Core/Spline.h" #include "../Core/Timer.h" #include "../Core/Variant.h" #include "../Graphics/Animation.h" #include "../Graphics/AnimationState.h" #include "../Graphics/Batch.h" #include "../Graphics/DebugRenderer.h" #include "../Graphics/DecalSet.h" #include "../Graphics/Drawable.h" #include "../Graphics/Graphics.h" #include "../Graphics/GraphicsDefs.h" #include "../Graphics/Light.h" #include "../Graphics/Material.h" #include "../Graphics/Model.h" #include "../Graphics/OcclusionBuffer.h" #include "../Graphics/OctreeQuery.h" #include "../Graphics/ParticleEmitter.h" #include "../Graphics/RenderPath.h" #include "../Graphics/RibbonTrail.h" #include "../Graphics/ShaderVariation.h" #include "../Graphics/StaticModel.h" #include "../Graphics/View.h" #include "../IO/Log.h" #include "../IO/VectorBuffer.h" #include "../Input/Controls.h" #include "../Math/AreaAllocator.h" #include "../Math/BoundingBox.h" #include "../Math/Color.h" #include "../Math/Frustum.h" #include "../Math/Matrix2.h" #include "../Math/Matrix3.h" #include "../Math/Matrix3x4.h" #include "../Math/Matrix4.h" #include "../Math/Plane.h" #include "../Math/Polyhedron.h" #include "../Math/Quaternion.h" #include "../Math/Ray.h" #include "../Math/Rect.h" #include "../Math/Sphere.h" #include "../Math/StringHash.h" #include "../Math/Vector2.h" #include "../Math/Vector3.h" #include "../Math/Vector4.h" #ifdef URHO3D_NAVIGATION #include "../Navigation/NavBuildData.h" #endif #ifdef URHO3D_NAVIGATION #include "../Navigation/NavigationMesh.h" #endif #ifdef URHO3D_NETWORK #include "../Network/Connection.h" #endif #ifdef URHO3D_PHYSICS #include "../Physics/PhysicsWorld.h" #endif #include "../Resource/BackgroundLoader.h" #include "../Resource/Image.h" #include "../Resource/JSONValue.h" #include "../Resource/ResourceCache.h" #include "../Resource/XMLElement.h" #include "../Scene/Node.h" #include "../Scene/ReplicationState.h" #include "../Scene/Scene.h" #include "../Scene/SceneResolver.h" #include "../Scene/ValueAnimation.h" #include "../UI/Cursor.h" #include "../UI/FileSelector.h" #include "../UI/FontFace.h" #include "../UI/Text.h" #include "../UI/UIBatch.h" #ifdef URHO3D_URHO2D #include "../Urho2D/Drawable2D.h" #endif #ifdef URHO3D_URHO2D #include "../Urho2D/ParticleEmitter2D.h" #endif #ifdef URHO3D_URHO2D #include "../Urho2D/PhysicsWorld2D.h" #endif namespace Urho3D { void FakeAddRef(void* ptr); void FakeReleaseRef(void* ptr); // AreaAllocator::AreaAllocator() | File: ../Math/AreaAllocator.h static void AreaAllocator_AreaAllocator_void(AreaAllocator* ptr) { new(ptr) AreaAllocator(); } // BoundingBox::BoundingBox() noexcept | File: ../Math/BoundingBox.h static void BoundingBox_BoundingBox_void(BoundingBox* ptr) { new(ptr) BoundingBox(); } // Color::Color() noexcept | File: ../Math/Color.h static void Color_Color_void(Color* ptr) { new(ptr) Color(); } // Condition::Condition() | File: ../Core/Condition.h static void Condition_Condition_void(Condition* ptr) { new(ptr) Condition(); } // Controls::Controls() | File: ../Input/Controls.h static void Controls_Controls_void(Controls* ptr) { new(ptr) Controls(); } // Frustum::Frustum() noexcept=default | File: ../Math/Frustum.h static void Frustum_Frustum_void(Frustum* ptr) { new(ptr) Frustum(); } // HashBase::HashBase() | File: ../Container/HashBase.h static void HashBase_HashBase_void(HashBase* ptr) { new(ptr) HashBase(); } // HiresTimer::HiresTimer() | File: ../Core/Timer.h static void HiresTimer_HiresTimer_void(HiresTimer* ptr) { new(ptr) HiresTimer(); } // IntRect::IntRect() noexcept | File: ../Math/Rect.h static void IntRect_IntRect_void(IntRect* ptr) { new(ptr) IntRect(); } // IntVector2::IntVector2() noexcept | File: ../Math/Vector2.h static void IntVector2_IntVector2_void(IntVector2* ptr) { new(ptr) IntVector2(); } // IntVector3::IntVector3() noexcept | File: ../Math/Vector3.h static void IntVector3_IntVector3_void(IntVector3* ptr) { new(ptr) IntVector3(); } // JSONValue::JSONValue() | File: ../Resource/JSONValue.h static void JSONValue_JSONValue_void(JSONValue* ptr) { new(ptr) JSONValue(); } // ListBase::ListBase() | File: ../Container/ListBase.h static void ListBase_ListBase_void(ListBase* ptr) { new(ptr) ListBase(); } // Matrix2::Matrix2() noexcept | File: ../Math/Matrix2.h static void Matrix2_Matrix2_void(Matrix2* ptr) { new(ptr) Matrix2(); } // Matrix3::Matrix3() noexcept | File: ../Math/Matrix3.h static void Matrix3_Matrix3_void(Matrix3* ptr) { new(ptr) Matrix3(); } // Matrix3x4::Matrix3x4() noexcept | File: ../Math/Matrix3x4.h static void Matrix3x4_Matrix3x4_void(Matrix3x4* ptr) { new(ptr) Matrix3x4(); } // Matrix4::Matrix4() noexcept | File: ../Math/Matrix4.h static void Matrix4_Matrix4_void(Matrix4* ptr) { new(ptr) Matrix4(); } // Mutex::Mutex() | File: ../Core/Mutex.h static void Mutex_Mutex_void(Mutex* ptr) { new(ptr) Mutex(); } // Plane::Plane() noexcept | File: ../Math/Plane.h static void Plane_Plane_void(Plane* ptr) { new(ptr) Plane(); } // Polyhedron::Polyhedron() noexcept=default | File: ../Math/Polyhedron.h static void Polyhedron_Polyhedron_void(Polyhedron* ptr) { new(ptr) Polyhedron(); } // Quaternion::Quaternion() noexcept | File: ../Math/Quaternion.h static void Quaternion_Quaternion_void(Quaternion* ptr) { new(ptr) Quaternion(); } // Ray::Ray() noexcept=default | File: ../Math/Ray.h static void Ray_Ray_void(Ray* ptr) { new(ptr) Ray(); } // Rect::Rect() noexcept | File: ../Math/Rect.h static void Rect_Rect_void(Rect* ptr) { new(ptr) Rect(); } // SceneResolver::SceneResolver() | File: ../Scene/SceneResolver.h static void SceneResolver_SceneResolver_void(SceneResolver* ptr) { new(ptr) SceneResolver(); } // Sphere::Sphere() noexcept | File: ../Math/Sphere.h static void Sphere_Sphere_void(Sphere* ptr) { new(ptr) Sphere(); } // Spline::Spline() | File: ../Core/Spline.h static void Spline_Spline_void(Spline* ptr) { new(ptr) Spline(); } // String::String() noexcept | File: ../Container/Str.h static void String_String_void(String* ptr) { new(ptr) String(); } // StringHash::StringHash() noexcept | File: ../Math/StringHash.h static void StringHash_StringHash_void(StringHash* ptr) { new(ptr) StringHash(); } // Timer::Timer() | File: ../Core/Timer.h static void Timer_Timer_void(Timer* ptr) { new(ptr) Timer(); } // UIBatch::UIBatch() | File: ../UI/UIBatch.h static void UIBatch_UIBatch_void(UIBatch* ptr) { new(ptr) UIBatch(); } // Variant::Variant()=default | File: ../Core/Variant.h static void Variant_Variant_void(Variant* ptr) { new(ptr) Variant(); } // Vector2::Vector2() noexcept | File: ../Math/Vector2.h static void Vector2_Vector2_void(Vector2* ptr) { new(ptr) Vector2(); } // Vector3::Vector3() noexcept | File: ../Math/Vector3.h static void Vector3_Vector3_void(Vector3* ptr) { new(ptr) Vector3(); } // Vector4::Vector4() noexcept | File: ../Math/Vector4.h static void Vector4_Vector4_void(Vector4* ptr) { new(ptr) Vector4(); } // VectorBase::VectorBase() noexcept | File: ../Container/VectorBase.h static void VectorBase_VectorBase_void(VectorBase* ptr) { new(ptr) VectorBase(); } // VectorBuffer::VectorBuffer() | File: ../IO/VectorBuffer.h static void VectorBuffer_VectorBuffer_void(VectorBuffer* ptr) { new(ptr) VectorBuffer(); } // XMLElement::XMLElement() | File: ../Resource/XMLElement.h static void XMLElement_XMLElement_void(XMLElement* ptr) { new(ptr) XMLElement(); } // XPathQuery::XPathQuery() | File: ../Resource/XMLElement.h static void XPathQuery_XPathQuery_void(XPathQuery* ptr) { new(ptr) XPathQuery(); } // XPathResultSet::XPathResultSet() | File: ../Resource/XMLElement.h static void XPathResultSet_XPathResultSet_void(XPathResultSet* ptr) { new(ptr) XPathResultSet(); } // AllocatorBlock::AllocatorBlock() | Implicitly-declared static void AllocatorBlock_Constructor(AllocatorBlock* ptr) { new(ptr) AllocatorBlock(); } // AllocatorNode::AllocatorNode() | Implicitly-declared static void AllocatorNode_Constructor(AllocatorNode* ptr) { new(ptr) AllocatorNode(); } // AnimationKeyFrame::AnimationKeyFrame() | File: ../Graphics/Animation.h static void AnimationKeyFrame_AnimationKeyFrame_void(AnimationKeyFrame* ptr) { new(ptr) AnimationKeyFrame(); } // AnimationStateTrack::AnimationStateTrack() | File: ../Graphics/AnimationState.h static void AnimationStateTrack_AnimationStateTrack_void(AnimationStateTrack* ptr) { new(ptr) AnimationStateTrack(); } // AnimationTriggerPoint::AnimationTriggerPoint() | File: ../Graphics/Animation.h static void AnimationTriggerPoint_AnimationTriggerPoint_void(AnimationTriggerPoint* ptr) { new(ptr) AnimationTriggerPoint(); } // AsyncProgress::AsyncProgress() | Implicitly-declared static void AsyncProgress_Constructor(AsyncProgress* ptr) { new(ptr) AsyncProgress(); } // AttributeInfo::AttributeInfo()=default | File: ../Core/Attribute.h static void AttributeInfo_AttributeInfo_void(AttributeInfo* ptr) { new(ptr) AttributeInfo(); } // BackgroundLoadItem::BackgroundLoadItem() | Implicitly-declared static void BackgroundLoadItem_Constructor(BackgroundLoadItem* ptr) { new(ptr) BackgroundLoadItem(); } // Batch::Batch()=default | File: ../Graphics/Batch.h static void Batch_Batch_void(Batch* ptr) { new(ptr) Batch(); } // BatchGroup::BatchGroup() | File: ../Graphics/Batch.h static void BatchGroup_BatchGroup_void(BatchGroup* ptr) { new(ptr) BatchGroup(); } // BatchGroupKey::BatchGroupKey()=default | File: ../Graphics/Batch.h static void BatchGroupKey_BatchGroupKey_void(BatchGroupKey* ptr) { new(ptr) BatchGroupKey(); } // BatchQueue::BatchQueue() | Implicitly-declared static void BatchQueue_Constructor(BatchQueue* ptr) { new(ptr) BatchQueue(); } // BiasParameters::BiasParameters()=default | File: ../Graphics/Light.h static void BiasParameters_BiasParameters_void(BiasParameters* ptr) { new(ptr) BiasParameters(); } // CascadeParameters::CascadeParameters()=default | File: ../Graphics/Light.h static void CascadeParameters_CascadeParameters_void(CascadeParameters* ptr) { new(ptr) CascadeParameters(); } // CharLocation::CharLocation() | Implicitly-declared static void CharLocation_Constructor(CharLocation* ptr) { new(ptr) CharLocation(); } // ComponentReplicationState::ComponentReplicationState() | Implicitly-declared static void ComponentReplicationState_Constructor(ComponentReplicationState* ptr) { new(ptr) ComponentReplicationState(); } // CompressedLevel::CompressedLevel() | Implicitly-declared static void CompressedLevel_Constructor(CompressedLevel* ptr) { new(ptr) CompressedLevel(); } // CursorShapeInfo::CursorShapeInfo() | File: ../UI/Cursor.h static void CursorShapeInfo_CursorShapeInfo_void(CursorShapeInfo* ptr) { new(ptr) CursorShapeInfo(); } // DebugLine::DebugLine()=default | File: ../Graphics/DebugRenderer.h static void DebugLine_DebugLine_void(DebugLine* ptr) { new(ptr) DebugLine(); } // DebugTriangle::DebugTriangle()=default | File: ../Graphics/DebugRenderer.h static void DebugTriangle_DebugTriangle_void(DebugTriangle* ptr) { new(ptr) DebugTriangle(); } // Decal::Decal() | File: ../Graphics/DecalSet.h static void Decal_Decal_void(Decal* ptr) { new(ptr) Decal(); } // DecalVertex::DecalVertex()=default | File: ../Graphics/DecalSet.h static void DecalVertex_DecalVertex_void(DecalVertex* ptr) { new(ptr) DecalVertex(); } #ifdef URHO3D_PHYSICS // DelayedWorldTransform::DelayedWorldTransform() | Implicitly-declared static void DelayedWorldTransform_Constructor(DelayedWorldTransform* ptr) { new(ptr) DelayedWorldTransform(); } #endif #ifdef URHO3D_URHO2D // DelayedWorldTransform2D::DelayedWorldTransform2D() | Implicitly-declared static void DelayedWorldTransform2D_Constructor(DelayedWorldTransform2D* ptr) { new(ptr) DelayedWorldTransform2D(); } #endif // DirtyBits::DirtyBits()=default | File: ../Scene/ReplicationState.h static void DirtyBits_DirtyBits_void(DirtyBits* ptr) { new(ptr) DirtyBits(); } // FileSelectorEntry::FileSelectorEntry() | Implicitly-declared static void FileSelectorEntry_Constructor(FileSelectorEntry* ptr) { new(ptr) FileSelectorEntry(); } // FocusParameters::FocusParameters()=default | File: ../Graphics/Light.h static void FocusParameters_FocusParameters_void(FocusParameters* ptr) { new(ptr) FocusParameters(); } // FontGlyph::FontGlyph() | Implicitly-declared static void FontGlyph_Constructor(FontGlyph* ptr) { new(ptr) FontGlyph(); } // FrameInfo::FrameInfo() | Implicitly-declared static void FrameInfo_Constructor(FrameInfo* ptr) { new(ptr) FrameInfo(); } // GeometryDesc::GeometryDesc() | Implicitly-declared static void GeometryDesc_Constructor(GeometryDesc* ptr) { new(ptr) GeometryDesc(); } // HashIteratorBase::HashIteratorBase() | File: ../Container/HashBase.h static void HashIteratorBase_HashIteratorBase_void(HashIteratorBase* ptr) { new(ptr) HashIteratorBase(); } // HashNodeBase::HashNodeBase() | File: ../Container/HashBase.h static void HashNodeBase_HashNodeBase_void(HashNodeBase* ptr) { new(ptr) HashNodeBase(); } // IndexBufferDesc::IndexBufferDesc() | Implicitly-declared static void IndexBufferDesc_Constructor(IndexBufferDesc* ptr) { new(ptr) IndexBufferDesc(); } // InstanceData::InstanceData()=default | File: ../Graphics/Batch.h static void InstanceData_InstanceData_void(InstanceData* ptr) { new(ptr) InstanceData(); } // LightBatchQueue::LightBatchQueue() | Implicitly-declared static void LightBatchQueue_Constructor(LightBatchQueue* ptr) { new(ptr) LightBatchQueue(); } // LightQueryResult::LightQueryResult() | Implicitly-declared static void LightQueryResult_Constructor(LightQueryResult* ptr) { new(ptr) LightQueryResult(); } // LinkedListNode::LinkedListNode() | File: ../Container/LinkedList.h static void LinkedListNode_LinkedListNode_void(LinkedListNode* ptr) { new(ptr) LinkedListNode(); } // ListIteratorBase::ListIteratorBase() | File: ../Container/ListBase.h static void ListIteratorBase_ListIteratorBase_void(ListIteratorBase* ptr) { new(ptr) ListIteratorBase(); } // ListNodeBase::ListNodeBase() | File: ../Container/ListBase.h static void ListNodeBase_ListNodeBase_void(ListNodeBase* ptr) { new(ptr) ListNodeBase(); } #ifdef URHO3D_PHYSICS // ManifoldPair::ManifoldPair() | File: ../Physics/PhysicsWorld.h static void ManifoldPair_ManifoldPair_void(ManifoldPair* ptr) { new(ptr) ManifoldPair(); } #endif // MaterialShaderParameter::MaterialShaderParameter() | Implicitly-declared static void MaterialShaderParameter_Constructor(MaterialShaderParameter* ptr) { new(ptr) MaterialShaderParameter(); } // ModelMorph::ModelMorph() | Implicitly-declared static void ModelMorph_Constructor(ModelMorph* ptr) { new(ptr) ModelMorph(); } #ifdef URHO3D_NAVIGATION // NavAreaStub::NavAreaStub() | Implicitly-declared static void NavAreaStub_Constructor(NavAreaStub* ptr) { new(ptr) NavAreaStub(); } #endif #ifdef URHO3D_NAVIGATION // NavBuildData::NavBuildData() | File: ../Navigation/NavBuildData.h static void NavBuildData_NavBuildData_void(NavBuildData* ptr) { new(ptr) NavBuildData(); } #endif #ifdef URHO3D_NAVIGATION // NavigationGeometryInfo::NavigationGeometryInfo() | Implicitly-declared static void NavigationGeometryInfo_Constructor(NavigationGeometryInfo* ptr) { new(ptr) NavigationGeometryInfo(); } #endif #ifdef URHO3D_NAVIGATION // NavigationPathPoint::NavigationPathPoint() | Implicitly-declared static void NavigationPathPoint_Constructor(NavigationPathPoint* ptr) { new(ptr) NavigationPathPoint(); } #endif // NetworkState::NetworkState() | Implicitly-declared static void NetworkState_Constructor(NetworkState* ptr) { new(ptr) NetworkState(); } // NodeImpl::NodeImpl() | Implicitly-declared static void NodeImpl_Constructor(NodeImpl* ptr) { new(ptr) NodeImpl(); } // NodeReplicationState::NodeReplicationState() | Implicitly-declared static void NodeReplicationState_Constructor(NodeReplicationState* ptr) { new(ptr) NodeReplicationState(); } // OcclusionBatch::OcclusionBatch() | Implicitly-declared static void OcclusionBatch_Constructor(OcclusionBatch* ptr) { new(ptr) OcclusionBatch(); } // OcclusionBufferData::OcclusionBufferData() | Implicitly-declared static void OcclusionBufferData_Constructor(OcclusionBufferData* ptr) { new(ptr) OcclusionBufferData(); } // OctreeQueryResult::OctreeQueryResult() | File: ../Graphics/OctreeQuery.h static void OctreeQueryResult_OctreeQueryResult_void(OctreeQueryResult* ptr) { new(ptr) OctreeQueryResult(); } #ifdef URHO3D_NETWORK // PackageDownload::PackageDownload() | File: ../Network/Connection.h static void PackageDownload_PackageDownload_void(PackageDownload* ptr) { new(ptr) PackageDownload(); } #endif #ifdef URHO3D_NETWORK // PackageUpload::PackageUpload() | File: ../Network/Connection.h static void PackageUpload_PackageUpload_void(PackageUpload* ptr) { new(ptr) PackageUpload(); } #endif // Particle::Particle() | Implicitly-declared static void Particle_Constructor(Particle* ptr) { new(ptr) Particle(); } #ifdef URHO3D_URHO2D // Particle2D::Particle2D() | Implicitly-declared static void Particle2D_Constructor(Particle2D* ptr) { new(ptr) Particle2D(); } #endif // PerThreadSceneResult::PerThreadSceneResult() | Implicitly-declared static void PerThreadSceneResult_Constructor(PerThreadSceneResult* ptr) { new(ptr) PerThreadSceneResult(); } #ifdef URHO3D_PHYSICS // PhysicsRaycastResult::PhysicsRaycastResult() | Implicitly-declared static void PhysicsRaycastResult_Constructor(PhysicsRaycastResult* ptr) { new(ptr) PhysicsRaycastResult(); } #endif #ifdef URHO3D_URHO2D // PhysicsRaycastResult2D::PhysicsRaycastResult2D() | Implicitly-declared static void PhysicsRaycastResult2D_Constructor(PhysicsRaycastResult2D* ptr) { new(ptr) PhysicsRaycastResult2D(); } #endif #ifdef URHO3D_PHYSICS // PhysicsWorldConfig::PhysicsWorldConfig() | File: ../Physics/PhysicsWorld.h static void PhysicsWorldConfig_PhysicsWorldConfig_void(PhysicsWorldConfig* ptr) { new(ptr) PhysicsWorldConfig(); } #endif // RayQueryResult::RayQueryResult() | File: ../Graphics/OctreeQuery.h static void RayQueryResult_RayQueryResult_void(RayQueryResult* ptr) { new(ptr) RayQueryResult(); } // RefCount::RefCount() | File: ../Container/RefCounted.h static void RefCount_RefCount_void(RefCount* ptr) { new(ptr) RefCount(); } #ifdef URHO3D_NETWORK // RemoteEvent::RemoteEvent() | Implicitly-declared static void RemoteEvent_Constructor(RemoteEvent* ptr) { new(ptr) RemoteEvent(); } #endif // RenderPathCommand::RenderPathCommand() | Implicitly-declared static void RenderPathCommand_Constructor(RenderPathCommand* ptr) { new(ptr) RenderPathCommand(); } // RenderTargetInfo::RenderTargetInfo() | Implicitly-declared static void RenderTargetInfo_Constructor(RenderTargetInfo* ptr) { new(ptr) RenderTargetInfo(); } // ReplicationState::ReplicationState() | Implicitly-declared static void ReplicationState_Constructor(ReplicationState* ptr) { new(ptr) ReplicationState(); } // ResourceGroup::ResourceGroup() | File: ../Resource/ResourceCache.h static void ResourceGroup_ResourceGroup_void(ResourceGroup* ptr) { new(ptr) ResourceGroup(); } // ResourceRef::ResourceRef()=default | File: ../Core/Variant.h static void ResourceRef_ResourceRef_void(ResourceRef* ptr) { new(ptr) ResourceRef(); } // ResourceRefList::ResourceRefList()=default | File: ../Core/Variant.h static void ResourceRefList_ResourceRefList_void(ResourceRefList* ptr) { new(ptr) ResourceRefList(); } // ScenePassInfo::ScenePassInfo() | Implicitly-declared static void ScenePassInfo_Constructor(ScenePassInfo* ptr) { new(ptr) ScenePassInfo(); } // SceneReplicationState::SceneReplicationState() | Implicitly-declared static void SceneReplicationState_Constructor(SceneReplicationState* ptr) { new(ptr) SceneReplicationState(); } // ScratchBuffer::ScratchBuffer() | File: ../Graphics/Graphics.h static void ScratchBuffer_ScratchBuffer_void(ScratchBuffer* ptr) { new(ptr) ScratchBuffer(); } // ScreenModeParams::ScreenModeParams() | Implicitly-declared static void ScreenModeParams_Constructor(ScreenModeParams* ptr) { new(ptr) ScreenModeParams(); } // ShaderParameter::ShaderParameter()=default | File: ../Graphics/ShaderVariation.h static void ShaderParameter_ShaderParameter_void(ShaderParameter* ptr) { new(ptr) ShaderParameter(); } // ShadowBatchQueue::ShadowBatchQueue() | Implicitly-declared static void ShadowBatchQueue_Constructor(ShadowBatchQueue* ptr) { new(ptr) ShadowBatchQueue(); } #ifdef URHO3D_NAVIGATION // SimpleNavBuildData::SimpleNavBuildData() | File: ../Navigation/NavBuildData.h static void SimpleNavBuildData_SimpleNavBuildData_void(SimpleNavBuildData* ptr) { new(ptr) SimpleNavBuildData(); } #endif // SourceBatch::SourceBatch() | File: ../Graphics/Drawable.h static void SourceBatch_SourceBatch_void(SourceBatch* ptr) { new(ptr) SourceBatch(); } #ifdef URHO3D_URHO2D // SourceBatch2D::SourceBatch2D() | File: ../Urho2D/Drawable2D.h static void SourceBatch2D_SourceBatch2D_void(SourceBatch2D* ptr) { new(ptr) SourceBatch2D(); } #endif // StaticModelGeometryData::StaticModelGeometryData() | Implicitly-declared static void StaticModelGeometryData_Constructor(StaticModelGeometryData* ptr) { new(ptr) StaticModelGeometryData(); } // StoredLogMessage::StoredLogMessage()=default | File: ../IO/Log.h static void StoredLogMessage_StoredLogMessage_void(StoredLogMessage* ptr) { new(ptr) StoredLogMessage(); } // TechniqueEntry::TechniqueEntry() noexcept | File: ../Graphics/Material.h static void TechniqueEntry_TechniqueEntry_void(TechniqueEntry* ptr) { new(ptr) TechniqueEntry(); } // TrailPoint::TrailPoint()=default | File: ../Graphics/RibbonTrail.h static void TrailPoint_TrailPoint_void(TrailPoint* ptr) { new(ptr) TrailPoint(); } // VAnimEventFrame::VAnimEventFrame() | Implicitly-declared static void VAnimEventFrame_Constructor(VAnimEventFrame* ptr) { new(ptr) VAnimEventFrame(); } // VAnimKeyFrame::VAnimKeyFrame() | Implicitly-declared static void VAnimKeyFrame_Constructor(VAnimKeyFrame* ptr) { new(ptr) VAnimKeyFrame(); } #ifdef URHO3D_URHO2D // Vertex2D::Vertex2D() | Implicitly-declared static void Vertex2D_Constructor(Vertex2D* ptr) { new(ptr) Vertex2D(); } #endif // VertexBufferDesc::VertexBufferDesc() | Implicitly-declared static void VertexBufferDesc_Constructor(VertexBufferDesc* ptr) { new(ptr) VertexBufferDesc(); } // VertexBufferMorph::VertexBufferMorph() | Implicitly-declared static void VertexBufferMorph_Constructor(VertexBufferMorph* ptr) { new(ptr) VertexBufferMorph(); } // VertexElement::VertexElement() noexcept | File: ../Graphics/GraphicsDefs.h static void VertexElement_VertexElement_void(VertexElement* ptr) { new(ptr) VertexElement(); } // WindowModeParams::WindowModeParams() | Implicitly-declared static void WindowModeParams_Constructor(WindowModeParams* ptr) { new(ptr) WindowModeParams(); } void ASRegisterGenerated_Members_HighPriority(asIScriptEngine* engine) { // AreaAllocator::AreaAllocator() | File: ../Math/AreaAllocator.h engine->RegisterObjectBehaviour("AreaAllocator", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(AreaAllocator_AreaAllocator_void), asCALL_CDECL_OBJFIRST); // BoundingBox::BoundingBox() noexcept | File: ../Math/BoundingBox.h engine->RegisterObjectBehaviour("BoundingBox", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(BoundingBox_BoundingBox_void), asCALL_CDECL_OBJFIRST); // Color::Color() noexcept | File: ../Math/Color.h engine->RegisterObjectBehaviour("Color", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Color_Color_void), asCALL_CDECL_OBJFIRST); // Condition::Condition() | File: ../Core/Condition.h engine->RegisterObjectBehaviour("Condition", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Condition_Condition_void), asCALL_CDECL_OBJFIRST); // Controls::Controls() | File: ../Input/Controls.h engine->RegisterObjectBehaviour("Controls", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Controls_Controls_void), asCALL_CDECL_OBJFIRST); // Frustum::Frustum() noexcept=default | File: ../Math/Frustum.h engine->RegisterObjectBehaviour("Frustum", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Frustum_Frustum_void), asCALL_CDECL_OBJFIRST); // HashBase::HashBase() | File: ../Container/HashBase.h engine->RegisterObjectBehaviour("HashBase", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(HashBase_HashBase_void), asCALL_CDECL_OBJFIRST); // HiresTimer::HiresTimer() | File: ../Core/Timer.h engine->RegisterObjectBehaviour("HiresTimer", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(HiresTimer_HiresTimer_void), asCALL_CDECL_OBJFIRST); // IntRect::IntRect() noexcept | File: ../Math/Rect.h engine->RegisterObjectBehaviour("IntRect", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(IntRect_IntRect_void), asCALL_CDECL_OBJFIRST); // IntVector2::IntVector2() noexcept | File: ../Math/Vector2.h engine->RegisterObjectBehaviour("IntVector2", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(IntVector2_IntVector2_void), asCALL_CDECL_OBJFIRST); // IntVector3::IntVector3() noexcept | File: ../Math/Vector3.h engine->RegisterObjectBehaviour("IntVector3", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(IntVector3_IntVector3_void), asCALL_CDECL_OBJFIRST); // JSONValue::JSONValue() | File: ../Resource/JSONValue.h engine->RegisterObjectBehaviour("JSONValue", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(JSONValue_JSONValue_void), asCALL_CDECL_OBJFIRST); // ListBase::ListBase() | File: ../Container/ListBase.h engine->RegisterObjectBehaviour("ListBase", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ListBase_ListBase_void), asCALL_CDECL_OBJFIRST); // Matrix2::Matrix2() noexcept | File: ../Math/Matrix2.h engine->RegisterObjectBehaviour("Matrix2", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Matrix2_Matrix2_void), asCALL_CDECL_OBJFIRST); // Matrix3::Matrix3() noexcept | File: ../Math/Matrix3.h engine->RegisterObjectBehaviour("Matrix3", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Matrix3_Matrix3_void), asCALL_CDECL_OBJFIRST); // Matrix3x4::Matrix3x4() noexcept | File: ../Math/Matrix3x4.h engine->RegisterObjectBehaviour("Matrix3x4", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Matrix3x4_Matrix3x4_void), asCALL_CDECL_OBJFIRST); // Matrix4::Matrix4() noexcept | File: ../Math/Matrix4.h engine->RegisterObjectBehaviour("Matrix4", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Matrix4_Matrix4_void), asCALL_CDECL_OBJFIRST); // Mutex::Mutex() | File: ../Core/Mutex.h engine->RegisterObjectBehaviour("Mutex", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Mutex_Mutex_void), asCALL_CDECL_OBJFIRST); // Plane::Plane() noexcept | File: ../Math/Plane.h engine->RegisterObjectBehaviour("Plane", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Plane_Plane_void), asCALL_CDECL_OBJFIRST); // Polyhedron::Polyhedron() noexcept=default | File: ../Math/Polyhedron.h engine->RegisterObjectBehaviour("Polyhedron", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Polyhedron_Polyhedron_void), asCALL_CDECL_OBJFIRST); // Quaternion::Quaternion() noexcept | File: ../Math/Quaternion.h engine->RegisterObjectBehaviour("Quaternion", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Quaternion_Quaternion_void), asCALL_CDECL_OBJFIRST); // Ray::Ray() noexcept=default | File: ../Math/Ray.h engine->RegisterObjectBehaviour("Ray", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Ray_Ray_void), asCALL_CDECL_OBJFIRST); // Rect::Rect() noexcept | File: ../Math/Rect.h engine->RegisterObjectBehaviour("Rect", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Rect_Rect_void), asCALL_CDECL_OBJFIRST); // SceneResolver::SceneResolver() | File: ../Scene/SceneResolver.h engine->RegisterObjectBehaviour("SceneResolver", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(SceneResolver_SceneResolver_void), asCALL_CDECL_OBJFIRST); // Sphere::Sphere() noexcept | File: ../Math/Sphere.h engine->RegisterObjectBehaviour("Sphere", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Sphere_Sphere_void), asCALL_CDECL_OBJFIRST); // Spline::Spline() | File: ../Core/Spline.h engine->RegisterObjectBehaviour("Spline", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Spline_Spline_void), asCALL_CDECL_OBJFIRST); // String::String() noexcept | File: ../Container/Str.h engine->RegisterObjectBehaviour("String", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(String_String_void), asCALL_CDECL_OBJFIRST); // StringHash::StringHash() noexcept | File: ../Math/StringHash.h engine->RegisterObjectBehaviour("StringHash", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(StringHash_StringHash_void), asCALL_CDECL_OBJFIRST); // Timer::Timer() | File: ../Core/Timer.h engine->RegisterObjectBehaviour("Timer", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Timer_Timer_void), asCALL_CDECL_OBJFIRST); // UIBatch::UIBatch() | File: ../UI/UIBatch.h engine->RegisterObjectBehaviour("UIBatch", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(UIBatch_UIBatch_void), asCALL_CDECL_OBJFIRST); // Variant::Variant()=default | File: ../Core/Variant.h engine->RegisterObjectBehaviour("Variant", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Variant_Variant_void), asCALL_CDECL_OBJFIRST); // Vector2::Vector2() noexcept | File: ../Math/Vector2.h engine->RegisterObjectBehaviour("Vector2", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Vector2_Vector2_void), asCALL_CDECL_OBJFIRST); // Vector3::Vector3() noexcept | File: ../Math/Vector3.h engine->RegisterObjectBehaviour("Vector3", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Vector3_Vector3_void), asCALL_CDECL_OBJFIRST); // Vector4::Vector4() noexcept | File: ../Math/Vector4.h engine->RegisterObjectBehaviour("Vector4", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Vector4_Vector4_void), asCALL_CDECL_OBJFIRST); // VectorBase::VectorBase() noexcept | File: ../Container/VectorBase.h engine->RegisterObjectBehaviour("VectorBase", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(VectorBase_VectorBase_void), asCALL_CDECL_OBJFIRST); // VectorBuffer::VectorBuffer() | File: ../IO/VectorBuffer.h engine->RegisterObjectBehaviour("VectorBuffer", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(VectorBuffer_VectorBuffer_void), asCALL_CDECL_OBJFIRST); // XMLElement::XMLElement() | File: ../Resource/XMLElement.h engine->RegisterObjectBehaviour("XMLElement", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(XMLElement_XMLElement_void), asCALL_CDECL_OBJFIRST); // XPathQuery::XPathQuery() | File: ../Resource/XMLElement.h engine->RegisterObjectBehaviour("XPathQuery", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(XPathQuery_XPathQuery_void), asCALL_CDECL_OBJFIRST); // XPathResultSet::XPathResultSet() | File: ../Resource/XMLElement.h engine->RegisterObjectBehaviour("XPathResultSet", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(XPathResultSet_XPathResultSet_void), asCALL_CDECL_OBJFIRST); // AllocatorBlock::AllocatorBlock() | Implicitly-declared engine->RegisterObjectBehaviour("AllocatorBlock", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(AllocatorBlock_Constructor), asCALL_CDECL_OBJFIRST); // AllocatorNode::AllocatorNode() | Implicitly-declared engine->RegisterObjectBehaviour("AllocatorNode", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(AllocatorNode_Constructor), asCALL_CDECL_OBJFIRST); // AnimationKeyFrame::AnimationKeyFrame() | File: ../Graphics/Animation.h engine->RegisterObjectBehaviour("AnimationKeyFrame", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(AnimationKeyFrame_AnimationKeyFrame_void), asCALL_CDECL_OBJFIRST); // AnimationStateTrack::AnimationStateTrack() | File: ../Graphics/AnimationState.h engine->RegisterObjectBehaviour("AnimationStateTrack", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(AnimationStateTrack_AnimationStateTrack_void), asCALL_CDECL_OBJFIRST); // AnimationTriggerPoint::AnimationTriggerPoint() | File: ../Graphics/Animation.h engine->RegisterObjectBehaviour("AnimationTriggerPoint", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(AnimationTriggerPoint_AnimationTriggerPoint_void), asCALL_CDECL_OBJFIRST); // AsyncProgress::AsyncProgress() | Implicitly-declared engine->RegisterObjectBehaviour("AsyncProgress", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(AsyncProgress_Constructor), asCALL_CDECL_OBJFIRST); // AttributeInfo::AttributeInfo()=default | File: ../Core/Attribute.h engine->RegisterObjectBehaviour("AttributeInfo", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(AttributeInfo_AttributeInfo_void), asCALL_CDECL_OBJFIRST); // BackgroundLoadItem::BackgroundLoadItem() | Implicitly-declared engine->RegisterObjectBehaviour("BackgroundLoadItem", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(BackgroundLoadItem_Constructor), asCALL_CDECL_OBJFIRST); // Batch::Batch()=default | File: ../Graphics/Batch.h engine->RegisterObjectBehaviour("Batch", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Batch_Batch_void), asCALL_CDECL_OBJFIRST); // BatchGroup::BatchGroup() | File: ../Graphics/Batch.h engine->RegisterObjectBehaviour("BatchGroup", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(BatchGroup_BatchGroup_void), asCALL_CDECL_OBJFIRST); // BatchGroupKey::BatchGroupKey()=default | File: ../Graphics/Batch.h engine->RegisterObjectBehaviour("BatchGroupKey", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(BatchGroupKey_BatchGroupKey_void), asCALL_CDECL_OBJFIRST); // BatchQueue::BatchQueue() | Implicitly-declared engine->RegisterObjectBehaviour("BatchQueue", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(BatchQueue_Constructor), asCALL_CDECL_OBJFIRST); // BiasParameters::BiasParameters()=default | File: ../Graphics/Light.h engine->RegisterObjectBehaviour("BiasParameters", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(BiasParameters_BiasParameters_void), asCALL_CDECL_OBJFIRST); // CascadeParameters::CascadeParameters()=default | File: ../Graphics/Light.h engine->RegisterObjectBehaviour("CascadeParameters", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(CascadeParameters_CascadeParameters_void), asCALL_CDECL_OBJFIRST); // CharLocation::CharLocation() | Implicitly-declared engine->RegisterObjectBehaviour("CharLocation", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(CharLocation_Constructor), asCALL_CDECL_OBJFIRST); // ComponentReplicationState::ComponentReplicationState() | Implicitly-declared engine->RegisterObjectBehaviour("ComponentReplicationState", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ComponentReplicationState_Constructor), asCALL_CDECL_OBJFIRST); // CompressedLevel::CompressedLevel() | Implicitly-declared engine->RegisterObjectBehaviour("CompressedLevel", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(CompressedLevel_Constructor), asCALL_CDECL_OBJFIRST); // CursorShapeInfo::CursorShapeInfo() | File: ../UI/Cursor.h engine->RegisterObjectBehaviour("CursorShapeInfo", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(CursorShapeInfo_CursorShapeInfo_void), asCALL_CDECL_OBJFIRST); // DebugLine::DebugLine()=default | File: ../Graphics/DebugRenderer.h engine->RegisterObjectBehaviour("DebugLine", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DebugLine_DebugLine_void), asCALL_CDECL_OBJFIRST); // DebugTriangle::DebugTriangle()=default | File: ../Graphics/DebugRenderer.h engine->RegisterObjectBehaviour("DebugTriangle", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DebugTriangle_DebugTriangle_void), asCALL_CDECL_OBJFIRST); // Decal::Decal() | File: ../Graphics/DecalSet.h engine->RegisterObjectBehaviour("Decal", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Decal_Decal_void), asCALL_CDECL_OBJFIRST); // DecalVertex::DecalVertex()=default | File: ../Graphics/DecalSet.h engine->RegisterObjectBehaviour("DecalVertex", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DecalVertex_DecalVertex_void), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_PHYSICS // DelayedWorldTransform::DelayedWorldTransform() | Implicitly-declared engine->RegisterObjectBehaviour("DelayedWorldTransform", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DelayedWorldTransform_Constructor), asCALL_CDECL_OBJFIRST); #endif #ifdef URHO3D_URHO2D // DelayedWorldTransform2D::DelayedWorldTransform2D() | Implicitly-declared engine->RegisterObjectBehaviour("DelayedWorldTransform2D", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DelayedWorldTransform2D_Constructor), asCALL_CDECL_OBJFIRST); #endif // DirtyBits::DirtyBits()=default | File: ../Scene/ReplicationState.h engine->RegisterObjectBehaviour("DirtyBits", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DirtyBits_DirtyBits_void), asCALL_CDECL_OBJFIRST); // FileSelectorEntry::FileSelectorEntry() | Implicitly-declared engine->RegisterObjectBehaviour("FileSelectorEntry", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(FileSelectorEntry_Constructor), asCALL_CDECL_OBJFIRST); // FocusParameters::FocusParameters()=default | File: ../Graphics/Light.h engine->RegisterObjectBehaviour("FocusParameters", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(FocusParameters_FocusParameters_void), asCALL_CDECL_OBJFIRST); // FontGlyph::FontGlyph() | Implicitly-declared engine->RegisterObjectBehaviour("FontGlyph", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(FontGlyph_Constructor), asCALL_CDECL_OBJFIRST); // FrameInfo::FrameInfo() | Implicitly-declared engine->RegisterObjectBehaviour("FrameInfo", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(FrameInfo_Constructor), asCALL_CDECL_OBJFIRST); // GeometryDesc::GeometryDesc() | Implicitly-declared engine->RegisterObjectBehaviour("GeometryDesc", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(GeometryDesc_Constructor), asCALL_CDECL_OBJFIRST); // HashIteratorBase::HashIteratorBase() | File: ../Container/HashBase.h engine->RegisterObjectBehaviour("HashIteratorBase", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(HashIteratorBase_HashIteratorBase_void), asCALL_CDECL_OBJFIRST); // HashNodeBase::HashNodeBase() | File: ../Container/HashBase.h engine->RegisterObjectBehaviour("HashNodeBase", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(HashNodeBase_HashNodeBase_void), asCALL_CDECL_OBJFIRST); // IndexBufferDesc::IndexBufferDesc() | Implicitly-declared engine->RegisterObjectBehaviour("IndexBufferDesc", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(IndexBufferDesc_Constructor), asCALL_CDECL_OBJFIRST); // InstanceData::InstanceData()=default | File: ../Graphics/Batch.h engine->RegisterObjectBehaviour("InstanceData", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(InstanceData_InstanceData_void), asCALL_CDECL_OBJFIRST); // LightBatchQueue::LightBatchQueue() | Implicitly-declared engine->RegisterObjectBehaviour("LightBatchQueue", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(LightBatchQueue_Constructor), asCALL_CDECL_OBJFIRST); // LightQueryResult::LightQueryResult() | Implicitly-declared engine->RegisterObjectBehaviour("LightQueryResult", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(LightQueryResult_Constructor), asCALL_CDECL_OBJFIRST); // LinkedListNode::LinkedListNode() | File: ../Container/LinkedList.h engine->RegisterObjectBehaviour("LinkedListNode", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(LinkedListNode_LinkedListNode_void), asCALL_CDECL_OBJFIRST); // ListIteratorBase::ListIteratorBase() | File: ../Container/ListBase.h engine->RegisterObjectBehaviour("ListIteratorBase", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ListIteratorBase_ListIteratorBase_void), asCALL_CDECL_OBJFIRST); // ListNodeBase::ListNodeBase() | File: ../Container/ListBase.h engine->RegisterObjectBehaviour("ListNodeBase", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ListNodeBase_ListNodeBase_void), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_PHYSICS // ManifoldPair::ManifoldPair() | File: ../Physics/PhysicsWorld.h engine->RegisterObjectBehaviour("ManifoldPair", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ManifoldPair_ManifoldPair_void), asCALL_CDECL_OBJFIRST); #endif // MaterialShaderParameter::MaterialShaderParameter() | Implicitly-declared engine->RegisterObjectBehaviour("MaterialShaderParameter", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(MaterialShaderParameter_Constructor), asCALL_CDECL_OBJFIRST); // ModelMorph::ModelMorph() | Implicitly-declared engine->RegisterObjectBehaviour("ModelMorph", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ModelMorph_Constructor), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_NAVIGATION // NavAreaStub::NavAreaStub() | Implicitly-declared engine->RegisterObjectBehaviour("NavAreaStub", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(NavAreaStub_Constructor), asCALL_CDECL_OBJFIRST); #endif #ifdef URHO3D_NAVIGATION // NavBuildData::NavBuildData() | File: ../Navigation/NavBuildData.h engine->RegisterObjectBehaviour("NavBuildData", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(NavBuildData_NavBuildData_void), asCALL_CDECL_OBJFIRST); #endif #ifdef URHO3D_NAVIGATION // NavigationGeometryInfo::NavigationGeometryInfo() | Implicitly-declared engine->RegisterObjectBehaviour("NavigationGeometryInfo", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(NavigationGeometryInfo_Constructor), asCALL_CDECL_OBJFIRST); #endif #ifdef URHO3D_NAVIGATION // NavigationPathPoint::NavigationPathPoint() | Implicitly-declared engine->RegisterObjectBehaviour("NavigationPathPoint", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(NavigationPathPoint_Constructor), asCALL_CDECL_OBJFIRST); #endif // NetworkState::NetworkState() | Implicitly-declared engine->RegisterObjectBehaviour("NetworkState", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(NetworkState_Constructor), asCALL_CDECL_OBJFIRST); // NodeImpl::NodeImpl() | Implicitly-declared engine->RegisterObjectBehaviour("NodeImpl", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(NodeImpl_Constructor), asCALL_CDECL_OBJFIRST); // NodeReplicationState::NodeReplicationState() | Implicitly-declared engine->RegisterObjectBehaviour("NodeReplicationState", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(NodeReplicationState_Constructor), asCALL_CDECL_OBJFIRST); // OcclusionBatch::OcclusionBatch() | Implicitly-declared engine->RegisterObjectBehaviour("OcclusionBatch", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(OcclusionBatch_Constructor), asCALL_CDECL_OBJFIRST); // OcclusionBufferData::OcclusionBufferData() | Implicitly-declared engine->RegisterObjectBehaviour("OcclusionBufferData", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(OcclusionBufferData_Constructor), asCALL_CDECL_OBJFIRST); // OctreeQueryResult::OctreeQueryResult() | File: ../Graphics/OctreeQuery.h engine->RegisterObjectBehaviour("OctreeQueryResult", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(OctreeQueryResult_OctreeQueryResult_void), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_NETWORK // PackageDownload::PackageDownload() | File: ../Network/Connection.h engine->RegisterObjectBehaviour("PackageDownload", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(PackageDownload_PackageDownload_void), asCALL_CDECL_OBJFIRST); #endif #ifdef URHO3D_NETWORK // PackageUpload::PackageUpload() | File: ../Network/Connection.h engine->RegisterObjectBehaviour("PackageUpload", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(PackageUpload_PackageUpload_void), asCALL_CDECL_OBJFIRST); #endif // Particle::Particle() | Implicitly-declared engine->RegisterObjectBehaviour("Particle", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Particle_Constructor), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_URHO2D // Particle2D::Particle2D() | Implicitly-declared engine->RegisterObjectBehaviour("Particle2D", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Particle2D_Constructor), asCALL_CDECL_OBJFIRST); #endif // PerThreadSceneResult::PerThreadSceneResult() | Implicitly-declared engine->RegisterObjectBehaviour("PerThreadSceneResult", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(PerThreadSceneResult_Constructor), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_PHYSICS // PhysicsRaycastResult::PhysicsRaycastResult() | Implicitly-declared engine->RegisterObjectBehaviour("PhysicsRaycastResult", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(PhysicsRaycastResult_Constructor), asCALL_CDECL_OBJFIRST); #endif #ifdef URHO3D_URHO2D // PhysicsRaycastResult2D::PhysicsRaycastResult2D() | Implicitly-declared engine->RegisterObjectBehaviour("PhysicsRaycastResult2D", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(PhysicsRaycastResult2D_Constructor), asCALL_CDECL_OBJFIRST); #endif #ifdef URHO3D_PHYSICS // PhysicsWorldConfig::PhysicsWorldConfig() | File: ../Physics/PhysicsWorld.h engine->RegisterObjectBehaviour("PhysicsWorldConfig", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(PhysicsWorldConfig_PhysicsWorldConfig_void), asCALL_CDECL_OBJFIRST); #endif // RayQueryResult::RayQueryResult() | File: ../Graphics/OctreeQuery.h engine->RegisterObjectBehaviour("RayQueryResult", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(RayQueryResult_RayQueryResult_void), asCALL_CDECL_OBJFIRST); // RefCount::RefCount() | File: ../Container/RefCounted.h engine->RegisterObjectBehaviour("RefCount", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(RefCount_RefCount_void), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_NETWORK // RemoteEvent::RemoteEvent() | Implicitly-declared engine->RegisterObjectBehaviour("RemoteEvent", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(RemoteEvent_Constructor), asCALL_CDECL_OBJFIRST); #endif // RenderPathCommand::RenderPathCommand() | Implicitly-declared engine->RegisterObjectBehaviour("RenderPathCommand", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(RenderPathCommand_Constructor), asCALL_CDECL_OBJFIRST); // RenderTargetInfo::RenderTargetInfo() | Implicitly-declared engine->RegisterObjectBehaviour("RenderTargetInfo", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(RenderTargetInfo_Constructor), asCALL_CDECL_OBJFIRST); // ReplicationState::ReplicationState() | Implicitly-declared engine->RegisterObjectBehaviour("ReplicationState", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ReplicationState_Constructor), asCALL_CDECL_OBJFIRST); // ResourceGroup::ResourceGroup() | File: ../Resource/ResourceCache.h engine->RegisterObjectBehaviour("ResourceGroup", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ResourceGroup_ResourceGroup_void), asCALL_CDECL_OBJFIRST); // ResourceRef::ResourceRef()=default | File: ../Core/Variant.h engine->RegisterObjectBehaviour("ResourceRef", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ResourceRef_ResourceRef_void), asCALL_CDECL_OBJFIRST); // ResourceRefList::ResourceRefList()=default | File: ../Core/Variant.h engine->RegisterObjectBehaviour("ResourceRefList", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ResourceRefList_ResourceRefList_void), asCALL_CDECL_OBJFIRST); // ScenePassInfo::ScenePassInfo() | Implicitly-declared engine->RegisterObjectBehaviour("ScenePassInfo", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ScenePassInfo_Constructor), asCALL_CDECL_OBJFIRST); // SceneReplicationState::SceneReplicationState() | Implicitly-declared engine->RegisterObjectBehaviour("SceneReplicationState", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(SceneReplicationState_Constructor), asCALL_CDECL_OBJFIRST); // ScratchBuffer::ScratchBuffer() | File: ../Graphics/Graphics.h engine->RegisterObjectBehaviour("ScratchBuffer", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ScratchBuffer_ScratchBuffer_void), asCALL_CDECL_OBJFIRST); // ScreenModeParams::ScreenModeParams() | Implicitly-declared engine->RegisterObjectBehaviour("ScreenModeParams", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ScreenModeParams_Constructor), asCALL_CDECL_OBJFIRST); // ShaderParameter::ShaderParameter()=default | File: ../Graphics/ShaderVariation.h engine->RegisterObjectBehaviour("ShaderParameter", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ShaderParameter_ShaderParameter_void), asCALL_CDECL_OBJFIRST); // ShadowBatchQueue::ShadowBatchQueue() | Implicitly-declared engine->RegisterObjectBehaviour("ShadowBatchQueue", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(ShadowBatchQueue_Constructor), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_NAVIGATION // SimpleNavBuildData::SimpleNavBuildData() | File: ../Navigation/NavBuildData.h engine->RegisterObjectBehaviour("SimpleNavBuildData", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(SimpleNavBuildData_SimpleNavBuildData_void), asCALL_CDECL_OBJFIRST); #endif // SourceBatch::SourceBatch() | File: ../Graphics/Drawable.h engine->RegisterObjectBehaviour("SourceBatch", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(SourceBatch_SourceBatch_void), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_URHO2D // SourceBatch2D::SourceBatch2D() | File: ../Urho2D/Drawable2D.h engine->RegisterObjectBehaviour("SourceBatch2D", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(SourceBatch2D_SourceBatch2D_void), asCALL_CDECL_OBJFIRST); #endif // StaticModelGeometryData::StaticModelGeometryData() | Implicitly-declared engine->RegisterObjectBehaviour("StaticModelGeometryData", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(StaticModelGeometryData_Constructor), asCALL_CDECL_OBJFIRST); // StoredLogMessage::StoredLogMessage()=default | File: ../IO/Log.h engine->RegisterObjectBehaviour("StoredLogMessage", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(StoredLogMessage_StoredLogMessage_void), asCALL_CDECL_OBJFIRST); // TechniqueEntry::TechniqueEntry() noexcept | File: ../Graphics/Material.h engine->RegisterObjectBehaviour("TechniqueEntry", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(TechniqueEntry_TechniqueEntry_void), asCALL_CDECL_OBJFIRST); // TrailPoint::TrailPoint()=default | File: ../Graphics/RibbonTrail.h engine->RegisterObjectBehaviour("TrailPoint", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(TrailPoint_TrailPoint_void), asCALL_CDECL_OBJFIRST); // VAnimEventFrame::VAnimEventFrame() | Implicitly-declared engine->RegisterObjectBehaviour("VAnimEventFrame", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(VAnimEventFrame_Constructor), asCALL_CDECL_OBJFIRST); // VAnimKeyFrame::VAnimKeyFrame() | Implicitly-declared engine->RegisterObjectBehaviour("VAnimKeyFrame", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(VAnimKeyFrame_Constructor), asCALL_CDECL_OBJFIRST); #ifdef URHO3D_URHO2D // Vertex2D::Vertex2D() | Implicitly-declared engine->RegisterObjectBehaviour("Vertex2D", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(Vertex2D_Constructor), asCALL_CDECL_OBJFIRST); #endif // VertexBufferDesc::VertexBufferDesc() | Implicitly-declared engine->RegisterObjectBehaviour("VertexBufferDesc", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(VertexBufferDesc_Constructor), asCALL_CDECL_OBJFIRST); // VertexBufferMorph::VertexBufferMorph() | Implicitly-declared engine->RegisterObjectBehaviour("VertexBufferMorph", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(VertexBufferMorph_Constructor), asCALL_CDECL_OBJFIRST); // VertexElement::VertexElement() noexcept | File: ../Graphics/GraphicsDefs.h engine->RegisterObjectBehaviour("VertexElement", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(VertexElement_VertexElement_void), asCALL_CDECL_OBJFIRST); // WindowModeParams::WindowModeParams() | Implicitly-declared engine->RegisterObjectBehaviour("WindowModeParams", asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(WindowModeParams_Constructor), asCALL_CDECL_OBJFIRST); } }
43.297252
178
0.767615
[ "model" ]
3a38dd0cb9b6cd92bd8b747bd59ca70d56eb3940
6,166
cpp
C++
cpp/passes/LILConversionInserter.cpp
veosotano/lil
da2d0774615827d521362ffb731e8abfa3887507
[ "MIT" ]
6
2021-01-02T16:36:28.000Z
2022-01-23T21:50:29.000Z
cpp/passes/LILConversionInserter.cpp
veosotano/lil
27ef338e7e21403acf2b0202f7db8ef662425d44
[ "MIT" ]
null
null
null
cpp/passes/LILConversionInserter.cpp
veosotano/lil
27ef338e7e21403acf2b0202f7db8ef662425d44
[ "MIT" ]
null
null
null
/******************************************************************** * * LIL Is a Language * * AUTHORS: Miro Keller * * COPYRIGHT: ©2020-today: All Rights Reserved * * LICENSE: see LICENSE file * * This file inserts calls to type conversion functions * ********************************************************************/ #include "LILConversionInserter.h" #include "LILConversionDecl.h" #include "LILExpression.h" #include "LILFlowControl.h" #include "LILFunctionCall.h" #include "LILFunctionType.h" #include "LILNodeToString.h" #include "LILMultipleType.h" #include "LILPointerType.h" #include "LILRootNode.h" #include "LILTypeDecl.h" #include "LILVarDecl.h" using namespace LIL; LILConversionInserter::LILConversionInserter() { } LILConversionInserter::~LILConversionInserter() { } void LILConversionInserter::initializeVisit() { if (this->getVerbose()) { std::cerr << "\n\n"; std::cerr << "============================\n"; std::cerr << "=== CONVERSION INSERTING ===\n"; std::cerr << "============================\n\n"; } } void LILConversionInserter::visit(LILNode *node) { this->process(node->shared_from_this()); } void LILConversionInserter::performVisit(std::shared_ptr<LILRootNode> rootNode) { this->setRootNode(rootNode); auto nodes = rootNode->getNodes(); for (const auto & node : nodes) { this->process(node); } } void LILConversionInserter::process(std::shared_ptr<LILNode> node) { this->processChildren(node->getChildNodes()); switch (node->getNodeType()) { case NodeTypeFunctionCall: { auto value = std::static_pointer_cast<LILFunctionCall>(node); this->process(value); break; } default: break; } } void LILConversionInserter::process(std::shared_ptr<LILFunctionCall> fc) { if (fc->isA(FunctionCallTypeNone)) { auto localNode = this->findNodeForName(fc->getName(), fc->getParentNode().get()); if (!localNode) { std::cerr << "!!!!!!! TARGET NODE NOT FOUND FAIL !!!!!!!\n"; return; } auto ty = localNode->getType(); if (ty->isA(TypeTypePointer)) { auto ptrTy = std::static_pointer_cast<LILPointerType>(ty); ty = ptrTy->getArgument(); } if ( !(localNode->isA(NodeTypeVarDecl) || localNode->isA(NodeTypeFunctionDecl)) || !ty || !ty->isA(TypeTypeFunction) ) { std::cerr << "!!!!!!! UNKNOWN TARGET NODE FAIL !!!!!!!\n"; return; } auto fnTy = std::static_pointer_cast<LILFunctionType>(ty); auto fnTyArgs = fnTy->getArguments(); auto fcArgs = fc->getArguments(); if (!fnTy->getIsVariadic() && fcArgs.size() != fnTyArgs.size()) { std::cerr << "!!!!!!! SIZE OF FUNCTION CALL ARGS AND ARGUMENT TYPES WAS NOT THE SAME FAIL !!!!!!!\n"; return; } auto conversions = this->getRootNode()->getConversions(); bool changed = false; std::vector<std::shared_ptr<LILNode>> newArguments; std::vector<std::shared_ptr<LILType>> newArgumentTypes; size_t i = 0; for (auto fcArg : fcArgs) { if (i > fnTyArgs.size()-1) { break; } auto fnTyArg = fnTyArgs[i]; auto fcArgTy = fcArg->getType(); std::shared_ptr<LILType> argTy; LILString argName; if (fnTyArg->isA(NodeTypeType)) { argTy = std::static_pointer_cast<LILType>(fnTyArg); argName = LILString::number((LILUnitI64)i+1); } else if (fnTyArg->isA(NodeTypeVarDecl)) { argTy = fnTyArg->getType(); auto vd = std::static_pointer_cast<LILVarDecl>(fnTyArg); argName = vd->getName(); } if (!argTy) { std::cerr << "ARG TY WAS NULL FAIL !!!!!!!!\n\n"; continue; } if (!fcArgTy) { std::cerr << "FC ARG TY WAS NULL FAIL !!!!!!!!\n\n"; continue; } if (argTy->equalTo(fcArgTy)) { newArguments.push_back(fcArg); newArgumentTypes.push_back(argTy); continue; } else { LILString conversionName = fcArgTy->getStrongTypeName(); if (conversionName.length() == 0) { conversionName = LILNodeToString::stringify(fcArgTy.get()); } conversionName += "_to_"; auto targetTyName = argTy->getStrongTypeName(); if (targetTyName.length() > 0) { conversionName += targetTyName; } else { conversionName += LILNodeToString::stringify(argTy.get()); } if (conversions.count(conversionName)) { auto conv = conversions[conversionName]; changed = true; auto newCall = std::make_shared<LILFunctionCall>(); newCall->setFunctionCallType(FunctionCallTypeConversion); newCall->setName(conv->encodedName()); newCall->addArgument(fcArg); std::vector<std::shared_ptr<LILType>> fcTypes; fcTypes.push_back(fcArgTy); newCall->setArgumentTypes(fcTypes); newCall->setReturnType(argTy); newArguments.push_back(newCall); newArgumentTypes.push_back(argTy); } } i += 1; } if (changed) { fc->setArguments(newArguments); fc->setArgumentTypes(newArgumentTypes); } } } void LILConversionInserter::processChildren(const std::vector<std::shared_ptr<LILNode> > &children) { for (auto it = children.begin(); it!=children.end(); ++it) { this->process((*it)); }; }
32.114583
113
0.520921
[ "vector" ]
3a39e56c415d915783dccfebef8523e3b4fdd300
2,636
hpp
C++
cpp/include/raft/stats/information_criterion.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
null
null
null
cpp/include/raft/stats/information_criterion.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
null
null
null
cpp/include/raft/stats/information_criterion.hpp
kaatish/raft
f487da7f2585e60f0a11aef43ce17c990cc6145a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019-2022, NVIDIA CORPORATION. * * 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. */ /** * This file is deprecated and will be removed in release 22.06. * Please use the cuh version instead. */ #ifndef __INFORMATION_CRIT_H #define __INFORMATION_CRIT_H /** * @file information_criterion.hpp * @brief These information criteria are used to evaluate the quality of models * by balancing the quality of the fit and the number of parameters. * * See: * - AIC: https://en.wikipedia.org/wiki/Akaike_information_criterion * - AICc: https://en.wikipedia.org/wiki/Akaike_information_criterion#AICc * - BIC: https://en.wikipedia.org/wiki/Bayesian_information_criterion */ #pragma once #include <raft/stats/common.hpp> #include <raft/stats/detail/batched/information_criterion.cuh> namespace raft { namespace stats { /** * Compute the given type of information criterion * * @note: it is safe to do the computation in-place (i.e give same pointer * as input and output) * * @param[out] d_ic Information criterion to be returned for each * series (device) * @param[in] d_loglikelihood Log-likelihood for each series (device) * @param[in] ic_type Type of criterion to compute. See IC_Type * @param[in] n_params Number of parameters in the model * @param[in] batch_size Number of series in the batch * @param[in] n_samples Number of samples in each series * @param[in] stream CUDA stream */ template <typename ScalarT, typename IdxT> void information_criterion_batched(ScalarT* d_ic, const ScalarT* d_loglikelihood, IC_Type ic_type, IdxT n_params, IdxT batch_size, IdxT n_samples, cudaStream_t stream) { batched::detail::information_criterion( d_ic, d_loglikelihood, ic_type, n_params, batch_size, n_samples, stream); } } // namespace stats } // namespace raft #endif
36.109589
79
0.66047
[ "model" ]
3a3f18b90010ba91db49eac88ada90672ac88f21
1,621
hh
C++
src/memory/TrackedRam.hh
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
320
2015-06-16T20:32:33.000Z
2022-03-26T17:03:27.000Z
src/memory/TrackedRam.hh
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
2,592
2015-05-30T12:12:21.000Z
2022-03-31T17:16:15.000Z
src/memory/TrackedRam.hh
D15C0DE/openMSX
5119a9657de4b82115c745f670cdc55dc7363133
[ "Naumen", "Condor-1.1", "MS-PL" ]
74
2015-06-18T19:51:15.000Z
2022-03-24T15:09:33.000Z
#ifndef TRACKED_RAM_HH #define TRACKED_RAM_HH #include "Ram.hh" namespace openmsx { // Ram with dirty tracking class TrackedRam { public: // Most methods simply delegate to the internal 'ram' object. TrackedRam(const DeviceConfig& config, const std::string& name, static_string_view description, unsigned size) : ram(config, name, description, size) {} TrackedRam(const XMLElement& xml, unsigned size) : ram(xml, size) {} [[nodiscard]] unsigned getSize() const { return ram.getSize(); } [[nodiscard]] const std::string& getName() const { return ram.getName(); } // Allow read via an explicit read() method or via backdoor access. [[nodiscard]] byte read(unsigned addr) const { return ram[addr]; } [[nodiscard]] const byte& operator[](unsigned addr) const { return ram[addr]; } // Only allow write/clear via an explicit method. void write(unsigned addr, byte value) { writeSinceLastReverseSnapshot = true; ram[addr] = value; } void clear(byte c = 0xff) { writeSinceLastReverseSnapshot = true; ram.clear(c); } // Some write operations are more efficient in bulk. For those this // method can be used. It will mark the ram as dirty on each // invocation, so the resulting pointer (although the same each time) // should not be reused for multiple (distinct) bulk write operations. [[nodiscard]] byte* getWriteBackdoor() { writeSinceLastReverseSnapshot = true; return &ram[0]; } template<typename Archive> void serialize(Archive& ar, unsigned version); private: Ram ram; bool writeSinceLastReverseSnapshot = true; }; } // namespace openmsx #endif
23.838235
71
0.714374
[ "object" ]
3a42ad56fb4b16f3720e5fc70421e20153b30538
26,643
hpp
C++
src/e2/src/ASN1/asn/ber/codec.hpp
shadansari/onos-cu-cp
16cbf4828bd11e4c7319e7a009a26b6f39fde628
[ "Apache-2.0" ]
5
2020-08-31T08:27:42.000Z
2022-03-27T10:39:37.000Z
src/e2/src/ASN1/asn/ber/codec.hpp
shadansari/onos-cu-cp
16cbf4828bd11e4c7319e7a009a26b6f39fde628
[ "Apache-2.0" ]
1
2020-08-28T23:32:17.000Z
2020-08-28T23:32:17.000Z
src/e2/src/ASN1/asn/ber/codec.hpp
shadansari/onos-cu-cp
16cbf4828bd11e4c7319e7a009a26b6f39fde628
[ "Apache-2.0" ]
5
2020-08-27T23:04:34.000Z
2021-11-17T01:49:52.000Z
#pragma once /****************************************************************************** * * Copyright (c) 2019 AT&T Intellectual Property. * Copyright (c) 2018-2019 Nokia. * * 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. * ******************************************************************************/ // Standard Includes: ANSI C/C++, MSA, and Third-Party Libraries // Local Includes: Application specific classes, functions, and libraries #include "asn/elements.hpp" #include "asn/ber/common.hpp" #include "asn/ber/context.hpp" #include "asn/ber/tag.hpp" #include "asn/ber/length.hpp" #include "asn/ber/visitor.hpp" #include "asn/ber/opentype.hpp" namespace asn { namespace ber { /******************************************************************************** pack (X.690) *********************************************************************************/ template <class IE> bool pack(IE const& ie, EncoderCtx& ctx) { ctx.refErrorCtx().reset(); Element<IE>::run(ie, ctx); if (ctx) Tools::bit_accessor::padByte(ctx.refBuffer()); return static_cast<bool>(ctx); } /******************************************************************************** unpack (X.690) *********************************************************************************/ template <class IE> bool unpack(IE& ie, DecoderCtx& ctx) { Element<IE>::run(ie, ctx); if (ctx) Tools::bit_accessor::padByte(ctx.refBuffer()); if(ctx && ctx.refBuffer().getBytesLeft()) { ctx.ie_name(IE::name()); ctx.refErrorCtx().lengthErrorBytes(ctx.refBuffer().getBytesLeft(), 0); } return static_cast<bool>(ctx); } /*************************************************************************************** * ElementType ***************************************************************************************/ template <class IE, class Enabler = void> struct ElementType; /*************************************************************************************** * ExplicitCodec: Codec for elements with EXPLICIT tag ***************************************************************************************/ template <class IE> struct ExplicitCodec { using tag_t = Tag<IE, true>; static bool inline is_matched(tag_value_t _tag) {return _tag == tag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { auto & buffer = ctx.refBuffer(); tag_t::encode(ctx); u8* len_ptr = buffer.advance(1); //reserve for the length Element<typename IE::parent_t>::run(static_cast<typename IE::parent_t const&>(ie), ctx); size_t len = buffer.begin() - len_ptr - 1; if(len > 127) { len_ptr[0] = 0x80; //undefinite length form per X.690 8.1.3.6 uint8_t buff[2] = {0}; // end-of-contents octets (X.690 8.1.5) buffer.putBytes(buff, sizeof(buff)); } else { len_ptr[0] = static_cast<u8>(len); //one byte form per X.690 8.1.3.4 } } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { if(tag_t::value() != tag) ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); else { auto & buffer = ctx.refBuffer(); size_t length = Length::decode(ctx); ASN_DECODER_TRACE("EX<tag=0x%x length=%zu> buffer: %s", static_cast<int>(tag), length, ctx.refBuffer().toString()); if(length == indefinite_length) { Element<typename IE::parent_t>::run(static_cast<typename IE::parent_t&>(ie), ctx); if(ctx) { uint8_t const* data_in = ctx.refBuffer().getBytes(2); if(data_in && (data_in[0] || data_in[1])) { ctx.refErrorCtx().errorWrongEndOfContent(); } } } else { if (buffer.getBytesLeft() < length) { ctx.refErrorCtx().lengthErrorBytes(buffer.getBytesLeft(), length); } else { DecoderCtx::buf_type::pointer end = buffer.end(); buffer.set_end(buffer.begin() + length); Element<typename IE::parent_t>::run(static_cast<typename IE::parent_t&>(ie), ctx); buffer.set_end(end); } } } } }; /*************************************************************************************** * BOOLEAN: Encoding the boolean type (X.690 8.2) ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_BOOLEAN> > { using tag_t = Tag<IE, false>; static bool inline is_matched(tag_value_t tag) {return tag == tag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { tag_t::encode(ctx); Length::encode(1, ctx); if(ie.get()) Tools::put_bytes(0xFF, 1, ctx); else Tools::put_bytes(0, 1, ctx); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { if(tag_t::value() != tag) ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); else { size_t length = Length::decode(ctx); if(length != 1) { ctx.refErrorCtx().sizeRangeError(length, 1, 1); } else { ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); uint8_t value; Tools::get_bytes(value, 1, ctx); ie.set(value > 0); } } } }; /*************************************************************************************** * INTEGER: Encoding the integer type (X.690 8.3) ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_INTEGER> > { using tag_t = Tag<IE, false>; static bool inline is_matched(tag_value_t tag) {return tag == tag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { tag_t::encode(ctx); size_t length = Length::get(ie.get()); Length::encode(length, ctx); Tools::put_bytes(ie.get(), length, ctx); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { if(tag_t::value() != tag) { ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); } else { size_t length = Length::decode(ctx); if(!length || length == indefinite_length) ctx.refErrorCtx().sizeRangeError(length); else { ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); typename IE::value_type value; Tools::get_bytes(value, length, ctx); ie.set(value); } } } }; /*************************************************************************************** * ENUMERATED: Encoding the enumerated type (X.690 8.4) ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_ENUMERATED> > { using tag_t = Tag<IE, false>; static bool inline is_matched(tag_value_t tag) {return tag == tag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { tag_t::encode(ctx); size_t length = Length::get(ie.get()); Length::encode(length, ctx); Tools::put_bytes(ie.get(), length, ctx); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { if(tag_t::value() != tag) ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); else { size_t length = Length::decode(ctx); if(!length || length == indefinite_length) ctx.refErrorCtx().sizeRangeError(length); else { ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); typename IE::value_type value; Tools::get_bytes(value, length, ctx); ie.set(value); } } } }; /*************************************************************************************** * REAL: Encoding the real type (X.690 8.5) ***************************************************************************************/ //missing... /*************************************************************************************** * BIT STRING: Encoding the bitstring type (X.690 8.6) ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<(IE::ie_type == element_type::T_BITSTRING)> > { using tag_t = Tag<IE, false>; using ctag_t = Tag<IE, true>; static bool inline is_matched(tag_value_t tag) {return tag == tag_t::value() || tag == ctag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { tag_t::encode(ctx); uint8_t tail = ie.get_bitqty() % 8; size_t length = ie.get_buffer().size(); Length::encode(length + 1, ctx); auto & buffer = ctx.refBuffer(); buffer.putByte((8 - tail) & 0x7F); if (tail) { buffer.putBytes(ie.get_buffer().data(), length - 1); u8 last_byte = *(ie.get_buffer().data() + length - 1); last_byte <<= 8 - tail; buffer.putBytes(&last_byte, 1); } else { buffer.putBytes(ie.get_buffer().data(), length); } } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { ie.clear(); if(tag_t::value() == tag) { size_t length = Length::decode(ctx); if(!length || length == indefinite_length) { ctx.refErrorCtx().sizeRangeError(length); } else { ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); uint8_t const* data_in = ctx.refBuffer().getBytes(length); if(data_in) { size_t len_bytes = length - 1; size_t bitqty = len_bytes << 3; if((data_in[0] & 0x80) || (bitqty < data_in[0])) { ctx.refErrorCtx().valueRangeError(data_in[0]); } else { bitqty = bitqty - data_in[0]; uint8_t* data_out = ctx.refAllocator().alloc_bytes(len_bytes); if (data_out) { memcpy(data_out, &data_in[1], len_bytes); const u8 shift = bitqty % 8; if (shift) { data_out[len_bytes - 1] >>= 8 - shift; } ie.set_buffer(bitqty, data_out); } else { ctx.refErrorCtx().allocatorNoMem(0, len_bytes); } } } } } else if(ctag_t::value() == tag) { //todo: implement the segmented data ctx.refErrorCtx().errorUnsupported(); } else { ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); } } }; /*************************************************************************************** * OCTET STRING: Encoding the octetstring type (X.690 8.7) * Restricted Character string types (X.690 8.23) ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_OCTETSTRING> > { using tag_t = Tag<IE, false>; using ctag_t = Tag<IE, true>; static bool inline is_matched(tag_value_t tag) {return tag == tag_t::value() || tag == ctag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { tag_t::encode(ctx); size_t length = ie.get().size(); Length::encode(length, ctx); ctx.refBuffer().putBytes(ie.get().data(), length); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { ie.clear(); if(tag_t::value() == tag) { size_t length = Length::decode(ctx); if(length == indefinite_length) { ctx.refErrorCtx().sizeRangeError(length); } else { ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); uint8_t const* data_in = ctx.refBuffer().getBytes(length); if(data_in) { ie.set(length, data_in); } } } else if(ctag_t::value() == tag) { //todo: implement the segmented data ctx.refErrorCtx().errorUnsupported(); } else { ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); } } }; /*************************************************************************************** * NULL: Encoding the null type (X.690 8.8) ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_NULL> > { using tag_t = Tag<IE, false>; static bool inline is_matched(tag_value_t tag) {return tag == tag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { tag_t::encode(ctx); Length::encode(0, ctx); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { if(tag_t::value() != tag) ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); else { size_t length = Length::decode(ctx); if(length) ctx.refErrorCtx().sizeRangeError(length); ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); } } }; /*************************************************************************************** * SEQUENCE: Encoding the sequence type (X.690 8.9) * SET: Encoding the set type (X.690 8.11) ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<(IE::ie_type == element_type::T_SEQUENCE) || (IE::ie_type == element_type::T_SET)> > { using tag_t = Tag<IE, true>; static bool inline is_matched(tag_value_t tag) {return tag == tag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { auto & buffer = ctx.refBuffer(); tag_t::encode(ctx); u8* len_ptr = buffer.advance(1); //reserve for the length VisitorEncoderSeq<IE> ve(ctx, ie); ie.encode(ve); size_t len = buffer.begin() - len_ptr - 1; if(len > 127) { len_ptr[0] = 0x80; //undefinite length form per X.690 8.1.3.6 uint8_t buff[2] = {0}; // end-of-contents octets (X.690 8.1.5) buffer.putBytes(buff, sizeof(buff)); } else len_ptr[0] = static_cast<u8>(len); //one byte form per X.690 8.1.3.4 } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) //todo: support arbitrary order of IEs in SET { if(tag_t::value() != tag) ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); else { VisitorDecoderSeq<IE> vd(ctx, ie); auto & buffer = ctx.refBuffer(); size_t length = Length::decode(ctx); ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); if(length == indefinite_length) { ie.decode(vd); if(ctx) { if(invalid_tag != vd.get_unhandled_tag()) { tag_value_t _tag = vd.get_unhandled_tag(); if(IE::constraint_t::extended) //skip the unknown extension now { tag_value_t const* tag_ptr = &_tag; size_t _length; do { _tag = OpenType::decode(ctx, _length, tag_ptr); tag_ptr = nullptr; } while(ctx && !(_tag == 0 && _length == 0)); } else // it should be the end-of-contents octets (8.1.5) { uint8_t const* data_in = ctx.refBuffer().getBytes(1); if(data_in && (_tag || data_in[0])) { ctx.refErrorCtx().errorWrongEndOfContent(); } } } else { uint8_t const* data_in = ctx.refBuffer().getBytes(2); if(data_in && (data_in[0] || data_in[1])) { ctx.refErrorCtx().errorWrongEndOfContent(); } } } } else { if (buffer.getBytesLeft() < length) { ctx.refErrorCtx().lengthErrorBytes(buffer.getBytesLeft(), length); } else { DecoderCtx::buf_type::pointer end = buffer.end(); buffer.set_end(buffer.begin() + length); ie.decode(vd); tag_value_t _tag = vd.get_unhandled_tag(); if(invalid_tag != _tag) { if(IE::constraint_t::extended) //skip the unknown extension now { tag_value_t const* tag_ptr = &_tag; size_t _length; do { _tag = OpenType::decode(ctx, _length, tag_ptr); tag_ptr = nullptr; } while(ctx && buffer.getBytesLeft() > 0); } else ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); // unexpected tag } buffer.set_end(end); } } } } }; /*************************************************************************************** * SEQUENCE OF: Encoding the sequence-of type (X.690 8.10) * SET OF: Encoding the set-of type (X.690 8.12) ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<(IE::ie_type == element_type::T_SEQUENCE_OF) || (IE::ie_type == element_type::T_SET_OF)> > { using tag_t = Tag<IE, true>; static bool inline is_matched(tag_value_t tag) {return tag == tag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { auto & buffer = ctx.refBuffer(); tag_t::encode(ctx); u8* len_ptr = buffer.advance(1); //reserve for the length for (auto& elem : ie) { Element<typename IE::element_t>::run(elem, ctx); } size_t len = buffer.begin() - len_ptr - 1; if(len > 127) { len_ptr[0] = 0x80; //undefinite length form per X.690 8.1.3.6 uint8_t buff[2] = {0}; // end-of-contents octets (X.690 8.1.5) buffer.putBytes(buff, sizeof(buff)); } else len_ptr[0] = static_cast<u8>(len); //one byte form per X.690 8.1.3.4 } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { ie.clear(); if(tag_t::value() != tag) ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); else { auto & buffer = ctx.refBuffer(); size_t length = Length::decode(ctx); ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); if(length == indefinite_length) { tag_value_t elm_tag = get_tag(ctx); while(ctx && Element<typename IE::element_t>::is_matched(elm_tag)) { add_element(ie, ctx, &elm_tag); elm_tag = get_tag(ctx); } if(ctx) { uint8_t const* data_in = ctx.refBuffer().getBytes(1); if(data_in && (elm_tag || data_in[0])) { ctx.refErrorCtx().errorWrongEndOfContent(); } } } else { if (buffer.getBytesLeft() < length) { ctx.refErrorCtx().lengthErrorBytes(buffer.getBytesLeft(), length); } else { DecoderCtx::buf_type::pointer end = buffer.end(); buffer.set_end(buffer.begin() + length); while(ctx && buffer.getBytesLeft() > 0) add_element(ie, ctx); buffer.set_end(end); } } } } private: static void inline add_element(IE& ie, DecoderCtx& ctx, tag_value_t const* elm_tag = nullptr) { uint8_t* data = ctx.refAllocator().alloc_bytes(sizeof(typename IE::value_type)); if (data) { typename IE::value_type * v = new (data) typename IE::value_type; v->clear(); ie.push_back(*v); Element<typename IE::element_t>::run(*v, ctx, elm_tag); } else { ctx.refErrorCtx().allocatorNoMem(0, sizeof(typename IE::value_type)); } } }; /*************************************************************************************** * CHOICE: Encoding the choice type ***************************************************************************************/ struct ChoiceVisitorEncoder { ChoiceVisitorEncoder(EncoderCtx& ctx) : m_ctx(ctx) {} template<typename IE> bool operator()(IE const& ie) { Element<IE>::run(ie, m_ctx); return static_cast<bool>(m_ctx); } EncoderCtx& m_ctx; }; struct ChoiceVisitorDecoder { ChoiceVisitorDecoder(DecoderCtx& ctx, tag_value_t tag) : m_ctx(ctx), m_tag(tag) {} template<typename IE> bool operator()(IE& ie) { Element<IE>::run(ie, m_ctx, &m_tag); return static_cast<bool>(m_ctx); } DecoderCtx& m_ctx; tag_value_t m_tag; }; template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_CHOICE && IE::asn_identifier_t::class_type == class_type_t::UNSPECIFIED> > { struct Selector { Selector(tag_value_t tag) : m_tag(tag) {} template<typename ELM> void operator()(size_t idx) { if(!m_valid && Element<ELM>::is_matched(m_tag)) { m_index = idx; m_valid = true; } } size_t get_idx() const {return m_index;} bool is_valid() const {return m_valid;} private: tag_value_t m_tag; size_t m_index {0}; bool m_valid {false}; }; static bool inline is_matched(tag_value_t tag) { Selector selector {tag}; IE::enumerate(selector); return selector.is_valid(); } static void inline run(IE const& ie, EncoderCtx& ctx) { ChoiceVisitorEncoder ve(ctx); if(ctx && !ie.encode(ve)) ctx.refErrorCtx().tagError(ie.get_index()); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { ie.clear(); Selector selector {tag}; IE::enumerate(selector); if(!selector.is_valid()) ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); else { ChoiceVisitorDecoder vd {ctx, tag}; if(ctx && !ie.decode(selector.get_idx(), vd)) ctx.refErrorCtx().tagError(ie.get_index()); } } }; template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_CHOICE && IE::asn_identifier_t::class_type != class_type_t::UNSPECIFIED> > { static bool inline is_matched(tag_value_t _tag) {return ExplicitCodec<IE>::is_matched(_tag);} static void inline run(IE const& ie, EncoderCtx& ctx) { ExplicitCodec<IE>::run(ie, ctx); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { ExplicitCodec<IE>::run(ie, ctx, tag); } }; /*************************************************************************************** * IE_OBJECT_IDENTIFIER: Encoding the object identifier type ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_OBJECTIDENTIFIER> > { using tag_t = Tag<IE, false>; static bool inline is_matched(tag_value_t _tag) {return _tag == tag_t::value();} static void inline run(IE const& ie, EncoderCtx& ctx) { tag_t::encode(ctx); size_t length = ie.get().size(); Length::encode(length, ctx); ctx.refBuffer().putBytes(ie.get().data(), length); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { ie.clear(); if(tag_t::value() == tag) { size_t length = Length::decode(ctx); if(!length || length == indefinite_length) { ctx.refErrorCtx().sizeRangeError(length); } else { ASN_DECODER_TRACE("IE<type=%d name=%s tag=0x%x length=%zu> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), static_cast<int>(tag), length, ctx.refBuffer().toString()); uint8_t const* data_in = ctx.refBuffer().getBytes(length); if(data_in) { ie.set(length, data_in); } } } else { ctx.refErrorCtx().tagError(static_cast<uint32_t>(tag)); } } }; /*************************************************************************************** * T_OBJFIELD_FTV ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_OBJFIELD_FTV> > { using tag_t = Tag<IE, false>; static bool inline is_matched(tag_value_t _tag) {return _tag == tag_t::value();} }; /*************************************************************************************** * T_OBJFIELD_TF ***************************************************************************************/ template <class IE> struct ElementType<IE, std::enable_if_t<IE::ie_type == element_type::T_OBJFIELD_TF> > { struct Selector { Selector(tag_value_t tag) : m_tag(tag) {} template<typename ELM> void operator()(size_t idx) { if(Element<ELM>::is_matched(m_tag)) { m_index = idx; m_valid = true; } } size_t get_idx() const {return m_index;} bool is_valid() const {return m_valid;} private: tag_value_t m_tag; size_t m_index {0}; bool m_valid {false}; }; static bool inline is_matched(tag_value_t tag) { Selector selector(tag); IE::enumerate(selector); return selector.is_valid(); } }; /*************************************************************************************** * Identifier ***************************************************************************************/ template <class IE, class Enabler = void> struct Identifier { static bool inline is_matched(tag_value_t _tag) { return ElementType<IE>::is_matched(_tag); } static void inline run(IE const& ie, EncoderCtx& ctx) { ElementType<IE>::run(ie, ctx); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { ElementType<IE>::run(ie, ctx, tag); } }; template <class IE> struct Identifier<IE, std::enable_if_t<IE::asn_identifier_t::tag_type == tag_type_t::EXPLICIT> > { static bool inline is_matched(tag_value_t _tag) {return ExplicitCodec<IE>::is_matched(_tag);} static void inline run(IE const& ie, EncoderCtx& ctx) { ExplicitCodec<IE>::run(ie, ctx); } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t tag) { ExplicitCodec<IE>::run(ie, ctx, tag); } }; /*************************************************************************************** * COMMON: Element ***************************************************************************************/ template <class IE> struct Element { static bool inline is_matched(tag_value_t _tag) { return Identifier<IE>::is_matched(_tag); } static void inline run(IE const& ie, EncoderCtx& ctx) { if (ctx) { ASN_ENCODER_TRACE("IE<type=%d name=%s> buffer: %s", static_cast<int>(IE::ie_type), IE::name(), ctx.refBuffer().toString()); ctx.ie_name(IE::name()); Identifier<IE>::run(ie, ctx); } } static void inline run(IE& ie, DecoderCtx& ctx, tag_value_t const* tag_ptr = nullptr) { if (ctx) { ctx.ie_name(IE::name()); tag_value_t tag = tag_ptr ? *tag_ptr : get_tag(ctx); if(ctx) Identifier<IE>::run(ie, ctx, tag); } } }; } //namespace ber } //namespace asn
28.58691
182
0.563337
[ "object" ]
3a4465dab67ad95485766f4f11dcf080576d67de
844
cpp
C++
1170-compare-strings-by-frequency-of-the-smallest-character/1170-compare-strings-by-frequency-of-the-smallest-character.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
2
2022-01-02T19:15:00.000Z
2022-01-05T21:12:24.000Z
1170-compare-strings-by-frequency-of-the-smallest-character/1170-compare-strings-by-frequency-of-the-smallest-character.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
null
null
null
1170-compare-strings-by-frequency-of-the-smallest-character/1170-compare-strings-by-frequency-of-the-smallest-character.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
1
2022-03-11T17:11:07.000Z
2022-03-11T17:11:07.000Z
class Solution { public: int helper(string &word){ vector<int> arr(26,0); for(char &ch : word){ arr[ch-'a']++; } for(int i=0; i<26; ++i){ if(arr[i]!=0){ return arr[i]; } } return -1; } vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) { vector<int> ans; vector<int> v; for(auto &w : words){ int freq = helper(w); v.push_back(freq); } sort(v.begin(), v.end()); int size = v.size(); for(auto &q : queries){ int freq = helper(q); int idx = upper_bound(v.begin(), v.end(), freq) - v.begin(); ans.push_back(size-idx); } return ans; } };
24.114286
87
0.422986
[ "vector" ]
3a4b1623a00e4d297d2c9b06b9900bc004e7a03a
5,322
cc
C++
seurat/component/transform_component.cc
Asteur/vrhelper
7b20ac69265ca7390a6c7f52a4f25b0fe87d0b53
[ "Apache-2.0" ]
819
2018-05-04T20:43:55.000Z
2022-03-22T01:21:24.000Z
seurat/component/transform_component.cc
mebalzer/seurat
78c1293debdd2744cba11395024812f277f613f7
[ "Apache-2.0" ]
35
2018-05-05T03:50:16.000Z
2019-11-04T22:56:02.000Z
seurat/component/transform_component.cc
mebalzer/seurat
78c1293debdd2744cba11395024812f277f613f7
[ "Apache-2.0" ]
88
2018-05-04T20:53:42.000Z
2022-03-05T03:50:07.000Z
/* Copyright 2017 Google Inc. 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 "seurat/component/transform_component.h" #include "ion/gfx/node.h" #include "ion/math/matrix.h" #include "seurat/base/ion_util_no_gl.h" #include "seurat/base/structured_io.h" #include "seurat/component/component.h" #include "seurat/component/renderable.h" using ion::math::Matrix4f; namespace seurat { namespace component { namespace { class TransformRenderable : public Renderable { public: explicit TransformRenderable(const TransformComponent* transform_component) : transform_component_(transform_component) { CHECK_NOTNULL(transform_component); } ~TransformRenderable() override = default; Properties GetProperties() const override { Properties properties; const Component* child = transform_component_->GetChild(); if (child) { // Transform the child's AABB. const Matrix4f parent_from_child = transform_component_->GetParentFromChildMatrix(); properties.bounding_box = base::ProjectAABB( parent_from_child, child->GetRenderable()->GetProperties().bounding_box); } return properties; } NodeSet GetRenderNodes(const RenderingContext& context) override { const Component* child = transform_component_->GetChild(); if (child) { return child->GetRenderable()->GetRenderNodes(context); } else { return NodeSet(); } } void Update(const ViewState& view_state) override { const Component* child = transform_component_->GetChild(); if (!child) { return; } ViewState transformed_view_state = view_state; const Matrix4f parent_from_child_matrix = transform_component_->GetParentFromChildMatrix(); transformed_view_state.left_clip_from_component_matrix = transformed_view_state.left_clip_from_component_matrix * parent_from_child_matrix; transformed_view_state.right_clip_from_component_matrix = transformed_view_state.right_clip_from_component_matrix * parent_from_child_matrix; transformed_view_state.left_eye_from_component_matrix = transformed_view_state.left_eye_from_component_matrix * parent_from_child_matrix; transformed_view_state.right_eye_from_component_matrix = transformed_view_state.right_eye_from_component_matrix * parent_from_child_matrix; child->GetRenderable()->Update(transformed_view_state); } private: const TransformComponent* transform_component_; }; } // namespace REGISTER_SEURAT_COMPONENT(TransformComponent); TransformComponent::TransformComponent(std::string label) : Component(std::move(label)), parent_from_child_matrix_(Matrix4f::Identity()), child_(nullptr), renderable_(new TransformRenderable(this)) {} TransformComponent::TransformComponent(std::string label, const Matrix4f& parent_from_child_matrix, std::unique_ptr<const Component> child) : Component(std::move(label)), parent_from_child_matrix_(parent_from_child_matrix), child_(std::move(child)), renderable_(new TransformRenderable(this)) {} // static std::unique_ptr<const Component> TransformComponent::Create( std::string label, base::StructureSource* source) { const Matrix4f parent_from_child_matrix = source->ReadMatrix<Matrix4f>(); std::unique_ptr<const Component> child; const bool has_child = source->ReadPod<bool>(); if (has_child) { child = Component::Create(source); } return std::unique_ptr<const Component>(new TransformComponent( std::move(label), parent_from_child_matrix, std::move(child))); } void TransformComponent::WriteInternal(base::StructureSink* sink) const { sink->WriteMatrix(parent_from_child_matrix_); sink->WritePod<bool>(child_ ? true : false); if (child_) { child_->Write(sink); } } bool TransformComponent::operator==(const Component& other) const { if (!IsComponentEqualTo(other)) { return false; } const TransformComponent& other_transform = static_cast<const TransformComponent&>(other); if (other_transform.parent_from_child_matrix_ != parent_from_child_matrix_) { return false; } if (child_ && (*child_ != *other_transform.child_)) { return false; } return true; } // static std::unique_ptr<const TransformComponent> TransformComponent::CreateFromComponent( std::string transformed_label, const ion::math::Matrix4f& matrix, std::unique_ptr<const Component> component) { std::unique_ptr<const TransformComponent> transformed_component( new TransformComponent(std::move(transformed_label), matrix, std::move(component))); return transformed_component; } } // namespace component } // namespace seurat
33.471698
80
0.733935
[ "transform" ]
3a560aacbcec326db8383f3234c3a104558317c7
5,314
hh
C++
neb/inc/com/centreon/broker/neb/node_events_stream.hh
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/broker/neb/node_events_stream.hh
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/broker/neb/node_events_stream.hh
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2015 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #ifndef CCB_NEB_NODE_EVENTS_STREAM_HH # define CCB_NEB_NODE_EVENTS_STREAM_HH # include <vector> # include <QString> # include <QHash> # include <QPair> # include "com/centreon/broker/io/stream.hh" # include "com/centreon/broker/misc/shared_ptr.hh" # include "com/centreon/broker/namespace.hh" # include "com/centreon/broker/persistent_cache.hh" # include "com/centreon/broker/extcmd/command_request.hh" # include "com/centreon/broker/neb/acknowledgement.hh" # include "com/centreon/broker/neb/downtime.hh" # include "com/centreon/broker/neb/downtime_scheduler.hh" # include "com/centreon/broker/neb/host.hh" # include "com/centreon/broker/neb/service.hh" # include "com/centreon/broker/neb/node_id.hh" # include "com/centreon/broker/time/timeperiod.hh" # include "com/centreon/broker/neb/node_cache.hh" # include "com/centreon/broker/neb/downtime_map.hh" CCB_BEGIN() namespace neb { /** * @class node_events_stream node_events_stream.hh "com/centreon/broker/neb/node_events_stream.hh" * @brief Node events stream. * * Manage node events: downtime, acks, etc. */ class node_events_stream : public io::stream { public: node_events_stream( std::string const& name, misc::shared_ptr<persistent_cache> cache, std::string const& config_file); ~node_events_stream(); bool read(misc::shared_ptr<io::data>& d, time_t deadline); void update(); int write(misc::shared_ptr<io::data> const& d); void parse_command( extcmd::command_request const& exc, io::stream& stream); void set_timeperiods( QHash<QString, time::timeperiod::ptr> const& tps); private: node_events_stream(node_events_stream const& other); node_events_stream& operator=(node_events_stream const& other); misc::shared_ptr<persistent_cache> _cache; std::string _config_file; QString _name; // Timeperiods. QHash<QString, time::timeperiod::ptr> _timeperiods; // Host/Service caches. node_cache _node_cache; void _process_host_status( neb::host_status const& hst); void _process_service_status( neb::service_status const& sst); void _update_downtime( neb::downtime const& dwn); void _remove_expired_acknowledgement( node_id node, timestamp check_time, short prev_state, short state); void _trigger_floating_downtime(node_id node, short state); // Acks and downtimes caches. QHash<node_id, neb::acknowledgement> _acknowledgements; std::vector<neb::downtime> _incomplete_downtime; downtime_map _downtimes; downtime_scheduler _downtime_scheduler; // Parsing methods. enum ack_type { ack_host = 0, ack_service }; enum down_type { down_service = 1, down_host = 2, down_host_service = 3 }; void _parse_ack( ack_type type, const char* args, io::stream& stream); void _parse_remove_ack( ack_type type, const char* args, io::stream& stream); void _parse_downtime( down_type type, const char* args, io::stream& stream); void _parse_remove_downtime( down_type type, const char* args, io::stream& stream); void _schedule_downtime( downtime const& dwn); void _spawn_recurring_downtime( timestamp when, downtime const& dwn); // Downtime utility methods. void _register_downtime(downtime const& d, io::stream* stream); void _delete_downtime(downtime const& d, timestamp ts, io::stream* stream); // Cache and config loading. void _check_downtime_timeperiod_consistency(); void _load_config_file(); void _load_cache(); void _process_loaded_event(misc::shared_ptr<io::data> const& d); void _apply_config_downtimes(); void _save_cache(); }; } CCB_END() #endif // !CCB_NEB_NODE_EVENTS_STREAM_HH
34.283871
101
0.596726
[ "vector" ]
3a57ca642c17ca8ca37bba18e93b5c7d326abe81
386
cpp
C++
cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Jacobi_makeGivens.cpp
TANHAIYU/Self-calibration-using-Homography-Constraints
a3e7efa8cc3de1be1489891d81c0fb00b5b98777
[ "BSD-3-Clause" ]
2
2020-03-17T16:34:31.000Z
2020-06-17T18:30:13.000Z
cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Jacobi_makeGivens.cpp
TANHAIYU/planecalib
a3e7efa8cc3de1be1489891d81c0fb00b5b98777
[ "BSD-3-Clause" ]
null
null
null
cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Jacobi_makeGivens.cpp
TANHAIYU/planecalib
a3e7efa8cc3de1be1489891d81c0fb00b5b98777
[ "BSD-3-Clause" ]
null
null
null
#include <Eigen/Dense> #include <iostream> using namespace Eigen; using namespace std; int main(int, char**) { cout.precision(3); Vector2f v = Vector2f::Random(); JacobiRotation<float> G; G.makeGivens(v.x(), v.y()); cout << "Here is the vector v:" << endl << v << endl; v.applyOnTheLeft(0, 1, G.adjoint()); cout << "Here is the vector J' * v:" << endl << v << endl; return 0; }
21.444444
58
0.634715
[ "vector" ]
3a592331ed49c0baf70d1b1f1dc237d27fdfbdf0
1,401
cxx
C++
panda/src/windisplay/winDetectDx9.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/windisplay/winDetectDx9.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/windisplay/winDetectDx9.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: winDetectDx9.cxx // Created by: aignacio (18Jan07) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "pandabase.h" #ifdef HAVE_DX9 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN 1 #endif #include <d3d9.h> #include "graphicsStateGuardian.h" #include "graphicsPipe.h" #include "displaySearchParameters.h" #define Direct3DCreate Direct3DCreate9 typedef LPDIRECT3D9 (WINAPI *DIRECT3DCREATE9)(UINT SDKVersion); typedef LPDIRECT3D9 DIRECT_3D; typedef D3DCAPS9 D3DCAPS; typedef D3DADAPTER_IDENTIFIER9 D3DADAPTER_IDENTIFIER; typedef LPDIRECT3DDEVICE9 DIRECT_3D_DEVICE; typedef DIRECT3DCREATE9 DIRECT_3D_CREATE; static char *d3d_dll_name = "d3d9.dll"; static char *direct_3d_create_function_name = "Direct3DCreate9"; // include common source code #include "winDetectDx.h" int dx9_display_information (DisplaySearchParameters &display_search_parameters, DisplayInformation *display_information) { return get_display_information (display_search_parameters, display_information); } #endif
28.02
123
0.723055
[ "3d" ]
3a599e6c5ff8c83043c89612c28d9e36f184f38d
3,505
cpp
C++
gtsam_unstable/geometry/tests/testEvent.cpp
acxz/gtsam
cd3854a1f6db923d40ecf3ced56bafbe339d1b3c
[ "BSD-3-Clause" ]
null
null
null
gtsam_unstable/geometry/tests/testEvent.cpp
acxz/gtsam
cd3854a1f6db923d40ecf3ced56bafbe339d1b3c
[ "BSD-3-Clause" ]
null
null
null
gtsam_unstable/geometry/tests/testEvent.cpp
acxz/gtsam
cd3854a1f6db923d40ecf3ced56bafbe339d1b3c
[ "BSD-3-Clause" ]
null
null
null
/* ---------------------------------------------------------------------------- * GTSAM Copyright 2010, Georgia Tech Research Corporation, * Atlanta, Georgia 30332-0415 * All Rights Reserved * Authors: Frank Dellaert, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file testEvent.cpp * @brief Unit tests for space time "Event" * @author Frank Dellaert * @author Jay Chakravarty * @date December 2014 */ #include <gtsam/base/numericalDerivative.h> #include <gtsam/nonlinear/Expression.h> #include <gtsam_unstable/geometry/Event.h> #include <CppUnitLite/TestHarness.h> #include <boost/bind/bind.hpp> using namespace boost::placeholders; using namespace std; using namespace gtsam; // Create a noise model for the TOA error static const double ms = 1e-3; static const double cm = 1e-2; typedef Eigen::Matrix<double, 1, 1> Vector1; static SharedNoiseModel model(noiseModel::Isotropic::Sigma(1, 0.5 * ms)); static const double timeOfEvent = 25; static const Event exampleEvent(timeOfEvent, 1, 0, 0); static const Point3 microphoneAt0(0, 0, 0); static const double kSpeedOfSound = 340; static const TimeOfArrival kToa(kSpeedOfSound); //***************************************************************************** TEST(Event, Constructor) { const double t = 0; Event actual(t, 201.5 * cm, 201.5 * cm, (212 - 45) * cm); } //***************************************************************************** TEST(Event, Toa1) { Event event(0, 1, 0, 0); double expected = 1. / kSpeedOfSound; EXPECT_DOUBLES_EQUAL(expected, kToa(event, microphoneAt0), 1e-9); } //***************************************************************************** TEST(Event, Toa2) { double expectedTOA = timeOfEvent + 1. / kSpeedOfSound; EXPECT_DOUBLES_EQUAL(expectedTOA, kToa(exampleEvent, microphoneAt0), 1e-9); } //************************************************************************* TEST(Event, Derivatives) { Matrix14 actualH1; Matrix13 actualH2; kToa(exampleEvent, microphoneAt0, actualH1, actualH2); Matrix expectedH1 = numericalDerivative11<double, Event>( boost::bind(kToa, _1, microphoneAt0, boost::none, boost::none), exampleEvent); EXPECT(assert_equal(expectedH1, actualH1, 1e-8)); Matrix expectedH2 = numericalDerivative11<double, Point3>( boost::bind(kToa, exampleEvent, _1, boost::none, boost::none), microphoneAt0); EXPECT(assert_equal(expectedH2, actualH2, 1e-8)); } //***************************************************************************** TEST(Event, Expression) { Key key = 12; Expression<Event> event_(key); Expression<Point3> knownMicrophone_(microphoneAt0); // constant expression Expression<double> expression(kToa, event_, knownMicrophone_); Values values; values.insert(key, exampleEvent); double expectedTOA = timeOfEvent + 1. / kSpeedOfSound; EXPECT_DOUBLES_EQUAL(expectedTOA, expression.value(values), 1e-9); } //***************************************************************************** TEST(Event, Retract) { Event event, expected(1, 2, 3, 4); Vector4 v; v << 1, 2, 3, 4; EXPECT(assert_equal(expected, event.retract(v))); } //***************************************************************************** int main() { TestResult tr; return TestRegistry::runAllTests(tr); } //*****************************************************************************
33.066038
80
0.560057
[ "geometry", "model" ]
3a5a7a0e3eaf14eff0cb7da20c21384fb1b827ad
8,986
cc
C++
libtest/server_container.cc
riddick2z/libmemcached
d6c35953c08a3d5529f1d2633157ec97449a9ca7
[ "BSD-3-Clause" ]
null
null
null
libtest/server_container.cc
riddick2z/libmemcached
d6c35953c08a3d5529f1d2633157ec97449a9ca7
[ "BSD-3-Clause" ]
null
null
null
libtest/server_container.cc
riddick2z/libmemcached
d6c35953c08a3d5529f1d2633157ec97449a9ca7
[ "BSD-3-Clause" ]
null
null
null
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Data Differential YATL (i.e. libtest) library * * Copyright (C) 2012 Data Differential, http://datadifferential.com/ * * 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. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "libtest/yatlcon.h" #include "libtest/common.h" #include <cerrno> #include <cstdlib> #include <iostream> #include <algorithm> #include <functional> #include <locale> // trim from end static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } namespace libtest { Server* server_startup_st::last() { return servers.back(); } void server_startup_st::push_server(Server *arg) { servers.push_back(arg); std::string server_config_string; if (arg->has_socket()) { server_config_string+= "--socket="; server_config_string+= '"'; server_config_string+= arg->socket(); server_config_string+= '"'; server_config_string+= " "; } else { libtest::vchar_t port_str; port_str.resize(NI_MAXSERV); snprintf(&port_str[0], port_str.size(), "%u", int(arg->port())); server_config_string+= "--server="; server_config_string+= arg->hostname(); server_config_string+= ":"; server_config_string+= &port_str[0]; server_config_string+= " "; } server_list+= server_config_string; } Server* server_startup_st::pop_server() { Server *tmp= servers.back(); servers.pop_back(); return tmp; } // host_to_shutdown => host number to shutdown in array bool server_startup_st::shutdown(uint32_t host_to_shutdown) { if (servers.size() > host_to_shutdown) { Server* tmp= servers[host_to_shutdown]; if (tmp and tmp->kill() == false) { } else { return true; } } return false; } void server_startup_st::clear() { std::for_each(servers.begin(), servers.end(), DeleteFromVector()); servers.clear(); } bool server_startup_st::check() const { bool success= true; for (std::vector<Server *>::const_iterator iter= servers.begin(); iter != servers.end(); ++iter) { if ((*iter)->check() == false) { success= false; } } return success; } bool server_startup_st::shutdown() { bool success= true; for (std::vector<Server *>::iterator iter= servers.begin(); iter != servers.end(); ++iter) { if ((*iter)->has_pid() and (*iter)->kill() == false) { Error << "Unable to kill:" << *(*iter); success= false; } } return success; } void server_startup_st::restart() { for (std::vector<Server *>::iterator iter= servers.begin(); iter != servers.end(); ++iter) { (*iter)->start(); } } #define MAGIC_MEMORY 123575 server_startup_st::server_startup_st() : _magic(MAGIC_MEMORY), _socket(false), _sasl(false), udp(0), _servers_to_run(5) { } server_startup_st::~server_startup_st() { clear(); } bool server_startup_st::validate() { return _magic == MAGIC_MEMORY; } bool server_startup(server_startup_st& construct, const std::string& server_type, in_port_t try_port, const char *argv[]) { return construct.start_server(server_type, try_port, argv); } libtest::Server* server_startup_st::create(const std::string& server_type, in_port_t try_port, const bool is_socket) { libtest::Server *server= NULL; if (is_socket == false) { if (try_port <= 0) { throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "was passed the invalid port number %d", int(try_port)); } } if (is_socket) { if (server_type.compare("memcached") == 0) { server= build_memcached_socket("localhost", try_port); } else { Error << "Socket is not support for server: " << server_type; return NULL; } } else if (server_type.compare("gearmand") == 0) { server= build_gearmand("localhost", try_port); } else if (server_type.compare("hostile-gearmand") == 0) { server= build_gearmand("localhost", try_port, "gearmand/hostile_gearmand"); } else if (server_type.compare("drizzled") == 0) { if (DRIZZLED_BINARY) { if (HAVE_LIBDRIZZLE) { server= build_drizzled("localhost", try_port); } } } else if (server_type.compare("blobslap_worker") == 0) { if (GEARMAND_BINARY) { if (GEARMAND_BLOBSLAP_WORKER) { if (HAVE_LIBGEARMAN) { server= build_blobslap_worker(try_port); } } } } else if (server_type.compare("memcached") == 0) { if (HAVE_MEMCACHED_BINARY) { server= build_memcached("localhost", try_port); } } return server; } class ServerPtr { public: ServerPtr(libtest::Server* server_): _server(server_) { } ~ServerPtr() { delete _server; } void reset() { delete _server; _server= NULL; } libtest::Server* release(libtest::Server* server_= NULL) { libtest::Server* tmp= _server; _server= server_; return tmp; } libtest::Server* operator->() const { return _server; } libtest::Server* operator&() const { return _server; } private: libtest::Server* _server; }; bool server_startup_st::_start_server(const bool is_socket, const std::string& server_type, in_port_t try_port, const char *argv[]) { try { ServerPtr server(create(server_type, try_port, is_socket)); if (&server == NULL) { Error << "Could not allocate server: " << server_type; return false; } /* We will now cycle the server we have created. */ if (server->cycle() == false) { Error << "Could not start up server " << &server; return false; } server->init(argv); #if 0 if (false) { Out << "Pausing for startup, hit return when ready."; std::string gdb_command= server->base_command(); getchar(); } else #endif if (server->start() == false) { return false; } else { { #if defined(DEBUG) if (DEBUG) { Outn(); Out << "STARTING SERVER(pid:" << server->pid() << "): " << server->running(); Outn(); } #endif } } push_server(server.release()); if (is_socket and &server) { set_default_socket(server->socket().c_str()); } } catch (const libtest::disconnected& err) { if (fatal::is_disabled() == false and try_port != LIBTEST_FAIL_PORT) { stream::cerr(err.file(), err.line(), err.func()) << err.what(); return false; } } catch (const libtest::__test_result& err) { stream::cerr(err.file(), err.line(), err.func()) << err.what(); return false; } catch (const std::exception& err) { Error << err.what(); return false; } catch (...) { Error << "error occured while creating server: " << server_type; return false; } return true; } bool server_startup_st::start_server(const std::string& server_type, in_port_t try_port, const char *argv[]) { return _start_server(false, server_type, try_port, argv); } bool server_startup_st::start_socket_server(const std::string& server_type, const in_port_t try_port, const char *argv[]) { return _start_server(true, server_type, try_port, argv); } std::string server_startup_st::option_string() const { std::string temp= server_list; rtrim(temp); return temp; } } // namespace libtest
22.807107
121
0.637881
[ "vector" ]
3a5c2f8049a6c51874fdbb9b341bfa7f6e26ca5e
8,965
cpp
C++
sksevr_plugin/plugin/FormDB.cpp
prodigious-moustachio/skyui-vr
932dae1d9e32d375cf874dab87a1944e15f3b932
[ "MIT" ]
null
null
null
sksevr_plugin/plugin/FormDB.cpp
prodigious-moustachio/skyui-vr
932dae1d9e32d375cf874dab87a1944e15f3b932
[ "MIT" ]
null
null
null
sksevr_plugin/plugin/FormDB.cpp
prodigious-moustachio/skyui-vr
932dae1d9e32d375cf874dab87a1944e15f3b932
[ "MIT" ]
null
null
null
#include <filesystem> #include <assert.h> #include "FormDB.h" #include "skse64/GameForms.h" #include "skse64/ScaleformValue.h" #include "skse64/ScaleformCallbacks.h" #include "skse64/ScaleformAPI.h" #include "skse64/Hooks_Scaleform.h" #include "skse64/ScaleformMovie.h" #include "skse64/GameExtraData.h" #include "skse64/ScaleformExtendedData.h" #include "skse64/GameRTTI.h" #include "Keyboard.h" lua_State* g_lua = nullptr; namespace FormDB { void Form_SetInt(UInt32 formID, const char* fieldName, SInt32 val) { const char* func_name = "Form_SetVal"; lua_getglobal(g_lua, func_name); // Grab the lua function lua_pushinteger(g_lua, formID); // Push the params lua_pushstring(g_lua, fieldName); lua_pushinteger(g_lua, val); // Call and print any errors if (lua_pcall(g_lua, 3, 1, 0) != 0) _ERROR("Error running `%s`: %s", func_name, lua_tostring(g_lua, -1)); // Pop the return value // The lua function actually returns the updated table. // Since there isn't a great way to interact with it in C/C++, // we're just going to discard it. lua_pop(g_lua, 1); } void Form_SetInt(TESForm* form, BSFixedString fieldName, SInt32 val) { Form_SetInt(form->formID, fieldName.c_str(), val); } void Papyrus_Form_SetInt(StaticFunctionTag*, TESForm* form, BSFixedString fieldName, SInt32 val) { Form_SetInt(form->formID, fieldName.c_str(), val); } SInt32 Form_GetInt(UInt32 formID, const char* fieldName, SInt32 default) { const char* func_name = "Form_GetVal"; lua_getglobal(g_lua, func_name); // Grab the lua function lua_pushinteger(g_lua, formID); // Push the params lua_pushstring(g_lua, fieldName); lua_pushinteger(g_lua, default); // Call and print any errors if (lua_pcall(g_lua, 3, 1, 0) != 0) _ERROR("Error running `%s`: %s", func_name, lua_tostring(g_lua, -1)); if (!lua_isnumber(g_lua, -1)) _ERROR("function `%s` did not return a number", func_name); // Get the fetch result SInt32 val = lua_tointeger(g_lua, -1); lua_pop(g_lua, 1); // Cleanup the result from the stack return val; } SInt32 Form_GetInt(TESForm* form, BSFixedString fieldName, SInt32 default) { return Form_GetInt(form->formID, fieldName.c_str(), default); } SInt32 Papyrus_Form_GetInt(StaticFunctionTag*, TESForm* form, BSFixedString fieldName, SInt32 default) { return Form_GetInt(form->formID, fieldName.c_str(), default); } void Form_SetBool(UInt32 formID, const char* fieldName, bool val) { const char* func_name = "Form_SetVal"; lua_getglobal(g_lua, func_name); // Grab the lua function lua_pushinteger(g_lua, formID); // Push the params lua_pushstring(g_lua, fieldName); lua_pushboolean(g_lua, val); if (lua_pcall(g_lua, 3, 1, 0) != 0) _ERROR("Error running `%s`: %s", func_name, lua_tostring(g_lua, -1)); lua_pop(g_lua, 1); } void Form_SetBool(TESForm* form, BSFixedString fieldName, bool val) { Form_SetBool(form->formID, fieldName.c_str(), val); } void Papyrus_Form_SetBool(StaticFunctionTag*, TESForm* form, BSFixedString fieldName, bool val) { //_MESSAGE("[PIH]Papyrus -> DLL: SetBool, %x, %s, %s", form->formID, fieldName.c_str(), val ? "true" : "false"); Form_SetBool(form->formID, fieldName.c_str(), val); } bool Form_GetBool(UInt32 formID, const char* fieldName, bool default) { const char* func_name = "Form_GetVal"; lua_getglobal(g_lua, func_name); // Grab the lua function lua_pushinteger(g_lua, formID); // Push the params lua_pushstring(g_lua, fieldName); lua_pushboolean(g_lua, default); // Call and print any errors if (lua_pcall(g_lua, 3, 1, 0) != 0) _ERROR("Error running `%s`: %s", func_name, lua_tostring(g_lua, -1)); if (!lua_isboolean(g_lua, -1)) _ERROR("function `%s` did not return a boolean", func_name); // Get the fetch result bool val = lua_toboolean(g_lua, -1); lua_pop(g_lua, 1); // Cleanup the result from the stack return val; } bool Form_GetBool(TESForm* form, BSFixedString fieldName, bool default) { //_MESSAGE("[PIH]Papyrus -> DLL: GetBool, %x, %s, %s", form->formID, fieldName.c_str(), default ? "true" : "false"); bool val = Form_GetBool(form->formID, fieldName.c_str(), default); //_MESSAGE("[PIH]Papyrus -> DLL: GetBool, %x, %s, %s -> %s", form->formID, fieldName.c_str(), default ? "true" : "false", val ? "true" : "false"); return val; } bool Papyrus_Form_GetBool(StaticFunctionTag*, TESForm* form, BSFixedString fieldName, bool default) { return Form_GetBool(form->formID, fieldName.c_str(), default); } void Form_RemoveField(UInt32 formID, const char* fieldName) { const char* func_name = "Form_RemoveField"; lua_getglobal(g_lua, func_name); // Grab the lua function lua_pushinteger(g_lua, formID); // Push the params lua_pushstring(g_lua, fieldName); // Call and print any errors if (lua_pcall(g_lua, 2, 0, 0) != 0) _ERROR("Error running `%s`: %s", func_name, lua_tostring(g_lua, -1)); } void Form_RemoveField(TESForm* form, BSFixedString fieldName) { Form_RemoveField(form->formID, fieldName.c_str()); } void Papyrus_Form_RemoveField(StaticFunctionTag*, TESForm* form, BSFixedString fieldName) { Form_RemoveField(form->formID, fieldName.c_str()); } void Form_RemoveAllFields(UInt32 formID) { const char* func_name = "Form_RemoveAllFields"; lua_getglobal(g_lua, func_name); lua_pushinteger(g_lua, formID); // Call and print any errors if (lua_pcall(g_lua, 1, 0, 0) != 0) _ERROR("Error running `%s`: %s", func_name, lua_tostring(g_lua, -1)); } void Form_RemoveAllFields(TESForm* form) { Form_RemoveAllFields(form->formID); } void Papyrus_Form_RemoveAllFields(StaticFunctionTag*, TESForm* form) { Form_RemoveAllFields(form->formID); } bool RegisterPapyrusFuncs(VMClassRegistry* registry) { _MESSAGE("Registering Papyrus Functions"); registry->RegisterFunction(new NativeFunction3 <StaticFunctionTag, void, TESForm*, BSFixedString, SInt32>("SetInt", "SKI_PlayerInventoryHook", Papyrus_Form_SetInt, registry)); registry->RegisterFunction(new NativeFunction3 <StaticFunctionTag, SInt32, TESForm*, BSFixedString, SInt32>("GetInt", "SKI_PlayerInventoryHook", Papyrus_Form_GetInt, registry)); registry->RegisterFunction(new NativeFunction3 <StaticFunctionTag, void, TESForm*, BSFixedString, bool>("SetBool", "SKI_PlayerInventoryHook", Papyrus_Form_SetBool, registry)); registry->RegisterFunction(new NativeFunction3 <StaticFunctionTag, bool, TESForm*, BSFixedString, bool>("GetBool", "SKI_PlayerInventoryHook", Papyrus_Form_GetBool, registry)); registry->RegisterFunction(new NativeFunction2 <StaticFunctionTag, void, TESForm*, BSFixedString>("RemoveField", "SKI_PlayerInventoryHook", Papyrus_Form_RemoveField, registry)); registry->RegisterFunction(new NativeFunction1 <StaticFunctionTag, void, TESForm*>("RemoveAllFields", "SKI_PlayerInventoryHook", Papyrus_Form_RemoveAllFields, registry)); return true; } bool InitGlobalLuaVM() { if (g_lua) return false; // Setup new lua instance g_lua = lua::lua_new_skyui_state(); if (g_lua) return true; else return false; } class Scaleform_RemoveField : public GFxFunctionHandler { public: virtual void Invoke(Args* args) { //_MESSAGE("In Scaleform_RemoveField"); ASSERT(args->numArgs == 2); ASSERT(args->args[0].GetType() == GFxValue::kType_Number); ASSERT(args->args[1].GetType() == GFxValue::kType_String); //_MESSAGE("Scaleform -> Dll: RemoveField, %d, %s", UInt32(args->args[0].GetNumber()), args->args[1].GetString()); Form_RemoveField(UInt32(args->args[0].GetNumber()), args->args[1].GetString()); } }; bool RegisterScaleformFuncs(GFxMovieView* view, GFxValue* plugin) { RegisterFunction<Scaleform_RemoveField>(plugin, view, "FormDB_RemoveField"); Keyboard::RegisterScaleformFuncs(view, plugin); return true; } void InventoryMarkNew(GFxMovieView* view, GFxValue* object, InventoryEntryData* item) { bool new_item = Form_GetBool(item->type->formID, "skyui/newItem", false); // Skip marking gold as new if (item->type->formID == 0x0000000f) return; if (new_item) { //_MESSAGE("Marking [%x] with 'newItem'", item->type->formID); RegisterBool(object, "newItem", new_item); } } void RegisterScaleformInventoryHooks(SKSEScaleformInterface* infc) { infc->RegisterForInventory(InventoryMarkNew); } }
38.476395
183
0.671166
[ "object" ]
3a6aa3e1916d41bc5c37bafd89e700f63e41b582
7,112
hpp
C++
src/shared/uart_framing/uart_framing.hpp
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
src/shared/uart_framing/uart_framing.hpp
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
src/shared/uart_framing/uart_framing.hpp
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <vector> const uint8_t START_END_FLAG_BYTE = 0x00; namespace { /** * Generates a CRC-16 adhering to the CRC-16-CCITT standard * * @param data the data to calculate the crc of * @param length the length of the data * @return CRC-16 for given data and length */ uint16_t crc16(const std::vector<uint8_t>& data, uint16_t length) { uint8_t x; uint16_t crc = 0xFFFF; int i = 0; while (length--) { x = static_cast<uint8_t>(crc >> 8u) ^ data[i++]; x ^= static_cast<uint8_t>(x >> 4u); crc = static_cast<uint16_t>((crc << 8u) ^ (x << 12u) ^ (x << 5u) ^ x); } return crc; } /** * Implementation of modified Consistent Overhead Byte Stuffing(COBS) encoding * https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing * * Uses a Delimiter byte at both the beginning(different) and end(normal) * * @param to_encode the vector of bytes to encode * @return a vector of bytes encoded with COBS */ std::vector<uint8_t> cobsEncoding(const std::vector<uint8_t>& to_encode) { auto encoded = std::vector<uint8_t>(); encoded.emplace_back(START_END_FLAG_BYTE); size_t overhead_location = 1; uint8_t overhead = 0x01; for (auto byte : to_encode) { if (byte == START_END_FLAG_BYTE) { encoded.insert(encoded.begin() + overhead_location, overhead); overhead_location = encoded.size(); overhead = 0x01; } else { encoded.emplace_back(byte); if (++overhead == 0xFF) { encoded.insert(encoded.begin() + overhead_location, overhead); overhead_location = encoded.size(); overhead = 0x01; } } } encoded.insert(encoded.begin() + overhead_location, overhead); encoded.emplace_back(START_END_FLAG_BYTE); return encoded; } /** * Implementation of modified Consistent Overhead Byte Stuffing(COBS) decoding * https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing * * Uses a Delimiter byte at both the beginning and end instead of a single * delimiter byte at the end as in the wikipedia example. * * @param to_decode the vector of bytes to decode * @param decoded the vector that bytes are decoded to * @return whether the decode was successful */ bool cobsDecoding(const std::vector<uint8_t>& to_decode, std::vector<uint8_t>& decoded) { if (to_decode.front() != START_END_FLAG_BYTE || to_decode.back() != START_END_FLAG_BYTE) { return false; } uint16_t i = 1; while (i < to_decode.size()) { uint8_t overhead = to_decode[i++]; // Check that overhead does not point to past the end of the vector if (overhead + i > to_decode.size()) { return false; } // Check that instances of the START_END_FLAG_BYTE are not in the middle of // the vector if (overhead == START_END_FLAG_BYTE && i != to_decode.size()) { return false; } for (uint16_t j = 1; i < to_decode.size() && j < overhead; j++) { decoded.emplace_back(to_decode[i++]); } if (overhead < 0xFF && i != to_decode.size() - 1 && overhead != START_END_FLAG_BYTE) { decoded.emplace_back(START_END_FLAG_BYTE); } } return true; } } // anonymous namespace /** * Acts as a frame for uart messages * The type of message should be structs. * These structs should not include pointers or references. * * @tparam T the type of message being framed */ template <typename T> struct UartMessageFrame { uint16_t length; uint16_t crc; T message; /** * Prepares a struct for being sent over uart. * Performs both the framing and encoding. * * @tparam T type of struct beginning sent * @param data struct being marshalled * @return vector of bytes to be sent over uart */ std::vector<uint8_t> marshallUartPacket() { auto message_ptr = reinterpret_cast<const char*>(this); std::vector<uint8_t> framed_packet(message_ptr, message_ptr + sizeof(*this)); return cobsEncoding(framed_packet); } /** * Checks if the length and crc of the UartMessageFrame match * the length and crc of the message * @tparam T type that is being wrapped in data * @param data the data to verify * @return true if the length and crc match false otherwise */ bool verifyLengthAndCrc() { uint16_t expected_length = sizeof(message); auto ptr = reinterpret_cast<const uint8_t*>(&message); auto bytes = std::vector<uint8_t>(ptr, ptr + sizeof(message)); uint16_t expected_crc = crc16(bytes, length); return crc == expected_crc && length == expected_length; } }; /** * Calculates the length and crc for the given data and returns * a UartMessageFrame with the given data and computed fields * * @tparam T the type of the data param * @param data the data to put in a UartMessageFrame * @return a UartMessageFrame with the given data and computed fields */ template <typename T> UartMessageFrame<T> createUartMessageFrame(const T& data) { uint16_t length = sizeof(data); auto ptr = reinterpret_cast<const uint8_t*>(&data); auto bytes = std::vector<uint8_t>(ptr, ptr + sizeof(data)); uint16_t crc = crc16(bytes, length); UartMessageFrame<T> frame{length, crc, data}; return frame; } /** * Converts a vector of bytes to its corresponding UartMessageFrame. * * @tparam T type of UartMessageFrame to unmarshal to * @param data vector of bytes to unmarshal * @param message_frame frame to unmarshal to * @return whether the unmarshall was successful * */ template <typename T> bool unmarshalUartPacket(const std::vector<uint8_t>& data, UartMessageFrame<T>& message_frame) { auto decoded = std::vector<uint8_t>(); if (!cobsDecoding(data, decoded)) { return false; } if (decoded.size() != sizeof(message_frame)) { return false; } std::copy(decoded.begin(), decoded.end(), reinterpret_cast<uint8_t*>(&message_frame)); return message_frame.verifyLengthAndCrc(); } template <typename T> size_t getMarshalledSize(const T& data) { auto data_ptr = reinterpret_cast<const char*>(&data); std::vector<uint8_t> data_vector(data_ptr, data_ptr + sizeof(data)); return cobsEncoding(data_vector).size() + sizeof(UartMessageFrame<T>) - sizeof(T); }
31.892377
90
0.600112
[ "vector" ]
3a6c7c8a097c41c2a95a4943095424861c61407e
2,868
cc
C++
test/percentile_buckets_test.cc
brharrington/atlas-native-client
c85713289dc8a98e8d2d3605c27058a13be6c3be
[ "Apache-2.0" ]
3
2017-09-15T22:52:34.000Z
2019-01-09T22:02:19.000Z
test/percentile_buckets_test.cc
brharrington/atlas-native-client
c85713289dc8a98e8d2d3605c27058a13be6c3be
[ "Apache-2.0" ]
56
2017-09-18T14:14:52.000Z
2020-10-30T20:35:46.000Z
test/percentile_buckets_test.cc
brharrington/atlas-native-client
c85713289dc8a98e8d2d3605c27058a13be6c3be
[ "Apache-2.0" ]
6
2017-09-19T03:14:29.000Z
2019-01-15T02:16:56.000Z
#include "../meter/percentile_buckets.h" #include <gtest/gtest.h> #include <random> using namespace atlas::meter; TEST(PercentileBuckets, IndexOf) { EXPECT_EQ(0, percentile_buckets::IndexOf(-1)); EXPECT_EQ(0, percentile_buckets::IndexOf(0)); EXPECT_EQ(1, percentile_buckets::IndexOf(1)); EXPECT_EQ(2, percentile_buckets::IndexOf(2)); EXPECT_EQ(3, percentile_buckets::IndexOf(3)); EXPECT_EQ(4, percentile_buckets::IndexOf(4)); EXPECT_EQ(25, percentile_buckets::IndexOf(87)); EXPECT_EQ(percentile_buckets::Length() - 1, percentile_buckets::IndexOf(std::numeric_limits<int64_t>::max())); } TEST(PercentileBuckets, IndexOfSanityCheck) { std::mt19937_64 rng; rng.seed(std::random_device()()); for (auto i = 0; i < 10000; ++i) { auto v = static_cast<int64_t>(rng()); if (v < 0) { EXPECT_EQ(0, percentile_buckets::IndexOf(v)); } else { auto b = percentile_buckets::Get(percentile_buckets::IndexOf(v)); EXPECT_TRUE(v <= b) << v << " > " << b; } } } TEST(PercentileBuckets, BucketSanityCheck) { std::mt19937_64 rng; rng.seed(std::random_device()()); for (auto i = 0; i < 10000; ++i) { auto v = static_cast<int64_t>(rng()); if (v < 0) { EXPECT_EQ(1, percentile_buckets::Bucket(v)); } else { auto b = percentile_buckets::Bucket(v); EXPECT_TRUE(v <= b) << v << " > " << b; } } } TEST(PercentileBuckets, Percentiles) { std::array<int64_t, percentile_buckets::Length()> counts; std::fill(counts.begin(), counts.end(), 0); for (int i = 0; i < 100000; ++i) { ++counts[percentile_buckets::IndexOf(i)]; } std::vector<double> pcts{0.0, 25.0, 50.0, 75.0, 90.0, 95.0, 98.0, 99.0, 99.5, 100.0}; std::vector<double> results; percentile_buckets::Percentiles(counts, pcts, &results); ASSERT_EQ(results.size(), pcts.size()); std::vector<double> expected = {0.0, 25e3, 50e3, 75e3, 90e3, 95e3, 98e3, 99e3, 99.5e3, 100e3}; for (size_t i = 0; i < results.size(); ++i) { auto threshold = 0.1 * expected.at(i); EXPECT_NEAR(expected.at(i), results.at(i), threshold); } } TEST(PercentileBuckets, Percentile) { std::array<int64_t, percentile_buckets::Length()> counts; std::fill(counts.begin(), counts.end(), 0); for (int i = 0; i < 100000; ++i) { ++counts[percentile_buckets::IndexOf(i)]; } std::vector<double> pcts{0.0, 25.0, 50.0, 75.0, 90.0, 95.0, 98.0, 99.0, 99.5, 100.0}; std::vector<double> results; percentile_buckets::Percentiles(counts, pcts, &results); ASSERT_EQ(results.size(), pcts.size()); for (size_t i = 0; i < pcts.size(); ++i) { auto expected = pcts[i] * 1e3; auto threshold = 0.1 * expected; EXPECT_NEAR(expected, percentile_buckets::Percentile(counts, pcts[i]), threshold); } }
31.173913
78
0.617852
[ "vector" ]
b91ea0d3787135a42c6ea7ded773eee7822248e0
5,534
cc
C++
source/common/stats/stats_impl.cc
Kernelalive/envoy
07c32c26221e778f06f429af0615123b11c0a205
[ "Apache-2.0" ]
null
null
null
source/common/stats/stats_impl.cc
Kernelalive/envoy
07c32c26221e778f06f429af0615123b11c0a205
[ "Apache-2.0" ]
1
2017-11-22T09:35:42.000Z
2017-11-22T09:35:42.000Z
source/common/stats/stats_impl.cc
georgi-d/envoy
3e6e4a73d5c1804842948088dd23b6f2f95ca377
[ "Apache-2.0" ]
null
null
null
#include "common/stats/stats_impl.h" #include <string.h> #include <algorithm> #include <chrono> #include <string> #include "envoy/common/exception.h" #include "common/common/utility.h" #include "common/config/well_known_names.h" namespace Envoy { namespace Stats { namespace { // Round val up to the next multiple of the natural alignment. // Note: this implementation only works because 8 is a power of 2. size_t roundUpMultipleNaturalAlignment(size_t val) { const size_t multiple = alignof(RawStatData); static_assert(multiple == 1 || multiple == 2 || multiple == 4 || multiple == 8 || multiple == 16, "multiple must be a power of 2 for this algorithm to work"); return (val + multiple - 1) & ~(multiple - 1); } } // namespace size_t RawStatData::size() { // Normally the compiler would do this, but because name_ is a flexible-array-length // element, the compiler can't. RawStatData is put into an array in HotRestartImpl, so // it's important that each element starts on the required alignment for the type. return roundUpMultipleNaturalAlignment(sizeof(RawStatData) + nameSize()); } size_t& RawStatData::initializeAndGetMutableMaxObjNameLength(size_t configured_size) { // Like CONSTRUCT_ON_FIRST_USE, but non-const so that the value can be changed by tests static size_t size = configured_size; return size; } void RawStatData::configure(Server::Options& options) { const size_t configured = options.maxObjNameLength(); RELEASE_ASSERT(configured > 0); size_t max_obj_name_length = initializeAndGetMutableMaxObjNameLength(configured); // If this fails, it means that this function was called too late during // startup because things were already using this size before it was set. RELEASE_ASSERT(max_obj_name_length == configured); } void RawStatData::configureForTestsOnly(Server::Options& options) { const size_t configured = options.maxObjNameLength(); initializeAndGetMutableMaxObjNameLength(configured) = configured; } std::string Utility::sanitizeStatsName(const std::string& name) { std::string stats_name = name; std::replace(stats_name.begin(), stats_name.end(), ':', '_'); return stats_name; } TagExtractorImpl::TagExtractorImpl(const std::string& name, const std::string& regex) : name_(name), regex_(regex) {} TagExtractorPtr TagExtractorImpl::createTagExtractor(const std::string& name, const std::string& regex) { if (name.empty()) { throw EnvoyException("tag_name cannot be empty"); } if (!regex.empty()) { return TagExtractorPtr{new TagExtractorImpl(name, regex)}; } else { // Look up the default for that name. const auto& name_regex_pairs = Config::TagNames::get().name_regex_pairs_; auto it = std::find_if(name_regex_pairs.begin(), name_regex_pairs.end(), [&name](const std::pair<std::string, std::string>& name_regex_pair) { return name == name_regex_pair.first; }); if (it != name_regex_pairs.end()) { return TagExtractorPtr{new TagExtractorImpl(name, it->second)}; } else { throw EnvoyException(fmt::format( "No regex specified for tag specifier and no default regex for name: '{}'", name)); } } } std::string TagExtractorImpl::extractTag(const std::string& tag_extracted_name, std::vector<Tag>& tags) const { std::smatch match; // The regex must match and contain one or more subexpressions (all after the first are ignored). if (std::regex_search(tag_extracted_name, match, regex_) && match.size() > 1) { // remove_subexpr is the first submatch. It represents the portion of the string to be removed. const auto& remove_subexpr = match[1]; // value_subexpr is the optional second submatch. It is usually inside the first submatch // (remove_subexpr) to allow the expression to strip off extra characters that should be removed // from the string but also not necessary in the tag value ("." for example). If there is no // second submatch, then the value_subexpr is the same as the remove_subexpr. const auto& value_subexpr = match.size() > 2 ? match[2] : remove_subexpr; tags.emplace_back(); Tag& tag = tags.back(); tag.name_ = name_; tag.value_ = value_subexpr.str(); // Reconstructs the tag_extracted_name without remove_subexpr. return std::string(match.prefix().first, remove_subexpr.first) .append(remove_subexpr.second, match.suffix().second); } return tag_extracted_name; } RawStatData* HeapRawStatDataAllocator::alloc(const std::string& name) { // This must be zero-initialized RawStatData* data = static_cast<RawStatData*>(::calloc(RawStatData::size(), 1)); data->initialize(name); return data; } void HeapRawStatDataAllocator::free(RawStatData& data) { // This allocator does not ever have concurrent access to the raw data. ASSERT(data.ref_count_ == 1); ::free(&data); } void RawStatData::initialize(const std::string& name) { ASSERT(!initialized()); ASSERT(name.size() <= maxNameLength()); ASSERT(std::string::npos == name.find(':')); ref_count_ = 1; StringUtil::strlcpy(name_, name.substr(0, maxNameLength()).c_str(), nameSize()); } bool RawStatData::matches(const std::string& name) { // In case a stat got truncated, match on the truncated name. return 0 == strcmp(name.substr(0, maxNameLength()).c_str(), name_); } } // namespace Stats } // namespace Envoy
37.90411
100
0.699313
[ "vector" ]
b92373ff0b94afc8dddeda8a41c3101a99a15c3d
4,519
cpp
C++
cameradar_standalone/src/tasks/path_attack.cpp
pereval-team/cameradar
0e7577ed7c10fcef6e33bae4e311ab2c4a781423
[ "Apache-2.0" ]
1
2019-09-21T14:03:20.000Z
2019-09-21T14:03:20.000Z
cameradar_standalone/src/tasks/path_attack.cpp
pereval-team/cameradar
0e7577ed7c10fcef6e33bae4e311ab2c4a781423
[ "Apache-2.0" ]
null
null
null
cameradar_standalone/src/tasks/path_attack.cpp
pereval-team/cameradar
0e7577ed7c10fcef6e33bae4e311ab2c4a781423
[ "Apache-2.0" ]
1
2018-12-07T03:53:04.000Z
2018-12-07T03:53:04.000Z
// Copyright (C) 2016 Etix Labs - All Rights Reserved. // All information contained herein is, and remains the property of Etix Labs // and its suppliers, // if any. The intellectual and technical concepts contained herein are // proprietary to Etix Labs // Dissemination of this information or reproduction of this material is // strictly forbidden unless // prior written permission is obtained from Etix Labs. #include <tasks/path_attack.h> namespace etix { namespace cameradar { static const std::string no_route_found_ = "The url.json files' default paths didn't match with the discovered " "cameras. Either " "they have a custom path, or your url.json file does not contain enough " "default " "routes. Thumbnail generation is impossible without the path."; // Tries to match the detected combination of Username / Password // with a route for the camera stream. Creates a resource in the DB upon // valid discovery bool path_attack::test_path(const stream_model& stream, const std::string& route) const { bool found = false; std::string path = stream.service_name + "://" + stream.username + ":" + stream.password + "@" + stream.address + ":" + std::to_string(stream.port); if (route.front() != '/') { path += "/"; } path += route; LOG_INFO_("Testing path : " + path, "path_attack"); try { if (curl_describe(path, false)) { // insert in DB and go to the next port, print a cool message found = true; LOG_INFO_("Discovered a valid path : [" + path + "]", "path_attack"); stream_model newstream{ stream.address, stream.port, stream.username, stream.password, route, stream.service_name, stream.product, stream.protocol, stream.state, true, stream.ids_found, stream.thumbnail_path }; if ((*cache)->has_changed(stream)) return true; (*cache)->update_stream(newstream); } else { stream_model newstream{ stream.address, stream.port, stream.username, stream.password, route, stream.service_name, stream.product, stream.protocol, stream.state, false, stream.ids_found, stream.thumbnail_path }; if ((*cache)->has_changed(stream)) return true; (*cache)->update_stream(newstream); } } catch (const std::runtime_error& e) { LOG_INFO_(e.what(), "path_attack"); } return found; } bool path_already_found(std::vector<stream_model> streams, stream_model model) { for (const auto& stream : streams) { if ((model.address == stream.address) && (model.port == stream.port) && stream.path_found) return true; } return false; } bool path_attack::attack_camera_path(const stream_model& stream) const { for (const auto& route : conf.paths) { if (signal_handler::instance().should_stop() != etix::cameradar::stop_priority::running) break; if ((*cache)->has_changed(stream)) return true; if (test_path(stream, route)) return true; } return false; } // Tries to discover a route on all RTSP streams in DB // Uses the url.json file to try different routes bool path_attack::run() const { std::vector<std::future<bool>> futures; LOG_INFO_("Beginning attack of the camera paths, it may take a while.", "path_attack"); std::vector<stream_model> streams = (*cache)->get_streams(); int found = 0; for (const auto& stream : streams) { if (signal_handler::instance().should_stop() != etix::cameradar::stop_priority::running) break; if (path_already_found(streams, stream)) { LOG_INFO_(stream.address + " : This camera's path was already discovered in the database. Skipping " "to the next camera.", "path_attack"); ++found; } else { futures.push_back( std::async(std::launch::async, &path_attack::attack_camera_path, this, stream)); } } for (auto& fit : futures) { if (fit.get()) { ++found; } } if (!found) { LOG_WARN_(no_route_found_, "path_attack"); } else LOG_INFO_("Found " + std::to_string(found) + " routes for " + std::to_string(streams.size()) + " cameras", "path_attack"); return true; } } }
39.295652
100
0.611197
[ "vector", "model" ]
b928adfd57aa7597cf5c8421b058d997385b71bc
1,381
cpp
C++
Assignment5/Graph.cpp
SpiritSeeker/CCN_Lab
ad78eef313c165e7d814e6c5c1a1baa870c03542
[ "Apache-2.0" ]
null
null
null
Assignment5/Graph.cpp
SpiritSeeker/CCN_Lab
ad78eef313c165e7d814e6c5c1a1baa870c03542
[ "Apache-2.0" ]
null
null
null
Assignment5/Graph.cpp
SpiritSeeker/CCN_Lab
ad78eef313c165e7d814e6c5c1a1baa870c03542
[ "Apache-2.0" ]
null
null
null
#include "Graph.h" #include <limits> #include <queue> #include <iostream> Graph::Graph(int vertices) : m_Vertices(vertices) { m_Adjacency = new std::list<intPair>[m_Vertices]; } Graph::~Graph() { delete[] m_Adjacency; } void Graph::AddEdge(int source, int destination, int weight) { m_Adjacency[source].push_back(std::make_pair(destination, weight)); m_Adjacency[destination].push_back(std::make_pair(source, weight)); } void Graph::ShortestPath(int source) { std::priority_queue<intPair, std::vector<intPair>, std::greater<intPair>> priorityQueue; std::vector<int> distances(m_Vertices, std::numeric_limits<int>::max()); priorityQueue.push(std::make_pair(0, source)); distances[source] = 0; while (!priorityQueue.empty()) { int vertex = priorityQueue.top().second; priorityQueue.pop(); for (auto i = m_Adjacency[vertex].begin(); i != m_Adjacency[vertex].end(); ++i) { int nextVertex = (*i).first; int weight = (*i).second; if (distances[vertex] + weight < distances[nextVertex]) { distances[nextVertex] = distances[vertex] + weight; priorityQueue.push(std::make_pair(distances[nextVertex], nextVertex)); } } } std::cout << "Shortest paths from vertex " << source << ":" << std::endl; std::cout << "To\tDistance" << std::endl; for (int i = 0; i < m_Vertices; ++i) std::cout << i << "\t " << distances[i] << std::endl; }
26.056604
89
0.674873
[ "vector" ]
b92ca74b91b76ecde379086993595e7cd1d687b2
7,680
cpp
C++
oss_src/lambda/rcpplambda_utils.cpp
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
493
2016-07-11T13:35:24.000Z
2022-02-15T13:04:29.000Z
oss_src/lambda/rcpplambda_utils.cpp
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
27
2016-07-13T20:01:07.000Z
2022-02-01T18:55:28.000Z
oss_src/lambda/rcpplambda_utils.cpp
venkattgg/venkey
796b9bdfb2fa1b881d82080754643c7e68629cd2
[ "BSD-3-Clause" ]
229
2016-07-12T10:39:54.000Z
2022-02-15T13:04:31.000Z
/* * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #include "rcpplambda_utils.hpp" #include <Rcpp.h> namespace Rcpp { template <> graphlab::flexible_type as(SEXP value) { if (Rf_length(value) > 1) { std::vector<graphlab::flexible_type> values(Rf_length(value)); switch( TYPEOF(value) ) { case REALSXP: { Rcpp::NumericVector tmp = Rcpp::as<Rcpp::NumericVector>(value); for (size_t i = 0; i < tmp.size(); i++) { if (!ISNA(REAL(value)[i])) { values[i] = tmp[i]; } else { values[i] = graphlab::FLEX_UNDEFINED; } } break; } case INTSXP: { if( Rf_isFactor(value) ) { Rcpp::stop("incompatible types, factor type is not support."); } Rcpp::IntegerVector tmp = Rcpp::as<Rcpp::IntegerVector>(value); for (size_t i = 0; i < tmp.size(); i++) { if (INTEGER(value)[i] != NA_INTEGER) { values[i] = tmp[i]; } else { values[i] = graphlab::FLEX_UNDEFINED; } } break; } case LGLSXP: { //Rcpp::Rcout << "logical type has been converted into int" << std::endl; Rcpp::IntegerVector tmp = Rcpp::as<Rcpp::IntegerVector>(value); for (size_t i = 0; i < tmp.size(); i++) { if (LOGICAL(value)[i] != NA_LOGICAL) { values[i] = tmp[i]; } else { values[i] = graphlab::FLEX_UNDEFINED; } } break; } case STRSXP: { Rcpp::CharacterVector tmp = Rcpp::as<Rcpp::CharacterVector>(value); for (size_t i = 0; i < tmp.size(); i++) { if (STRING_ELT(value, i) != NA_STRING) { values[i] = Rcpp::as<std::string>(tmp[i]); } else { values[i] = graphlab::FLEX_UNDEFINED; } } break; } case CHARSXP: { Rcpp::CharacterVector tmp = Rcpp::as<Rcpp::CharacterVector>(value); for (size_t i = 0; i < tmp.size(); i++) { if (tmp[i] != NA_STRING) { values[i] = Rcpp::as<std::string>(tmp[i]); } else { values[i] = graphlab::FLEX_UNDEFINED; } } break; } case VECSXP: { Rcpp::List lst(value); for (size_t i = 0; i < values.size(); i++) { if (TYPEOF(lst[i]) == VECSXP) { values[i] = Rcpp::as<graphlab::flexible_type>(lst[i]); } else { values[i] = Rcpp::as<graphlab::flexible_type>(lst[i]); } } break; } default: { Rcpp::stop("incompatible types encountered"); } } return values; } else { graphlab::flexible_type flex_value; switch( TYPEOF(value) ) { case REALSXP: { if (!ISNA(REAL(value)[0])) { flex_value = Rcpp::as<double>(value); } else { flex_value = graphlab::FLEX_UNDEFINED; } break; } case INTSXP: { if (INTEGER(value)[0] != NA_INTEGER) { flex_value = Rcpp::as<int>(value); } else { flex_value = graphlab::FLEX_UNDEFINED; } break; } case LGLSXP: { //Rcpp::Rcout << "logical type has been converted into int" << std::endl; if (LOGICAL(value)[0] != NA_LOGICAL) { flex_value = Rcpp::as<int>(value); } else { flex_value = graphlab::FLEX_UNDEFINED; } break; } case STRSXP: { if (STRING_ELT(value, 0) != NA_STRING) { flex_value = Rcpp::as<std::string>(value); } else { flex_value = graphlab::FLEX_UNDEFINED; } break; } case CHARSXP: { if (value != NA_STRING) { flex_value = Rcpp::as<std::string>(value); } else { flex_value = graphlab::FLEX_UNDEFINED; } break; } case VECSXP: { Rcpp::List lst(value); std::vector<graphlab::flexible_type> tmp; tmp.push_back(Rcpp::as<graphlab::flexible_type>(lst[0])); flex_value = tmp; break; } default: { Rcpp::stop("incompatible types encountered"); } } return flex_value; } } template <> SEXP wrap( const graphlab::flexible_type& value) { graphlab::flex_type_enum type = value.get_type(); switch(type) { case graphlab::flex_type_enum::STRING: { return Rcpp::wrap(value.to<graphlab::flex_string>()); } case graphlab::flex_type_enum::FLOAT: { return Rcpp::wrap(value.to<graphlab::flex_float>()); } case graphlab::flex_type_enum::INTEGER: { return Rcpp::wrap(value.to<graphlab::flex_int>()); } case graphlab::flex_type_enum::LIST: { std::vector<graphlab::flexible_type> f_vec = value.to<graphlab::flex_list>(); Rcpp::List lst(f_vec.size()); bool is_vec = true; for (size_t i = 0; i < f_vec.size(); i++) { graphlab::flex_type_enum type = f_vec[i].get_type(); switch(type) { case graphlab::flex_type_enum::STRING: { lst[i] = Rcpp::wrap(f_vec[i].to<graphlab::flex_string>()); break; } case graphlab::flex_type_enum::FLOAT: { lst[i] = Rcpp::wrap(f_vec[i].to<graphlab::flex_float>()); break; } case graphlab::flex_type_enum::INTEGER: { lst[i] = Rcpp::wrap(f_vec[i].to<graphlab::flex_int>()); break; } case graphlab::flex_type_enum::LIST: { is_vec = false; lst[i] = Rcpp::wrap(f_vec[i]); break; } default: { Rcpp::stop("incompatible types found!"); break; } } } if (is_vec) { SEXP as_df_symb = Rf_install("unlist"); Rcpp::Shield<SEXP> call(Rf_lang2(as_df_symb, lst)) ; Rcpp::Shield<SEXP> res(Rcpp_eval(call)); switch(TYPEOF(lst[0])) { case REALSXP: { Rcpp::Vector<REALSXP, Rcpp::PreserveStorage> out(res) ; return out; } case INTSXP: { Rcpp::Vector<INTSXP, Rcpp::PreserveStorage> out(res) ; return out; } case STRSXP: { Rcpp::Vector<STRSXP, Rcpp::PreserveStorage> out(res) ; return out; } } } else { return lst; } } case graphlab::flex_type_enum::DICT: { dict d; for(auto imap: value.to<graphlab::flex_dict>()) d[imap.first] = imap.second; return Rcpp::XPtr<dict>(new dict(d), true) ; } case graphlab::flex_type_enum::UNDEFINED: { return Rcpp::wrap(NA_REAL); } default: { Rcpp::stop("incompatible types found!"); break; } } } }
32.820513
85
0.463542
[ "vector" ]
b9342303dfe91249832d3d0c039f58dc1906f6ad
1,187
cpp
C++
Hackerearth/Practice/Monk and the Islands.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
4
2019-06-04T11:03:38.000Z
2020-06-19T23:37:32.000Z
Hackerearth/Practice/Monk and the Islands.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
Hackerearth/Practice/Monk and the Islands.cpp
coderanant/Competitive-Programming
45076af7894251080ac616c9581fbf2dc49604af
[ "MIT" ]
null
null
null
/*coderanant*/ #include <bits/stdc++.h> using namespace std; #define int long long #define ll long long #define f1(i,a,b) for(i=a;i<b;i++) #define f2(i,a,b) for(i=a;i>=b;i--) #define endl '\n' #define pb push_back #define gp " " #define ff first #define ss second #define mp make_pair const int mod=1000000007; int i,j; ll temp; int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("/home/akmittal/Desktop/Competitive Programming/in.txt","r",stdin); freopen("/home/akmittal/Desktop/Competitive Programming/out.txt","w",stdout); #endif int t; cin>>t; while(t--) { int n,m; cin>>n>>m; int vis[n+1]; memset(vis,-1,sizeof(vis)); vector<int> v[n+1]; f1(i,0,m) { int a,b; cin>>a>>b; v[a].pb(b); v[b].pb(a); } queue<int> q; q.push(1); vis[1]=0; while(!q.empty()) { int node=q.front(); q.pop(); f1(i,0,v[node].size()) { if(vis[v[node][i]]==-1) { q.push(v[node][i]); vis[v[node][i]]=vis[node]+1; } } } cout<<vis[n]<<endl; } return 0; }
18.84127
82
0.52738
[ "vector" ]
b936f8c39382c6a5c66d5308394b37f6e56ad9e7
30,174
cc
C++
services/audio/output_device_mixer_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
services/audio/output_device_mixer_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
services/audio/output_device_mixer_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/audio/output_device_mixer_impl.h" #include "base/check.h" #include "base/containers/contains.h" #include "base/dcheck_is_on.h" #include "base/logging.h" #include "base/memory/raw_ptr.h" #include "base/metrics/histogram_functions.h" #include "base/strings/strcat.h" #include "base/trace_event/trace_event.h" #include "media/audio/audio_device_description.h" #include "media/audio/audio_io.h" namespace audio { constexpr base::TimeDelta OutputDeviceMixerImpl::kSwitchToUnmixedPlaybackDelay; constexpr double OutputDeviceMixerImpl::kDefaultVolume; namespace { const char* LatencyToUmaSuffix(media::AudioLatency::LatencyType latency) { switch (latency) { case media::AudioLatency::LATENCY_EXACT_MS: return "LatencyExactMs"; case media::AudioLatency::LATENCY_INTERACTIVE: return "LatencyInteractive"; case media::AudioLatency::LATENCY_RTC: return "LatencyRtc"; case media::AudioLatency::LATENCY_PLAYBACK: return "LatencyPlayback"; default: return "LatencyUnknown"; } } const char* DeviceIdToUmaSuffix(const std::string& device_id) { if (device_id == "") return ".Default"; return ".NonDefault"; } // Do not change: used for UMA reporting, matches // AudioOutputDeviceMixerStreamStatus from enums.xml. enum class TrackError { kNone = 0, kIndependentOpenFailed, kIndependentPlaybackFailed, kMixedOpenFailed, kMixedPlaybackFailed, kMaxValue = kMixedPlaybackFailed }; const char* TrackErrorToString(TrackError error) { switch (error) { case TrackError::kIndependentOpenFailed: return "Failed to open independent rendering stream"; case TrackError::kIndependentPlaybackFailed: return "Error during independent playback"; case TrackError::kMixedOpenFailed: return "Failed to open mixing rendering stream"; case TrackError::kMixedPlaybackFailed: return "Error during mixed playback"; default: NOTREACHED(); return "No error"; } } } // namespace // Audio data flow though the mixer: // // * Independent (ummixed) audio stream playback: // MixTrack::|audio_source_callback_| // -> MixTrack::|rendering_stream_|. // // * Mixed playback: // MixTrack::|audio_source_callback_| // -> MixTrack::|graph_input_| // --> OutputDeviceMixerImpl::|mixing_graph_| // ---> OutputDeviceMixerImpl::|mixing_graph_rendering_stream_| // Helper class which stores all the data associated with a specific audio // output managed by the mixer. To the clients such an audio output is // represented as MixableOutputStream (below). class OutputDeviceMixerImpl::MixTrack final : public media::AudioOutputStream::AudioSourceCallback { public: MixTrack(OutputDeviceMixerImpl* mixer, std::unique_ptr<MixingGraph::Input> graph_input, base::OnceClosure on_device_change_callback) : mixer_(mixer), on_device_change_callback_(std::move(on_device_change_callback)), graph_input_(std::move(graph_input)) {} ~MixTrack() final { DCHECK(!audio_source_callback_); base::UmaHistogramEnumeration( "Media.Audio.OutputDeviceMixer.StreamPlaybackStatus", error_); } void SetSource( media::AudioOutputStream::AudioSourceCallback* audio_source_callback) { DCHECK(!audio_source_callback_ || !audio_source_callback); audio_source_callback_ = audio_source_callback; } void SetVolume(double volume) { volume_ = volume; graph_input_->SetVolume(volume); if (rendering_stream_) rendering_stream_->SetVolume(volume); } double GetVolume() const { return volume_; } void StartProvidingAudioToMixingGraph() { DCHECK(audio_source_callback_); RegisterPlaybackStarted(); graph_input_->Start(audio_source_callback_); } void StopProvidingAudioToMixingGraph() { DCHECK(audio_source_callback_); graph_input_->Stop(); RegisterPlaybackStopped(PlaybackType::kMixed); } void StartIndependentRenderingStream() { DCHECK(audio_source_callback_); if (!rendering_stream_) { // Open the rendering stream if it's not open yet. It will be closed in // CloseIndependentRenderingStream() or during destruction. rendering_stream_.reset( mixer_->CreateAndOpenDeviceStream(graph_input_->GetParams())); if (!rendering_stream_) { ReportError(TrackError::kIndependentOpenFailed); return; } rendering_stream_->SetVolume(volume_); } RegisterPlaybackStarted(); rendering_stream_->Start(this); } void StopIndependentRenderingStream() { DCHECK(audio_source_callback_); if (rendering_stream_) { rendering_stream_->Stop(); RegisterPlaybackStopped(PlaybackType::kIndependent); } } void CloseIndependentRenderingStream() { DCHECK(!audio_source_callback_); // Closes the stream. rendering_stream_.reset(); } void ReportError(TrackError error) { DCHECK(audio_source_callback_); DCHECK_NE(error, TrackError::kNone); LOG(ERROR) << "MixableOutputStream: " << TrackErrorToString(error); error_ = error; audio_source_callback_->OnError(ErrorType::kUnknown); } void OnDeviceChange() { DCHECK(!on_device_change_callback_.is_null()); std::move(on_device_change_callback_).Run(); } private: enum class PlaybackType { kMixed, kIndependent }; void RegisterPlaybackStarted() { DCHECK(playback_activation_time_for_uma_.is_null()); playback_activation_time_for_uma_ = base::TimeTicks::Now(); } void RegisterPlaybackStopped(PlaybackType playback_type) { if (playback_type == PlaybackType::kIndependent && playback_activation_time_for_uma_.is_null()) { return; // Stop() for an independent stream can be called multiple times. } DCHECK(!playback_activation_time_for_uma_.is_null()); base::UmaHistogramLongTimes( base::StrCat( {"Media.Audio.OutputDeviceMixer.StreamDuration.", ((playback_type == PlaybackType::kMixed) ? "Mixed." : "Unmixed."), LatencyToUmaSuffix(graph_input_->GetParams().latency_tag())}), base::TimeTicks::Now() - playback_activation_time_for_uma_); playback_activation_time_for_uma_ = base::TimeTicks(); } // media::AudioOutputStream::AudioSourceCallback implementation to intercept // error reporting during independent playback. int OnMoreData(base::TimeDelta delay, base::TimeTicks delay_timestamp, int prior_frames_skipped, media::AudioBus* dest) final { DCHECK(audio_source_callback_); return audio_source_callback_->OnMoreData(delay, delay_timestamp, prior_frames_skipped, dest); } void OnError(ErrorType type) final { // Device change events are intercepted by the underlying physical streams. DCHECK_EQ(type, ErrorType::kUnknown); ReportError(TrackError::kIndependentPlaybackFailed); } double volume_ = kDefaultVolume; const raw_ptr<OutputDeviceMixerImpl> mixer_; // Callback to notify the audio output client of the device change. Note that // all the device change events are initially routed to MixerManager which // does the centralized processing and notifies each mixer via // OutputDeviceMixer::ProcessDeviceChange(). There OutputDeviceMixerImpl does // the cleanup and then dispatches the device change event to all its clients // via |on_device_change_callback_| of its MixTracks. base::OnceClosure on_device_change_callback_; // Callback to request the audio output data from the client. raw_ptr<media::AudioOutputStream::AudioSourceCallback> audio_source_callback_ = nullptr; // Delivers the audio output into MixingGraph, to be mixed for the reference // signal playback. const std::unique_ptr<MixingGraph::Input> graph_input_; // When non-nullptr, points to an open physical output stream used to render // the audio output independently when mixing is not required. std::unique_ptr<media::AudioOutputStream, StreamAutoClose> rendering_stream_ = nullptr; base::TimeTicks playback_activation_time_for_uma_; TrackError error_ = TrackError::kNone; }; // A proxy which represents MixTrack as media::AudioOutputStream. class OutputDeviceMixerImpl::MixableOutputStream final : public media::AudioOutputStream { public: MixableOutputStream(base::WeakPtr<OutputDeviceMixerImpl> mixer, MixTrack* mix_track) : mixer_(std::move(mixer)), mix_track_(mix_track) {} MixableOutputStream(const MixableOutputStream&) = delete; MixableOutputStream& operator=(const MixableOutputStream&) = delete; ~MixableOutputStream() final { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); } // AudioOutputStream interface. bool Open() final { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); if (!mixer_) { LOG(ERROR) << "Stream start failed: device changed"; return false; } // No-op: required resources are determened when the stream starts playing. return true; } void Start(AudioSourceCallback* callback) final { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); DCHECK(callback); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1( TRACE_DISABLED_BY_DEFAULT("audio"), "MixableOutputStream::IsPlaying", this, "device_id", mixer_ ? mixer_->device_id() : "device changed"); if (!mixer_) { LOG(ERROR) << "Stream start failed: device changed"; callback->OnError(ErrorType::kDeviceChange); return; } mixer_->StartStream(mix_track_, callback); } void Stop() final { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); TRACE_EVENT_NESTABLE_ASYNC_END0(TRACE_DISABLED_BY_DEFAULT("audio"), "MixableOutputStream::IsPlaying", this); if (!mixer_) return; mixer_->StopStream(mix_track_); } void SetVolume(double volume) final { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); if (!mixer_) return; mix_track_->SetVolume(volume); } void GetVolume(double* volume) final { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); DCHECK(volume); if (!mixer_) return; *volume = mix_track_->GetVolume(); } void Close() final { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); if (mixer_) { mixer_->CloseStream(mix_track_); } // To match the typical usage pattern of AudioOutputStream. delete this; } void Flush() final {} private: SEQUENCE_CHECKER(owning_sequence_); // OutputDeviceMixerImpl will release all the resources and invalidate its // weak pointers in OutputDeviceMixer::ProcessDeviceChange(). After that // MixableOutputStream becomes a no-op. base::WeakPtr<OutputDeviceMixerImpl> const mixer_ GUARDED_BY_CONTEXT(owning_sequence_); const raw_ptr<MixTrack> mix_track_; // Valid only when |mixer_| is valid. }; // Logs mixing statistics upon the destruction. Should be created when mixing // playback starts, and destroyed when it ends. class OutputDeviceMixerImpl::MixingStats { public: MixingStats(const std::string& device_id, int active_track_count, int listener_count) : suffix_(DeviceIdToUmaSuffix(device_id)), active_track_count_(active_track_count), listener_count_(listener_count), start_(base::TimeTicks::Now()) { DCHECK_GT(active_track_count, 0); DCHECK_GT(listener_count, 0); } ~MixingStats() { if (!noop_mixing_start_.is_null()) { LogNoopMixingDuration(); } DCHECK(!start_.is_null()); base::TimeDelta duration = base::TimeTicks::Now() - start_; LogPerDeviceUma(duration, suffix_); LogPerDeviceUma(duration, ""); // Combined. } void AddListener() { listener_count_.Increment(); } void RemoveListener() { listener_count_.Decrement(); } void AddActiveTrack() { active_track_count_.Increment(); if (!noop_mixing_start_.is_null()) { // First track after a period of feeding silence to the listeners. DCHECK_EQ(active_track_count_.GetCurrent(), 1); DCHECK(listener_count_.GetCurrent()); LogNoopMixingDuration(); } } void RemoveActiveTrack() { active_track_count_.Decrement(); if (listener_count_.GetCurrent() && !active_track_count_.GetCurrent()) { // No more tracks, so we start feeding silence to listeners. DCHECK(noop_mixing_start_.is_null()); noop_mixing_start_ = base::TimeTicks::Now(); } } private: // A helper to track the max value. class MaxTracker { public: explicit MaxTracker(int value) : value_(value), max_value_(value) {} int GetCurrent() { return value_; } int GetMax() { return max_value_; } void Increment() { if (++value_ > max_value_) max_value_ = value_; } void Decrement() { DCHECK(value_ > 0); value_--; } private: int value_; int max_value_; }; void LogNoopMixingDuration() { DCHECK(!noop_mixing_start_.is_null()); base::UmaHistogramLongTimes( "Media.Audio.OutputDeviceMixer.NoopMixingDuration", base::TimeTicks::Now() - noop_mixing_start_); noop_mixing_start_ = base::TimeTicks(); } void LogPerDeviceUma(base::TimeDelta duration, const char* suffix) { constexpr int kMaxActiveStreamCount = 50; constexpr int kMaxListeners = 20; base::UmaHistogramLongTimes( base::StrCat({"Media.Audio.OutputDeviceMixer.MixingDuration", suffix}), duration); base::UmaHistogramExactLinear( base::StrCat( {"Media.Audio.OutputDeviceMixer.MaxMixedStreamCount", suffix}), active_track_count_.GetMax(), kMaxActiveStreamCount); base::UmaHistogramExactLinear( base::StrCat( {"Media.Audio.OutputDeviceMixer.MaxListenerCount", suffix}), listener_count_.GetMax(), kMaxListeners); } const char* const suffix_; MaxTracker active_track_count_; MaxTracker listener_count_; const base::TimeTicks start_; // Start of the period when there are no active tracks and we play and feed // silence to the listeners. base::TimeTicks noop_mixing_start_; }; OutputDeviceMixerImpl::OutputDeviceMixerImpl( const std::string& device_id, const media::AudioParameters& output_params, MixingGraph::CreateCallback create_mixing_graph_callback, CreateStreamCallback create_stream_callback) : OutputDeviceMixer(device_id), create_stream_callback_(std::move(create_stream_callback)), mixing_graph_output_params_(output_params), mixing_graph_(std::move(create_mixing_graph_callback) .Run(output_params, base::BindRepeating( &OutputDeviceMixerImpl::BroadcastToListeners, base::Unretained(this)), base::BindRepeating( &OutputDeviceMixerImpl::OnMixingGraphError, base::Unretained(this)))) { DCHECK(mixing_graph_output_params_.IsValid()); DCHECK_EQ(mixing_graph_output_params_.format(), media::AudioParameters::AUDIO_PCM_LOW_LATENCY); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl", this, "device_id", device_id); } OutputDeviceMixerImpl::~OutputDeviceMixerImpl() { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); DCHECK(active_tracks_.empty()); DCHECK(!HasListeners()); DCHECK(!mixing_graph_output_stream_); TRACE_EVENT_NESTABLE_ASYNC_END0(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl", this); } media::AudioOutputStream* OutputDeviceMixerImpl::MakeMixableStream( const media::AudioParameters& params, base::OnceClosure on_device_change_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); NON_REENTRANT_SCOPE(reentrancy_checker_); if (!(params.IsValid() && params.format() == media::AudioParameters::AUDIO_PCM_LOW_LATENCY)) { LOG(ERROR) << "Invalid output stream patameters for device [" << device_id() << "], parameters: " << params.AsHumanReadableString(); return nullptr; } auto mix_track = std::make_unique<MixTrack>(this, mixing_graph_->CreateInput(params), std::move(on_device_change_callback)); media::AudioOutputStream* mixable_stream = new MixableOutputStream(weak_factory_.GetWeakPtr(), mix_track.get()); mix_tracks_.insert(std::move(mix_track)); return mixable_stream; } void OutputDeviceMixerImpl::ProcessDeviceChange() { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); NON_REENTRANT_SCOPE(reentrancy_checker_); #if DCHECK_IS_ON() DCHECK(!device_changed_); device_changed_ = true; #endif // Make all MixableOutputStream instances no-op. weak_factory_.InvalidateWeakPtrs(); // Stop and close all audio playback. if (mixing_graph_output_stream_) { StopMixingGraphPlayback(MixingError::kNone); } else { for (MixTrack* mix_track : active_tracks_) mix_track->StopIndependentRenderingStream(); } // For consistency. for (MixTrack* mix_track : active_tracks_) mix_track->SetSource(nullptr); active_tracks_.clear(); // Close independent rendering streams: the clients will want to restore // active playback in mix_track->OnDeviceChange() calls below; we don't want // to exceed the limit of simultaneously open output streams when they do so. for (auto&& mix_track : mix_tracks_) mix_track->CloseIndependentRenderingStream(); { base::AutoLock scoped_lock(listener_lock_); listeners_.clear(); } // Notify MixableOutputStream users of the device change. Normally they should // close the current stream they are holding to, create/open a new one and // resume the playback. We already released all the resources; closing a // MixableOutputStream will be a no-op since weak pointers to |this| have just // been invalidated. for (auto&& mix_track : mix_tracks_) mix_track->OnDeviceChange(); } void OutputDeviceMixerImpl::StartListening(Listener* listener) { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); NON_REENTRANT_SCOPE(reentrancy_checker_); #if DCHECK_IS_ON() DCHECK(!device_changed_); #endif DVLOG(1) << "Reference output listener added for device [" << device_id() << "]"; // A new listener came: cancel scheduled switch to independent playback. switch_to_unmixed_playback_delay_timer_.Stop(); { base::AutoLock scoped_lock(listener_lock_); DCHECK(listeners_.find(listener) == listeners_.end()); listeners_.insert(listener); if (mixing_stats_) { DCHECK(mixing_graph_output_stream_); // We are mixing. mixing_stats_->AddListener(); } } if (!mixing_graph_output_stream_ && !active_tracks_.empty()) { // Start reference playback only if at least one audio stream is playing. for (MixTrack* mix_track : active_tracks_) mix_track->StopIndependentRenderingStream(); StartMixingGraphPlayback(); // Note that if StartMixingGraphPlayback() failed, no audio will be playing // and each client of a playing MixableOutputStream will receive OnError() // callback call. } } void OutputDeviceMixerImpl::StopListening(Listener* listener) { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); #if DCHECK_IS_ON() DCHECK(!device_changed_); #endif DVLOG(1) << "Reference output listener removed for device [" << device_id() << "]"; { base::AutoLock scoped_lock(listener_lock_); auto iter = listeners_.find(listener); DCHECK(iter != listeners_.end()); listeners_.erase(iter); } if (mixing_stats_) { DCHECK(mixing_graph_output_stream_); // We are mixing. mixing_stats_->RemoveListener(); } if (HasListeners()) { // We still have some listeners left, so no need to switch to independent // playback. return; } if (!mixing_graph_output_stream_) return; // Mixing graph playback is ongoing. if (active_tracks_.empty()) { // There is no actual playback: we were just sending silence to the // listener as a reference. StopMixingGraphPlayback(MixingError::kNone); } else { // No listeners left, and we are playing via the mixing graph. Schedule // switching to independent playback. switch_to_unmixed_playback_delay_timer_.Start( FROM_HERE, kSwitchToUnmixedPlaybackDelay, this, &OutputDeviceMixerImpl::SwitchToUnmixedPlaybackTimerHelper); } } void OutputDeviceMixerImpl::StartStream( MixTrack* mix_track, media::AudioOutputStream::AudioSourceCallback* callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); NON_REENTRANT_SCOPE(reentrancy_checker_); #if DCHECK_IS_ON() DCHECK(!device_changed_); #endif DCHECK(mix_track); DCHECK(callback); DCHECK(!base::Contains(active_tracks_, mix_track)); TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl::StartStream", "device_id", device_id(), "mix_track", static_cast<void*>(mix_track)); mix_track->SetSource(callback); active_tracks_.emplace(mix_track); if (mixing_graph_output_stream_) { // We are playing all audio as a |mixing_graph_| output. mix_track->StartProvidingAudioToMixingGraph(); DCHECK(mixing_stats_); mixing_stats_->AddActiveTrack(); } else if (HasListeners()) { // Either we are starting the first active stream, or the previous switch to // playing via the mixing graph failed because the its output stream failed // to open. In any case, none of the active streams are playing individually // at this point. StartMixingGraphPlayback(); } else { // No reference signal is requested. mix_track->StartIndependentRenderingStream(); } } void OutputDeviceMixerImpl::StopStream(MixTrack* mix_track) { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); NON_REENTRANT_SCOPE(reentrancy_checker_); #if DCHECK_IS_ON() DCHECK(!device_changed_); #endif DCHECK(mix_track); if (!base::Contains(active_tracks_, mix_track)) { // MixableOutputStream::Stop() can be called multiple times, even if the // stream has not been started. See media::AudioOutputStream documentation. return; } TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl::StopStream", "device_id", device_id(), "mix_track", static_cast<void*>(mix_track)); active_tracks_.erase(mix_track); if (mixing_graph_output_stream_) { // We are playing all audio as a |mixing_graph_| output. mix_track->StopProvidingAudioToMixingGraph(); DCHECK(mixing_stats_); mixing_stats_->RemoveActiveTrack(); if (!HasListeners() && active_tracks_.empty()) { // All listeners are gone, which means a switch to an independent playback // is scheduled. But since we have no active tracks, we can stop mixing // immediately. DCHECK(switch_to_unmixed_playback_delay_timer_.IsRunning()); StopMixingGraphPlayback(MixingError::kNone); } // Note: if there are listeners, we do not stop the reference playback even // if there are no active mix members. This way the echo canceller will be // in a consistent state when the playback is activated again. Drawback: we // keep playing silent audio. An example would be some occasional // notification sounds and no other audio output: we start the mixing // playback at the first notification, and stop it only when the echo // cancellation session is finished (i.e. all the listeners are gone). } else { mix_track->StopIndependentRenderingStream(); } mix_track->SetSource(nullptr); } void OutputDeviceMixerImpl::CloseStream(MixTrack* mix_track) { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); NON_REENTRANT_SCOPE(reentrancy_checker_); #if DCHECK_IS_ON() DCHECK(!device_changed_); #endif DCHECK(mix_track); DCHECK(!base::Contains(active_tracks_, mix_track)); auto iter = mix_tracks_.find(mix_track); DCHECK(iter != mix_tracks_.end()); mix_tracks_.erase(iter); } media::AudioOutputStream* OutputDeviceMixerImpl::CreateAndOpenDeviceStream( const media::AudioParameters& params) { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); DCHECK(params.IsValid()); DCHECK_EQ(params.format(), media::AudioParameters::AUDIO_PCM_LOW_LATENCY); media::AudioOutputStream* stream = create_stream_callback_.Run(device_id(), params); if (!stream) return nullptr; if (!stream->Open()) { LOG(ERROR) << "Failed to open stream"; stream->Close(); return nullptr; } return stream; } void OutputDeviceMixerImpl::BroadcastToListeners( const media::AudioBus& audio_bus, base::TimeDelta delay) { TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl::BroadcastToListeners", "delay ms", delay.InMilliseconds()); base::AutoLock scoped_lock(listener_lock_); for (Listener* listener : listeners_) { listener->OnPlayoutData(audio_bus, mixing_graph_output_params_.sample_rate(), delay); } } // Processes errors coming from |mixing_graph_| during mixed playback. void OutputDeviceMixerImpl::OnMixingGraphError(ErrorType error) { // |mixing_graph_output_stream_| guarantees this. DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); // Device change events are intercepted by the underlying physical stream. DCHECK_EQ(error, ErrorType::kUnknown); // This call is expected only during mixed playback. DCHECK(mixing_graph_output_stream_); StopMixingGraphPlayback(MixingError::kPlaybackFailed); } bool OutputDeviceMixerImpl::HasListeners() const { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); return TS_UNCHECKED_READ(listeners_).size(); } void OutputDeviceMixerImpl::StartMixingGraphPlayback() { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); DCHECK(!mixing_graph_output_stream_); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl mixing", this, "device_id", device_id()); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl::StartMixingGraphPlayback", "device_id", device_id()); // Unlike output streams for individual rendering, we create and open the // mixing output stream each time we are about to start playing audio via the // mixing graph, to provide the reference signal to the listeners; and stop // and close it when the reference playback is not needed any more - just for // simplicity. |switch_to_unmixed_playback_delay_timer_| helps to avoid // situations when we recreate the stream immediately; also the physical // stream is managed by media::AudioOutputDispatcher which optimizes reopening // of an output device if it happens soon after it was closed, and starting // such a stream after a period of inactivity is the same as // recreating/opening/starting it. mixing_graph_output_stream_.reset( CreateAndOpenDeviceStream(mixing_graph_output_params_)); if (!mixing_graph_output_stream_) { StopMixingGraphPlayback(MixingError::kOpenFailed); return; } DCHECK(!mixing_stats_); mixing_stats_ = std::make_unique<MixingStats>( device_id(), active_tracks_.size(), TS_UNCHECKED_READ(listeners_).size()); for (MixTrack* mix_track : active_tracks_) mix_track->StartProvidingAudioToMixingGraph(); mixing_graph_output_stream_->Start(mixing_graph_.get()); DVLOG(1) << " Mixing started for device [" << device_id() << "]"; } void OutputDeviceMixerImpl::StopMixingGraphPlayback(MixingError error) { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); if (mixing_graph_output_stream_) { // Mixing was in progress, we should stop it. DCHECK_NE(error, MixingError::kOpenFailed); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl::StopMixingGraphPlayback", "device_id", device_id()); switch_to_unmixed_playback_delay_timer_.Stop(); mixing_graph_output_stream_->Stop(); mixing_graph_output_stream_.reset(); // Auto-close the stream. DCHECK(mixing_stats_); mixing_stats_.reset(); DVLOG(1) << " Mixing stopped for device [" << device_id() << "]"; for (MixTrack* mix_track : active_tracks_) mix_track->StopProvidingAudioToMixingGraph(); TRACE_EVENT_NESTABLE_ASYNC_END0(TRACE_DISABLED_BY_DEFAULT("audio"), "OutputDeviceMixerImpl mixing", this); } DCHECK(!mixing_graph_output_stream_); if (error != MixingError::kNone) { LOG(ERROR) << ErrorToString(error) << " for device [" << device_id() << "]"; TrackError track_error = (error == MixingError::kOpenFailed) ? TrackError::kMixedOpenFailed : TrackError::kMixedPlaybackFailed; for (MixTrack* mix_track : active_tracks_) mix_track->ReportError(track_error); } base::UmaHistogramEnumeration( "Media.Audio.OutputDeviceMixer.MixedPlaybackStatus", error); } void OutputDeviceMixerImpl::SwitchToUnmixedPlaybackTimerHelper() { DCHECK_CALLED_ON_VALID_SEQUENCE(owning_sequence_); NON_REENTRANT_SCOPE(reentrancy_checker_); DCHECK(mixing_graph_output_stream_); #if DCHECK_IS_ON() DCHECK(!device_changed_); #endif StopMixingGraphPlayback(MixingError::kNone); for (MixTrack* mix_track : active_tracks_) mix_track->StartIndependentRenderingStream(); } // static const char* OutputDeviceMixerImpl::ErrorToString(MixingError error) { switch (error) { case MixingError::kOpenFailed: return "Failed to open mixing rendering stream"; case MixingError::kPlaybackFailed: return "Error during mixed playback"; default: NOTREACHED(); return "No error"; } } } // namespace audio
34.445205
80
0.71502
[ "render" ]
b93f6e2a9cd648a097676e6fbf126b9a7f3e66c8
14,219
cpp
C++
davarocr/davarocr/davar_det/datasets/pipelines/lib/east_data.cpp
icedream2/DAVAR-Lab-OCR
c8b82f45516850eeadcab2739fb2a4292f2fdca1
[ "Apache-2.0" ]
387
2021-01-02T07:50:15.000Z
2022-03-31T04:30:03.000Z
davarocr/davarocr/davar_det/datasets/pipelines/lib/east_data.cpp
icedream2/DAVAR-Lab-OCR
c8b82f45516850eeadcab2739fb2a4292f2fdca1
[ "Apache-2.0" ]
70
2021-05-04T18:28:18.000Z
2022-03-31T14:14:52.000Z
davarocr/davarocr/davar_det/datasets/pipelines/lib/east_data.cpp
icedream2/DAVAR-Lab-OCR
c8b82f45516850eeadcab2739fb2a4292f2fdca1
[ "Apache-2.0" ]
83
2021-01-05T08:28:26.000Z
2022-03-31T07:14:03.000Z
/* ################################################################################################## // Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. // Filename : east_data.cpp // Abstract : GT_mask generating in EAST // Current Version: 1.0.0 // Date : 2020-05-31 ################################################################################################### */ #include <iostream> #include <functional> #include <utility> #include <vector> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <cctype> #include <fstream> #include <sstream> #include <algorithm> #include <iterator> #include <opencv2/opencv.hpp> using namespace std; vector<vector<cv::Point> > Shrink_Poly(vector<vector<cv::Point> > poly, float R); double distance_to_Line(cv::Point2f line_start, cv::Point2f line_end, cv::Point2f point); void balance_BF(float* conf_data, float fg_ratio, int* mask_data, int out_height_, int out_width_); extern "C" void parse_east_data(int height, int width, int* gt_boxes, int gt_boxes_size, int* gt_boxes_ignore, int gt_boxes_ignore_size, int pool_ratio, int geometry, //0 RBOX 1 QUAD int label_shape, // 0 normal 1 gaussian float shrink_ratio, float ignore_ratio, float* gt_score_map, int* gt_score_map_mask, float* gt_geo_data, float* gt_geo_weight, int seed ); vector<vector<cv::Point> > Shrink_Poly(vector<vector<cv::Point> > poly, float R) { /* Shrink gt_bboxes according to factor R. */ vector<vector<cv::Point> > tmp = poly; for (int poly_idx = 0; poly_idx < tmp.size(); ++poly_idx) { vector<cv::Point> p = tmp[poly_idx]; float four_side[4] = { 0 }; for (int p_idx = 0; p_idx < 4; ++p_idx) { float length1 = sqrt(pow(p[p_idx].x - p[p_idx + 1 > 3 ? 0 : p_idx + 1].x, 2) + pow(p[p_idx].y - p[p_idx + 1 > 3 ? 0 : p_idx + 1].y, 2)); float length2 = sqrt(pow(p[p_idx].x - p[p_idx - 1 < 0 ? 3 : p_idx - 1].x, 2) + pow(p[p_idx].y - p[p_idx - 1 < 0 ? 3 : p_idx - 1].y, 2)); four_side[p_idx] = MIN(length1, length2); } float _0_1 = sqrt(pow(p[0].x - p[1].x, 2) + pow(p[0].y - p[1].y, 2)); float _2_3 = sqrt(pow(p[2].x - p[3].x, 2) + pow(p[2].y - p[3].y, 2)); float _0_3 = sqrt(pow(p[0].x - p[3].x, 2) + pow(p[0].y - p[3].y, 2)); float _1_2 = sqrt(pow(p[2].x - p[1].x, 2) + pow(p[2].y - p[1].y, 2)); // Find longer side if (_0_1 + _2_3 > _1_2 + _0_3) { // p0, p1 double theta = atan2(p[1].y - p[0].y, p[1].x - p[0].x); poly[poly_idx][0].x += R*four_side[0] * cos(theta); poly[poly_idx][0].y += R*four_side[0] * sin(theta); poly[poly_idx][1].x -= R*four_side[1] * cos(theta); poly[poly_idx][1].y -= R*four_side[1] * sin(theta); // p2, p3 theta = atan2(p[2].y - p[3].y, p[2].x - p[3].x); poly[poly_idx][3].x += R*four_side[3] * cos(theta); poly[poly_idx][3].y += R*four_side[3] * sin(theta); poly[poly_idx][2].x -= R*four_side[2] * cos(theta); poly[poly_idx][2].y -= R*four_side[2] * sin(theta); // p0, p3 theta = atan2(p[3].y - p[0].y, p[3].x - p[0].x); poly[poly_idx][0].x += R*four_side[0] * cos(theta); poly[poly_idx][0].y += R*four_side[0] * sin(theta); poly[poly_idx][3].x -= R*four_side[3] * cos(theta); poly[poly_idx][3].y -= R*four_side[3] * sin(theta); // p1, p2 theta = atan2(p[1].y - p[2].y, p[1].x - p[2].x); poly[poly_idx][2].x += R*four_side[2] * cos(theta); poly[poly_idx][2].y += R*four_side[2] * sin(theta); poly[poly_idx][1].x -= R*four_side[1] * cos(theta); poly[poly_idx][1].y -= R*four_side[1] * sin(theta); } else { // p0, p3 double theta = atan2(p[3].y - p[0].y, p[3].x - p[0].x); poly[poly_idx][0].x += R*four_side[0] * cos(theta); poly[poly_idx][0].y += R*four_side[0] * sin(theta); poly[poly_idx][3].x -= R*four_side[3] * cos(theta); poly[poly_idx][3].y -= R*four_side[3] * sin(theta); // p1, p2 theta = atan2(p[1].y - p[2].y, p[1].x - p[2].x); poly[poly_idx][2].x += R*four_side[2] * cos(theta); poly[poly_idx][2].y += R*four_side[2] * sin(theta); poly[poly_idx][1].x -= R*four_side[1] * cos(theta); poly[poly_idx][1].y -= R*four_side[1] * sin(theta); // p0, p1 theta = atan2(p[1].y - p[0].y, p[1].x - p[0].x); poly[poly_idx][0].x += R*four_side[0] * cos(theta); poly[poly_idx][0].y += R*four_side[0] * sin(theta); poly[poly_idx][1].x -= R*four_side[1] * cos(theta); poly[poly_idx][1].y -= R*four_side[1] * sin(theta); // p2, p3 theta = atan2(p[2].y - p[3].y, p[2].x - p[3].x); poly[poly_idx][3].x += R*four_side[3] * cos(theta); poly[poly_idx][3].y += R*four_side[3] * sin(theta); poly[poly_idx][2].x -= R*four_side[2] * cos(theta); poly[poly_idx][2].y -= R*four_side[2] * sin(theta); } } return poly; } double distance_to_Line(cv::Point2f line_start, cv::Point2f line_end, cv::Point2f point) { /* Calculate point-to-line distance */ double normalLength = hypot(line_end.x - line_start.x, line_end.y - line_start.y); double distance = (double)((point.x - line_start.x) * (line_end.y - line_start.y) - (point.y - line_start.y) * (line_end.x - line_start.x)) / MAX(normalLength,0.0001); return abs(distance); } void balance_BF(float* conf_data, float fg_ratio, int* mask_data, int out_height_, int out_width_){ /* Random select foreground and background pixels Args: conf_data: score_map of the segmentation fg_ratio: the ratio of foreground pixels / background pixels mask_data: the mask (weight) of score_map out_height_: height of score_map out_width_: width of score_map */ vector<int> fg_inds; fg_inds.clear(); vector<int> bg_inds; bg_inds.clear(); for (int h = 0; h < out_height_; h++) { for (int w = 0; w < out_width_; w++) { int index = h*out_width_ + w; if ((conf_data[index] - 0)<1e-5) { bg_inds.push_back(index); } else { fg_inds.push_back(index); } } } int num_fg_all = fg_inds.size(); int num_bg_all = bg_inds.size(); if (num_bg_all * fg_ratio > num_fg_all){ random_shuffle(bg_inds.begin(), bg_inds.end()); for (int i = 0; i < num_bg_all * fg_ratio - num_fg_all; i++) { if (mask_data != NULL){ mask_data[bg_inds[i]] = 0; } } } } extern "C" void parse_east_data(int height, int width, int* gt_boxes, int gt_boxes_size, int* gt_boxes_ignore, int gt_boxes_ignore_size, int pool_ratio, int geometry, //0 RBOX 1 QUAD int label_shape, // 0 normal 1 gaussian float shrink_ratio, float ignore_ratio, float* gt_score_map, int* gt_score_map_mask, float* gt_geo_data, float* gt_geo_weight, int seed) { srand(seed); int out_height_ = height / pool_ratio; int out_width_ = width / pool_ratio; cv::Mat conf_origin = cv::Mat::zeros(height, width, CV_32FC1); cv::Mat geo_origin; cv::Mat geo_mask_origin; cv::Mat temp_N_Q_data; // Output Initialization for (int i = 0; i < out_height_ * out_width_; i++){ gt_score_map[i] = 0; gt_score_map_mask[i] = 1; } if (geometry == 0) { //RBOX for (int i = 0; i < 5 * out_height_ * out_width_; i++){ gt_geo_data[i] = 0; gt_geo_weight[i] = 0; } } else if (geometry == 1) { //QUAD for (int i = 0; i < 8 * out_height_ * out_width_; i++){ gt_geo_data[i] = 0; gt_geo_weight[i] = 0; } } // Get ignore bboxes, fill all ignore boxes with label 64 and set gt_score_map_mask to 0 vector<vector<cv::Point> > poly_ignore; poly_ignore.clear(); for (int i = 0; i < gt_boxes_ignore_size; i++) { vector<cv::Point> poly_tmp; for (int j = 0; j<8; j += 2) { poly_tmp.push_back(cv::Point(gt_boxes_ignore[i * 8 + j], gt_boxes_ignore[i * 8 + j + 1])); } poly_ignore.push_back(poly_tmp); } cv::fillPoly(conf_origin, poly_ignore, 64); for (int h = 0; h < out_height_; h++) { for (int w = 0; w < out_width_; w++) { if (conf_origin.at<float>(int(pool_ratio*h), int(pool_ratio*w)) == 64) { gt_score_map_mask[h*out_width_ + w] = 0; } } } // Get cared bboxes vector<vector<cv::Point> > poly; poly.clear(); for (int i = 0; i < gt_boxes_size; i++) { vector<cv::Point> poly_tmp; for (int j = 0; j < 8; j += 2){ poly_tmp.push_back(cv::Point(gt_boxes[i * 8 + j], gt_boxes[i * 8 + j + 1])); } poly.push_back(poly_tmp); } // Shrink bboxes vector<vector<cv::Point> > shrinked_poly = Shrink_Poly(poly, shrink_ratio); // Use conf_origin == 1 to mark cared bboxes //cv::fillPoly(conf_origin, shrinked_poly, 1); // for (int poly_idx = 0; poly_idx < poly.size(); ++poly_idx) { vector<cv::Point> point_tmp = poly[poly_idx]; // Use conf_origin_tmp == 1 to mark cared bboxes cv::Mat conf_origin_tmp = cv::Mat::zeros(height, width, CV_32FC1); vector<vector<cv::Point> > shrink_poly_tmps; shrink_poly_tmps.push_back(shrinked_poly[poly_idx]); cv::fillPoly(conf_origin_tmp, shrink_poly_tmps, 1); float center_x, center_y, sigma; if (label_shape == 1) { // If generate score map in Gaussian mode, we need to calculate the center point and sigma vector<cv::Point> shrink_poly_tmp = shrinked_poly[poly_idx]; float shrinked_four_side[4] = { 0 }; for (int p_idx = 0; p_idx < 4; ++p_idx) { shrinked_four_side[p_idx] = sqrt(pow(shrink_poly_tmp[p_idx].x - shrink_poly_tmp[p_idx + 1 > 3 ? 0 : p_idx + 1].x, 2) + pow(shrink_poly_tmp[p_idx].y - shrink_poly_tmp[p_idx + 1 > 3 ? 0 : p_idx + 1].y, 2));; } float shrink_poly_h = MAX(shrinked_four_side[1], shrinked_four_side[3]); float shrink_poly_w = MAX(shrinked_four_side[0], shrinked_four_side[2]); sigma = MAX(shrink_poly_h, shrink_poly_w) / 2 * 0.7485; center_x = (shrink_poly_tmp[0].x + shrink_poly_tmp[1].x + shrink_poly_tmp[2].x + shrink_poly_tmp[3].x) / 4.; center_y = (shrink_poly_tmp[0].y + shrink_poly_tmp[1].y + shrink_poly_tmp[2].y + shrink_poly_tmp[3].y) / 4.; } if (geometry == 0) { /********** RBOX **********/ cv::RotatedRect rbox = cv::minAreaRect(point_tmp); cv::Point2f vertices[4]; rbox.points(vertices); float angle = rbox.angle; // Switch order cv::Point2f min_area_box[4]; if (abs(angle) > 45.0) { angle = -(90.0 + angle) / 180.0*3.1415926535897; min_area_box[0] = vertices[2]; min_area_box[1] = vertices[3]; min_area_box[2] = vertices[0]; min_area_box[3] = vertices[1]; } else { angle = abs(angle) / 180.0*3.1415926535897; min_area_box[0] = vertices[1]; min_area_box[1] = vertices[2]; min_area_box[2] = vertices[3]; min_area_box[3] = vertices[0]; } // Generate final gt target for each box for (int h = 0; h < out_height_; ++h) { for (int w = 0; w < out_width_; ++w) { if (conf_origin_tmp.at<float>(h * pool_ratio, w * pool_ratio) == 1) { // generate score map for each bbox if (label_shape == 1) { // if using gaussian score map gt_score_map[h*out_width_ + w] = exp(-0.5 / pow(sigma, 2) * (pow(h*pool_ratio - center_y, 2) + pow(w*pool_ratio - center_x, 2))); } else { // if using normal score map gt_score_map[h*out_width_ + w] = 1; } // generate geo map for each bbox gt_geo_data[0*out_height_*out_width_ + h*out_width_ + w] = (float)distance_to_Line(min_area_box[0], min_area_box[1], cv::Point2f(w * pool_ratio, h * pool_ratio)); gt_geo_data[1*out_height_*out_width_ + h*out_width_ + w] = (float)distance_to_Line(min_area_box[1], min_area_box[2], cv::Point2f(w * pool_ratio, h * pool_ratio)); gt_geo_data[2*out_height_*out_width_ + h*out_width_ + w] = (float)distance_to_Line(min_area_box[2], min_area_box[3], cv::Point2f(w * pool_ratio, h * pool_ratio)); gt_geo_data[3*out_height_*out_width_ + h*out_width_ + w] = (float)distance_to_Line(min_area_box[3], min_area_box[0], cv::Point2f(w * pool_ratio, h * pool_ratio)); gt_geo_data[4*out_height_*out_width_ + h*out_width_ + w] = (float)angle; for (int k = 0; k < 5; k++) { gt_geo_weight[k*out_height_*out_width_ + h*out_width_ + w] = 1; } } } } } else if (geometry == 1) { /********** QUAD **********/ float four_side[4] = { 0 }; for (int p_idx = 0; p_idx < 4; ++p_idx) { four_side[p_idx] = sqrt(pow(point_tmp[p_idx].x - point_tmp[(p_idx + 1) % 4].x, 2) + pow(point_tmp[p_idx].y - point_tmp[(p_idx + 1)%4].y, 2)); } // Generate final gt target for each box for (int h = 0; h < out_height_; ++h) { for (int w = 0; w < out_width_; ++w) { if (conf_origin_tmp.at<float>(h * pool_ratio, w * pool_ratio) == 1) { // generate score map for each bbox if (label_shape == 1) { // if using gaussian score map gt_score_map[h*out_width_ + w] = exp(-0.5 / pow(sigma, 2) * (pow(h*pool_ratio - center_y, 2) + pow(w*pool_ratio - center_x, 2))); } else { // if using normal score map gt_score_map[h*out_width_ + w] = 1; } // generate geo map for each bbox for (int k = 0; k < 4; ++k ) { gt_geo_data[2*k*out_height_*out_width_ + h*out_width_ + w] = point_tmp[k].x - w*pool_ratio; gt_geo_data[(2*k+1)*out_height_*out_width_ + h*out_width_ + w] = point_tmp[k].y - h*pool_ratio; // Balance large text and small text according to their side length float min_side = four_side[k]<four_side[(k + 1) % 4] ? four_side[k] : four_side[(k + 1) % 4]; gt_geo_weight[2*k*out_height_*out_width_ + h*out_width_ + w] = 1./(min_side + 1e-7); gt_geo_weight[(2*k+1)*out_height_*out_width_ + h*out_width_ + w] = 1./(min_side + 1e-7); } } } } } } balance_BF(gt_score_map, ignore_ratio, gt_score_map_mask, out_height_, out_width_); }
33.935561
168
0.58457
[ "geometry", "vector" ]
b945006cdaa553435d936e72911a146374a94e7c
5,140
cpp
C++
src/libtsduck/tsAbstractTable.cpp
mypopydev/tsduck
38e29aa7ba82d0d07ca926a4e37a7f6d167089d3
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/tsAbstractTable.cpp
mypopydev/tsduck
38e29aa7ba82d0d07ca926a4e37a7f6d167089d3
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/tsAbstractTable.cpp
mypopydev/tsduck
38e29aa7ba82d0d07ca926a4e37a7f6d167089d3
[ "BSD-2-Clause" ]
null
null
null
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2019, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- #include "tsAbstractTable.h" #include "tsBinaryTable.h" TSDUCK_SOURCE; //---------------------------------------------------------------------------- // Constructors and destructors. //---------------------------------------------------------------------------- ts::AbstractTable::AbstractTable(TID tid, const UChar* xml_name, Standards standards) : AbstractSignalization(xml_name, standards), _table_id(tid) { } ts::AbstractTable::~AbstractTable() { } //---------------------------------------------------------------------------- // Entry base class implementation. //---------------------------------------------------------------------------- ts::AbstractTable::EntryWithDescriptors::EntryWithDescriptors(const AbstractTable* table) : descs(table) { } ts::AbstractTable::EntryWithDescriptors::EntryWithDescriptors(const AbstractTable* table, const EntryWithDescriptors& other) : descs(table, other.descs) { } ts::AbstractTable::EntryWithDescriptors& ts::AbstractTable::EntryWithDescriptors::operator=(const EntryWithDescriptors& other) { if (&other != this) { // Copying the descriptor list preserves the associated table of the target. descs = other.descs; } return *this; } ts::AbstractTable::EntryWithDescriptors& ts::AbstractTable::EntryWithDescriptors::operator=(EntryWithDescriptors&& other) noexcept { if (&other != this) { // Moving the descriptor list preserves the associated table of the target. descs = std::move(other.descs); } return *this; } //---------------------------------------------------------------------------- // This method checks if a table id is valid for this object. //---------------------------------------------------------------------------- bool ts::AbstractTable::isValidTableId(TID tid) const { // The default implementation checks that the TID is identical to the TID of this object. return tid == _table_id; } //---------------------------------------------------------------------------- // This method serializes a table. //---------------------------------------------------------------------------- void ts::AbstractTable::serialize(DuckContext& duck, BinaryTable& table) const { // Reinitialize table object. table.clear(); // Return an empty table if this object is not valid. if (!_is_valid) { return; } // Call the subclass implementation. serializeContent(duck, table); // Add the standards of the serialized table into the context. duck.addStandards(definingStandards()); } //---------------------------------------------------------------------------- // This method deserializes a binary table. //---------------------------------------------------------------------------- void ts::AbstractTable::deserialize(DuckContext& duck, const BinaryTable& table) { // Invalidate this object. // Note that deserializeContent() is still responsible for clearing specific fields. _is_valid = false; // Keep this object invalid if the binary table is invalid or has an incorrect table if for this class. if (!table.isValid() || !isValidTableId(table.tableId())) { return; } // Table is already checked to be compatible but can be different from current one. // So, we need to update this object. _table_id = table.tableId(); // Call the subclass implementation. deserializeContent(duck, table); // Add the standards of the deserialized table into the context. duck.addStandards(definingStandards()); }
36.453901
130
0.597276
[ "object" ]
b94db18649bf1531e84e58a33e5c7bb0bca4a3d1
4,034
hpp
C++
include/doo_ecs/System.hpp
TerensTare/tnt
916067a9bf697101afb1d0785112aa34014e8126
[ "MIT" ]
29
2020-04-22T01:31:30.000Z
2022-02-03T12:21:29.000Z
include/doo_ecs/System.hpp
TerensTare/tnt
916067a9bf697101afb1d0785112aa34014e8126
[ "MIT" ]
6
2020-04-17T10:31:56.000Z
2021-09-10T12:07:22.000Z
include/doo_ecs/System.hpp
TerensTare/tnt
916067a9bf697101afb1d0785112aa34014e8126
[ "MIT" ]
7
2020-03-13T01:50:41.000Z
2022-03-06T23:44:29.000Z
#ifndef TNT_DOO_ECS_SYSTEM_UTILITIES_HPP #define TNT_DOO_ECS_SYSTEM_UTILITIES_HPP #include <concepts> #include <nlohmann/json_fwd.hpp> #include "doo_ecs/Base.hpp" #include "types/SparseSet.hpp" #include "types/TypeUtils.hpp" // TODO: // noexcept // draw_imgui // TODO(maybe): // store base() in a member reference ?? namespace tnt::doo { #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace detail { template <typename T> concept void_type = std::is_void_v<T>; } // namespace detail #endif // clang-format off /// @brief A concept representing the minimal requirements that a type must fulfill to be a DOO ECS system. template <typename T> concept system = requires { typename T::component; } and requires (T &t, object const& o, nlohmann::json& j, typename T::component const& c) { { t.add_object(o, c) } -> detail::void_type; { t.remove(o) } -> detail::void_type; { t.Update(o, 1.f) } -> detail::void_type; { t.from_json(o, j) } -> detail::void_type; { t.to_json(o, j) } -> detail::void_type; // TODO: draw_imgui; { t.active } -> std::same_as<tnt::sparse_set<tnt::doo::object>>; }; // clang-format on /// @brief A helper class for defining custom DOO ECS systems. /// @tparam T The class that will be used as a system. template <system T> struct system_base : crtp<T> { static_assert(std::is_class_v<T> and std::is_same_v<T, std::remove_cv_t<T>>); static_assert(std::is_base_of_v<system_base<T>, T>, "system T must derive from tnt::doo::system_base<T>!!"); using component = typename T::component; /// < The component type stored by this system. /// @brief Add the data of the object with given id to the system. /// @param id The id of the object. /// @param c The component data. inline void add_object(object const &id, component const &c) noexcept( noexcept(this->base().add_object(id, c))) { this->base().add_object(id, c); } /// @brief Update the data of the desired object. /// @param id The id of the object. /// @param time_ The time elapsed since the last Update call. inline void Update(object const &id, float time_) noexcept( noexcept(this->base().Update(id, time_))) { this->base().Update(id, time_); } /// @brief Remove the data of the desired object from the system. /// @param id The id of the object to remove. inline void remove(object const &id) noexcept( noexcept(this->base().remove(id))) { this->base().remove(id); } /// @brief Remove the data of all the objects from the system. inline void clear() { if constexpr (requires { this->base().clear(); }) this->base().clear(); else for (auto const &active = this->base().active; auto const &o : active) this->base().remove(o); } /// @brief Load the data of an object from a json chunk. /// @param id The id of the desired object. /// @param j The json chunk containing the data of the component. inline void from_json(object const &id, nlohmann::json const &j) noexcept( noexcept(this->base().from_json(id, j))) { this->base().from_json(id, j); } /// @brief Serialize the component data of the given object to a json chunk. /// @param id The id of the desired object. /// @param j The json chunk where the data will be stored. inline void to_json(object const &id, nlohmann::json &j) noexcept( noexcept(this->base().to_json(id, j))) { this->base().to_json(id, j); } // TODO: draw_imgui }; } // namespace tnt::doo #endif //!TNT_DOO_ECS_SYSTEM_UTILITIES_HPP
34.478632
116
0.584036
[ "object" ]
b94f64c58d3aac913f5d3b27dffb73d929a445b1
27,060
cpp
C++
src/services/cuptitrace/CuptiTrace.cpp
daboehme/Caliper
38e2fc9a703601801ea8223a0bbd53795b6a0a3a
[ "BSD-3-Clause" ]
null
null
null
src/services/cuptitrace/CuptiTrace.cpp
daboehme/Caliper
38e2fc9a703601801ea8223a0bbd53795b6a0a3a
[ "BSD-3-Clause" ]
null
null
null
src/services/cuptitrace/CuptiTrace.cpp
daboehme/Caliper
38e2fc9a703601801ea8223a0bbd53795b6a0a3a
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, Lawrence Livermore National Security, LLC. // See top-level LICENSE file for details. // CuptiTrace.cpp // Implementation of the CUpti trace service #include "caliper/CaliperService.h" #include "caliper/Caliper.h" #include "caliper/SnapshotRecord.h" #include "caliper/common/Log.h" #include "caliper/common/Node.h" #include "caliper/common/RuntimeConfig.h" #include "caliper/common/c-util/unitfmt.h" #include <cupti.h> #include <cuda_runtime_api.h> #include <nvToolsExt.h> #if CUDART_VERSION >= 9000 #include <nvToolsExtSync.h> #endif #include <generated_nvtx_meta.h> #include <iomanip> #include <iterator> #include <mutex> #include <sstream> #include <unordered_map> using namespace cali; namespace { class CuptiTraceService { static const ConfigSet::Entry s_configdata[]; struct ActivityBuffer { uint8_t* buffer; CUcontext ctx; uint32_t stream_id; size_t size; size_t valid_size; ActivityBuffer* next; ActivityBuffer* prev; ActivityBuffer(CUcontext ctx_, uint32_t stream_, uint8_t* buffer_, size_t size_, size_t valid_size_) : buffer(buffer_), ctx(ctx_), stream_id(stream_), size(size_), valid_size(valid_size_), next(nullptr), prev(nullptr) { } void unlink() { if (next) next->prev = prev; if (prev) prev->next = next; } }; struct DeviceInfo { uint32_t id; const char* name; CUuuid uuid; std::string uuid_string; }; std::map<uint32_t, DeviceInfo> device_info_map; size_t buffer_size = 1 * 1024 * 1024; size_t buffer_size_used = 0; ActivityBuffer* retired_buffers_list = nullptr; std::mutex retired_buffers_list_lock; unsigned num_buffers_empty = 0; unsigned num_buffers_allocated = 0; unsigned num_buffers_completed = 0; unsigned num_dropped_records = 0; unsigned num_correlation_recs = 0; unsigned num_device_recs = 0; unsigned num_kernel_recs = 0; unsigned num_driver_recs = 0; unsigned num_memcpy_recs = 0; unsigned num_runtime_recs = 0; unsigned num_unknown_recs = 0; unsigned num_correlations_found = 0; unsigned num_correlations_missed = 0; Attribute activity_start_attr; Attribute activity_end_attr; Attribute activity_duration_attr; Attribute activity_kind_attr; Attribute kernel_name_attr; Attribute memcpy_kind_attr; Attribute memcpy_bytes_attr; Attribute starttime_attr; Attribute timestamp_attr; Attribute duration_attr; Attribute device_uuid_attr; bool record_host_timestamp = false; bool record_host_duration = false; static CuptiTraceService* s_instance; typedef std::unordered_map<uint32_t, uint64_t> correlation_id_map_t; // --- Helpers // static void print_cupti_error(std::ostream& os, CUptiResult err, const char* func) { const char* errstr; cuptiGetResultString(err, &errstr); os << "cupti: " << func << ": error: " << errstr << std::endl; } // --- CUpti buffer management callbacks // static void CUPTIAPI buffer_requested(uint8_t** buffer, size_t* size, size_t* max_num_recs) { *buffer = new uint8_t[s_instance->buffer_size]; *size = s_instance->buffer_size; *max_num_recs = 0; ++s_instance->num_buffers_allocated; } void add_completed_buffer(ActivityBuffer* acb, size_t dropped) { if (!acb->valid_size) ++num_buffers_empty; num_dropped_records += dropped; std::lock_guard<std::mutex> g(retired_buffers_list_lock); if (retired_buffers_list) retired_buffers_list->prev = acb; acb->next = retired_buffers_list; retired_buffers_list = acb; ++num_buffers_completed; } static void CUPTIAPI buffer_completed(CUcontext ctx, uint32_t stream, uint8_t* buffer, size_t size, size_t valid_size) { ActivityBuffer* acb = new ActivityBuffer(ctx, stream, buffer, size, valid_size); size_t dropped = 0; cuptiActivityGetNumDroppedRecords(ctx, stream, &dropped); s_instance->add_completed_buffer(acb, dropped); } // --- Caliper flush // const char* get_memcpy_kind_string(CUpti_ActivityMemcpyKind kind) { switch (kind) { case CUPTI_ACTIVITY_MEMCPY_KIND_HTOD: return "HtoD"; case CUPTI_ACTIVITY_MEMCPY_KIND_DTOH: return "DtoH"; case CUPTI_ACTIVITY_MEMCPY_KIND_HTOA: return "HtoA"; case CUPTI_ACTIVITY_MEMCPY_KIND_ATOH: return "AtoH"; case CUPTI_ACTIVITY_MEMCPY_KIND_ATOA: return "AtoA"; case CUPTI_ACTIVITY_MEMCPY_KIND_ATOD: return "AtoD"; case CUPTI_ACTIVITY_MEMCPY_KIND_DTOA: return "DtoA"; case CUPTI_ACTIVITY_MEMCPY_KIND_DTOD: return "DtoD"; case CUPTI_ACTIVITY_MEMCPY_KIND_HTOH: return "HtoH"; default: break; } return "<unknown>"; } size_t flush_record(CUpti_Activity* rec, correlation_id_map_t& correlation_map, Caliper* c, const SnapshotRecord* flush_info, SnapshotFlushFn proc_fn) { switch (rec->kind) { case CUPTI_ACTIVITY_KIND_DEVICE: { CUpti_ActivityDevice2* device = reinterpret_cast<CUpti_ActivityDevice2*>(rec); DeviceInfo info; info.id = device->id; info.name = device->name; info.uuid = device->uuid; { // make a string with the uuid bytes in hex representation std::ostringstream os; std::copy(device->uuid.bytes, device->uuid.bytes+sizeof(device->uuid.bytes), std::ostream_iterator<unsigned>(os << std::hex << std::setw(2) << std::setfill('0'))); info.uuid_string = os.str(); } device_info_map[device->id] = info; ++num_device_recs; return 0; } case CUPTI_ACTIVITY_KIND_EXTERNAL_CORRELATION: { CUpti_ActivityExternalCorrelation* exco = reinterpret_cast<CUpti_ActivityExternalCorrelation*>(rec); if (exco->externalKind == CUPTI_EXTERNAL_CORRELATION_KIND_CUSTOM0) correlation_map[exco->correlationId] = exco->externalId; ++num_correlation_recs; return 0; } case CUPTI_ACTIVITY_KIND_DRIVER: { CUpti_ActivityAPI* api = reinterpret_cast<CUpti_ActivityAPI*>(rec); ++num_driver_recs; return 0; } case CUPTI_ACTIVITY_KIND_RUNTIME: { CUpti_ActivityAPI* api = reinterpret_cast<CUpti_ActivityAPI*>(rec); ++num_runtime_recs; return 0; } case CUPTI_ACTIVITY_KIND_MEMCPY: { CUpti_ActivityMemcpy* memcpy = reinterpret_cast<CUpti_ActivityMemcpy*>(rec); Node* parent = nullptr; // find a Caliper context correlation, if any auto it = correlation_map.find(memcpy->correlationId); if (it != correlation_map.end()) { parent = c->node(it->second); ++num_correlations_found; correlation_map.erase(it); } else { ++num_correlations_missed; } // find a device info record { auto it = device_info_map.find(memcpy->deviceId); if (it != device_info_map.end()) parent = c->make_tree_entry(device_uuid_attr, Variant(CALI_TYPE_STRING, it->second.uuid_string.c_str(), it->second.uuid_string.size() + 1), parent); } // append the memcpy info Attribute attr[6] = { activity_kind_attr, memcpy_kind_attr, memcpy_bytes_attr, activity_start_attr, activity_end_attr, activity_duration_attr }; Variant data[6] = { Variant(CALI_TYPE_STRING, "memcpy", 7), Variant(CALI_TYPE_STRING, get_memcpy_kind_string(static_cast<CUpti_ActivityMemcpyKind>(memcpy->copyKind)), 5), Variant(cali_make_variant_from_uint(memcpy->bytes)), Variant(cali_make_variant_from_uint(memcpy->start)), Variant(cali_make_variant_from_uint(memcpy->end)), Variant(cali_make_variant_from_uint(memcpy->end - memcpy->start)) }; SnapshotRecord::FixedSnapshotRecord<8> snapshot_data; SnapshotRecord snapshot(snapshot_data); c->make_record(6, attr, data, snapshot, parent); proc_fn(*c, snapshot.to_entrylist()); ++num_memcpy_recs; return 1; } case CUPTI_ACTIVITY_KIND_KERNEL: case CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL: { CUpti_ActivityKernel4* kernel = reinterpret_cast<CUpti_ActivityKernel4*>(rec); Node* parent = nullptr; // find a Caliper context correlation, if any { auto it = correlation_map.find(kernel->correlationId); if (it != correlation_map.end()) { parent = c->node(it->second); ++num_correlations_found; correlation_map.erase(it); } else { ++num_correlations_missed; } } // find a device info record { auto it = device_info_map.find(kernel->deviceId); if (it != device_info_map.end()) parent = c->make_tree_entry(device_uuid_attr, Variant(CALI_TYPE_STRING, it->second.uuid_string.c_str(), it->second.uuid_string.size() + 1), parent); } // append the kernel info Attribute attr[5] = { activity_kind_attr, kernel_name_attr, activity_start_attr, activity_end_attr, activity_duration_attr }; Variant data[5] = { Variant(CALI_TYPE_STRING, "kernel", 7), Variant(CALI_TYPE_STRING, kernel->name, strlen(kernel->name)+1), Variant(cali_make_variant_from_uint(kernel->start)), Variant(cali_make_variant_from_uint(kernel->end)), Variant(cali_make_variant_from_uint(kernel->end - kernel->start)) }; SnapshotRecord::FixedSnapshotRecord<8> snapshot_data; SnapshotRecord snapshot(snapshot_data); c->make_record(5, attr, data, snapshot, parent); proc_fn(*c, snapshot.to_entrylist()); ++num_kernel_recs; return 1; } default: ++num_unknown_recs; } return 0; } size_t flush_buffer(ActivityBuffer* acb, Caliper* c, const SnapshotRecord* flush_info, SnapshotFlushFn proc_fn) { if (! (acb->valid_size > 0)) return 0; size_t num_records = 0; CUpti_Activity* rec = nullptr; CUptiResult res = CUPTI_SUCCESS; correlation_id_map_t correlation_map(2000); do { res = cuptiActivityGetNextRecord(acb->buffer, acb->valid_size, &rec); if (res == CUPTI_SUCCESS) num_records += flush_record(rec, correlation_map, c, flush_info, proc_fn); } while (res == CUPTI_SUCCESS); if (res != CUPTI_SUCCESS && res != CUPTI_ERROR_MAX_LIMIT_REACHED) print_cupti_error(Log(0).stream(), res, "cuptiActivityGetNextRecord"); return num_records; } // --- Caliper callbacks // void flush_cb(Caliper* c, Channel* chn, const SnapshotRecord* flush_info, SnapshotFlushFn proc_fn) { // Flush CUpti. Apppends all currently active CUpti trace buffers // to the retired_buffers_list. CUptiResult res = cuptiActivityFlushAll(CUPTI_ACTIVITY_FLAG_NONE); if (res != CUPTI_SUCCESS) { print_cupti_error(Log(0).stream(), res, "cuptiActivityFlushAll"); return; } // go through all stored buffers and flush them ActivityBuffer* acb = nullptr; { std::lock_guard<std::mutex> g(retired_buffers_list_lock); acb = retired_buffers_list; } size_t num_written = 0; for ( ; acb; acb = acb->next ) num_written += flush_buffer(acb, c, flush_info, proc_fn); Log(1).stream() << "cuptitrace: Wrote " << num_written << " records." << std::endl; } void clear_cb(Caliper* c, Channel* chn) { ActivityBuffer* acb = nullptr; { std::lock_guard<std::mutex> g(retired_buffers_list_lock); acb = retired_buffers_list; retired_buffers_list = nullptr; } while (acb) { ActivityBuffer* tmp = acb->next; buffer_size_used += acb->valid_size; acb->unlink(); delete[] acb->buffer; delete acb; acb = tmp; } } void post_begin_cb(Caliper* c, Channel* chn, const Attribute& attr, const Variant& value) { if (attr.is_nested()) { Entry e = c->get(attr); if (e.is_reference()) { CUptiResult res = cuptiActivityPushExternalCorrelationId(CUPTI_EXTERNAL_CORRELATION_KIND_CUSTOM0, e.node()->id()); if (res != CUPTI_SUCCESS) print_cupti_error(Log(0).stream(), res, "cuptiActivityPushExternalCorrelationId"); } } } void pre_end_cb(Caliper* c, Channel* chn, const Attribute& attr, const Variant& value) { if (attr.is_nested()) { CUptiResult res = cuptiActivityPopExternalCorrelationId(CUPTI_EXTERNAL_CORRELATION_KIND_CUSTOM0, nullptr); if (res != CUPTI_SUCCESS) print_cupti_error(Log(0).stream(), res, "cuptiActivityPopExternalCorrelationId"); } } void finish_cb(Caliper* c, Channel* chn) { cuptiFinalize(); if (Log::verbosity() < 1) return; if (num_dropped_records > 0) Log(1).stream() << chn->name() << ": cuptitrace: Dropped " << num_dropped_records << " records." << std::endl; unitfmt_result bytes_reserved = unitfmt(num_buffers_completed * buffer_size, unitfmt_bytes); unitfmt_result bytes_used = unitfmt(buffer_size_used, unitfmt_bytes); Log(1).stream() << chn->name() << ": cuptitrace: Allocated " << num_buffers_allocated << " buffers (" << bytes_reserved.val << bytes_reserved.symbol << " reserved, " << bytes_used.val << bytes_used.symbol << " used). " << num_buffers_completed << " buffers completed, " << num_buffers_empty << " empty." << std::endl; if (Log::verbosity() < 2) return; Log(2).stream() << chn->name() << ": cuptitrace: Processed CUpti activity records:" << "\n correlation records: " << num_correlation_recs << "\n device records: " << num_device_recs << "\n driver records: " << num_driver_recs << "\n runtime records: " << num_runtime_recs << "\n kernel records: " << num_kernel_recs << "\n memcpy records: " << num_memcpy_recs << "\n unknown records: " << num_unknown_recs << std::endl; Log(2).stream() << chn->name() << ": cuptitrace: " << num_correlations_found << " context correlations found, " << num_correlations_missed << " missed." << std::endl; } void enable_cupti_activities(const ConfigSet& config) { struct activity_map_t { const char* name; CUpti_ActivityKind kind; } activity_map[] = { { "correlation", CUPTI_ACTIVITY_KIND_EXTERNAL_CORRELATION }, { "device", CUPTI_ACTIVITY_KIND_DEVICE }, { "driver", CUPTI_ACTIVITY_KIND_DRIVER }, { "runtime", CUPTI_ACTIVITY_KIND_RUNTIME }, { "kernel", CUPTI_ACTIVITY_KIND_KERNEL }, { "memcpy", CUPTI_ACTIVITY_KIND_MEMCPY }, { nullptr, CUPTI_ACTIVITY_KIND_INVALID } }; std::vector<std::string> selection = config.get("activities").to_stringlist(); for (const activity_map_t* act = activity_map; act && act->name; ++act) { auto it = std::find(selection.begin(), selection.end(), act->name); if (it == selection.end()) continue; selection.erase(it); CUptiResult res = cuptiActivityEnable(act->kind); if (res != CUPTI_SUCCESS) { const char* errstr; cuptiGetResultString(res, &errstr); Log(0).stream() << "cuptitrace: cuptiActivityEnable (" << act->name << "): " << errstr << std::endl; } } for (const std::string& s : selection) Log(0).stream() << "cuptitrace: selected activity \"" << s << "\" not found!" << std::endl; } void snapshot_cb(Caliper* c, Channel* chn, int scopes, const SnapshotRecord* trigger_info, SnapshotRecord* snapshot) { uint64_t timestamp = 0; cuptiGetTimestamp(&timestamp); Variant v_now(cali_make_variant_from_uint(timestamp)); Variant v_prev = c->exchange(timestamp_attr, v_now); if (record_host_duration) snapshot->append(duration_attr.id(), Variant(cali_make_variant_from_uint(timestamp - v_prev.to_uint()))); } void post_init_cb(Caliper* c, Channel* chn) { ConfigSet config = chn->config().init("cuptitrace", s_configdata); enable_cupti_activities(config); CUptiResult res = cuptiActivityRegisterCallbacks(buffer_requested, buffer_completed); if (res != CUPTI_SUCCESS) { print_cupti_error(Log(0).stream(), res, "cuptiActivityRegisterCallbacks"); return; } uint64_t starttime = 0; cuptiGetTimestamp(&starttime); c->set(starttime_attr, cali_make_variant_from_uint(starttime)); if (config.get("correlate_context").to_bool()) { chn->events().post_begin_evt.connect( [](Caliper* c, Channel* chn, const Attribute& attr, const Variant& value){ s_instance->post_begin_cb(c, chn, attr, value); }); chn->events().pre_end_evt.connect( [](Caliper* c, Channel* chn, const Attribute& attr, const Variant& value){ s_instance->pre_end_cb(c, chn, attr, value); }); } if (record_host_timestamp || record_host_duration) { c->set(timestamp_attr, cali_make_variant_from_uint(starttime)); chn->events().snapshot.connect( [](Caliper* c, Channel* chn, int scopes, const SnapshotRecord* info, SnapshotRecord* rec){ s_instance->snapshot_cb(c, chn, scopes, info, rec); }); } chn->events().flush_evt.connect( [](Caliper* c, Channel* chn, const SnapshotRecord* info, SnapshotFlushFn flush_fn){ s_instance->flush_cb(c, chn, info, flush_fn); }); chn->events().clear_evt.connect( [](Caliper* c, Channel* chn){ s_instance->clear_cb(c, chn); }); chn->events().finish_evt.connect( [](Caliper* c, Channel* chn){ s_instance->finish_cb(c, chn); delete s_instance; s_instance = nullptr; }); Log(1).stream() << chn->name() << ": Registered cuptitrace service" << std::endl; } CuptiTraceService(Caliper* c, Channel* chn) { Attribute unit_attr = c->create_attribute("time.unit", CALI_TYPE_STRING, CALI_ATTR_SKIP_EVENTS); Attribute aggr_class_attr = c->get_attribute("class.aggregatable"); Variant nsec_val = Variant(CALI_TYPE_STRING, "nsec", 4); Variant true_val = Variant(true); Attribute meta_attr[2] = { aggr_class_attr, unit_attr }; Variant meta_vals[2] = { true_val, nsec_val }; activity_start_attr = c->create_attribute("cupti.activity.start", CALI_TYPE_UINT, CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS); activity_end_attr = c->create_attribute("cupti.activity.end", CALI_TYPE_UINT, CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS); activity_duration_attr = c->create_attribute("cupti.activity.duration", CALI_TYPE_UINT, CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS, 2, meta_attr, meta_vals); activity_kind_attr = c->create_attribute("cupti.activity.kind", CALI_TYPE_STRING, CALI_ATTR_DEFAULT | CALI_ATTR_SKIP_EVENTS); kernel_name_attr = c->create_attribute("cupti.kernel.name", CALI_TYPE_STRING, CALI_ATTR_DEFAULT | CALI_ATTR_SKIP_EVENTS); memcpy_kind_attr = c->create_attribute("cupti.memcpy.kind", CALI_TYPE_STRING, CALI_ATTR_DEFAULT | CALI_ATTR_SKIP_EVENTS); memcpy_bytes_attr = c->create_attribute("cupti.memcpy.bytes", CALI_TYPE_UINT, CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS, 1, &aggr_class_attr, &true_val); starttime_attr = c->create_attribute("cupti.starttime", CALI_TYPE_UINT, CALI_ATTR_SCOPE_PROCESS | CALI_ATTR_SKIP_EVENTS); device_uuid_attr = c->create_attribute("cupti.device.uuid", CALI_TYPE_STRING, CALI_ATTR_DEFAULT | CALI_ATTR_SKIP_EVENTS); ConfigSet config = chn->config().init("cuptitrace", s_configdata); record_host_timestamp = config.get("snapshot_timestamps").to_bool(); record_host_duration = config.get("snapshot_duration").to_bool(); if (record_host_duration || record_host_timestamp) { int hide_offset = record_host_timestamp ? 0 : CALI_ATTR_HIDDEN; timestamp_attr = c->create_attribute("cupti.timestamp", CALI_TYPE_UINT, CALI_ATTR_SCOPE_THREAD | CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS | hide_offset); duration_attr = c->create_attribute("cupti.host.duration", CALI_TYPE_UINT, CALI_ATTR_SCOPE_THREAD | CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS, 2, meta_attr, meta_vals); } } public: static void cuptitrace_initialize(Caliper* c, Channel* chn) { if (s_instance) { Log(0).stream() << chn->name() << ": cuptitrace service is already initialized!" << std::endl; return; } s_instance = new CuptiTraceService(c, chn); chn->events().post_init_evt.connect( [](Caliper* c, Channel* chn){ s_instance->post_init_cb(c, chn); }); } }; const struct ConfigSet::Entry CuptiTraceService::s_configdata[] = { { "activities", CALI_TYPE_STRING, "correlation,device,runtime,kernel,memcpy", "The CUpti activity kinds to record", "The CUpti activity kinds to record. Possible values: " " device: Device info" " correlation: Correlation records. Required for Caliper context correlation." " driver: Driver API." " runtime: Runtime API." " Runtime records are also required for Caliper context correlation." " kernel: CUDA Kernels being executed." " memcpy: CUDA memory copies." }, { "correlate_context", CALI_TYPE_BOOL, "true", "Correlate CUpti records with Caliper context", "Correlate CUpti records with Caliper context" }, { "snapshot_timestamps", CALI_TYPE_BOOL, "false", "Record CUpti timestamps for all Caliper snapshots", "Record CUpti timestamps for all Caliper snapshots" }, { "snapshot_duration", CALI_TYPE_BOOL, "false", "Record duration of host-side activities using CUpti timestamps", "Record duration of host-side activities using CUpti timestamps" }, ConfigSet::Terminator }; CuptiTraceService* CuptiTraceService::s_instance = nullptr; } // namespace [anonymous] namespace cali { CaliperService cuptitrace_service = { "cuptitrace", ::CuptiTraceService::cuptitrace_initialize }; }
34.296578
149
0.547228
[ "vector" ]
b950976315fdf07a6d5b1fe38be0d3127bb256b3
15,034
cpp
C++
ork.lev2/src/gfx/util/grid.cpp
tweakoz/orkid
e3f78dfb3375853fd512a9d0828b009075a18345
[ "BSL-1.0" ]
25
2015-02-21T04:21:21.000Z
2022-01-20T05:19:27.000Z
ork.lev2/src/gfx/util/grid.cpp
tweakoz/orkid
e3f78dfb3375853fd512a9d0828b009075a18345
[ "BSL-1.0" ]
113
2019-08-23T04:52:14.000Z
2021-09-13T04:04:11.000Z
ork.lev2/src/gfx/util/grid.cpp
tweakoz/orkid
e3f78dfb3375853fd512a9d0828b009075a18345
[ "BSL-1.0" ]
4
2017-02-20T18:17:55.000Z
2020-06-28T03:47:55.000Z
//////////////////////////////////////////////////////////////// // Orkid Media Engine // Copyright 1996-2020, Michael T. Mayers. // Distributed under the Boost Software License - Version 1.0 - August 17, 2003 // see http://www.boost.org/LICENSE_1_0.txt //////////////////////////////////////////////////////////////// #include <math.h> #include <ork/lev2/gfx/gfxenv.h> #include <ork/lev2/gfx/gfxmaterial_test.h> #include <ork/lev2/gfx/gfxprimitives.h> #include <ork/lev2/gfx/renderer/rendercontext.h> #include <ork/lev2/gfx/util/grid.h> #include <ork/math/audiomath.h> #include <ork/math/misc_math.h> #include <ork/pch.h> using namespace ork::audiomath; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// namespace ork { namespace lev2 { Grid3d::Grid3d() : _visGridBase(0.3f) , _visGridDiv(10.0f) , _visGridHiliteDiv(100.0f) { } /////////////////////////////////////////////////////////////////////////////// void Grid3d::Calc(const CameraMatrices& camdat) { const fvec4& vn0 = camdat.GetFrustum().mNearCorners[0]; const fvec4& vn1 = camdat.GetFrustum().mNearCorners[1]; const fvec4& vn2 = camdat.GetFrustum().mNearCorners[2]; const fvec4& vn3 = camdat.GetFrustum().mNearCorners[3]; const fvec4& vf0 = camdat.GetFrustum().mFarCorners[0]; const fvec4& vf1 = camdat.GetFrustum().mFarCorners[1]; const fvec4& vf2 = camdat.GetFrustum().mFarCorners[2]; const fvec4& vf3 = camdat.GetFrustum().mFarCorners[3]; fvec3 vr0 = (vf0 - vn0).Normal(); fvec3 vr1 = (vf1 - vn1).Normal(); fvec3 vr2 = (vf2 - vn2).Normal(); fvec3 vr3 = (vf3 - vn3).Normal(); ///////////////////////////////////////////////////////////////// // get center ray fvec3 vnc = (vn0 + vn1 + vn2 + vn3) * float(0.25f); fvec3 vfc = (vf0 + vf1 + vf2 + vf3) * float(0.25f); fvec3 vrc = (vfc - vnc).Normal(); fray3 centerray; centerray.mOrigin = vnc; centerray.mDirection = vrc; ///////////////////////////////////////////////////////////////// float itx0 = 0.0f, itx1 = 0.0f, ity0 = 0.0f, ity1 = 0.0f; ///////////////////////////////////////////////////////////////// // calc intersection of frustum and XYPlane float DistToPlane(0.0f); if (_gridMode == EGRID_XY) { fplane3 XYPlane(fvec3(float(0.0f), float(0.0f), float(1.0f)), fvec3::zero()); fvec3 vc; bool bc = XYPlane.Intersect(centerray, DistToPlane); float isect_dist; bc = XYPlane.Intersect(centerray, isect_dist, vc); float Restrict = DistToPlane * float(1.0f); // extend Grid to cover full viewport itx0 = vc.x - Restrict; itx1 = vc.x + Restrict; ity0 = vc.y - Restrict; ity1 = vc.y + Restrict; } else if (_gridMode == EGRID_XZ) { fplane3 XZPlane(fvec3(float(0.0f), float(1.0f), float(0.0f)), fvec3::zero()); fvec3 vc; bool bc = XZPlane.Intersect(centerray, DistToPlane); float isect_dist; bc = XZPlane.Intersect(centerray, isect_dist, vc); float Restrict = DistToPlane * float(1.0f); // extend Grid to cover full viewport itx0 = vc.x - Restrict; itx1 = vc.x + Restrict; ity0 = vc.z - Restrict; ity1 = vc.z + Restrict; } ///////////////////////////////////////////////////////////////// // get params for grid float fLEFT = float(itx0); float fRIGHT = float(itx1); float fTOP = float(ity0); float fBOTTOM = float(ity1); float fWIDTH = fRIGHT - fLEFT; float fHEIGHT = fBOTTOM - fTOP; float fASPECT = fHEIGHT / fWIDTH; float fLOG = float(log_base(_visGridDiv, DistToPlane * _visGridBase)); float fiLOG = float(pow_base(_visGridDiv, float(floor(fLOG)))); _visGridSize = fiLOG / _visGridDiv; if (_visGridSize < 10.0f) _visGridSize = 10.0f; // if( _visGridSize<float(0.5f) ) _visGridSize = float(0.5f); // if( _visGridSize>float(8.0f) ) _visGridSize = float(8.0f); _gridDL = _visGridSize * float(floor(fLEFT / _visGridSize)); _gridDR = _visGridSize * float(ceil(fRIGHT / _visGridSize)); _gridDT = _visGridSize * float(floor(fTOP / _visGridSize)); _gridDB = _visGridSize * float(ceil(fBOTTOM / _visGridSize)); } /////////////////////////////////////////////////////////////////////////////// void Grid3d::Render(RenderContextFrameData& FrameData) const { Context* pTARG = FrameData.GetTarget(); // pTARG->MTXI()->PushPMatrix( FrameData.cameraMatrices()->GetPMatrix() ); // pTARG->MTXI()->PushVMatrix( FrameData.cameraMatrices()->GetVMatrix() ); pTARG->MTXI()->PushMMatrix(fmtx4::Identity()); { static GfxMaterial3DSolid gridmat(pTARG); gridmat.SetColorMode(GfxMaterial3DSolid::EMODE_MOD_COLOR); gridmat._rasterstate.SetBlending(Blending::ADDITIVE); //////////////////////////////// // Grid float GridGrey(0.10f); float GridHili(0.20f); fvec4 BaseGridColor(GridGrey, GridGrey, GridGrey); fvec4 HiliGridColor(GridHili, GridHili, GridHili); pTARG->PushModColor(BaseGridColor); if (_gridMode == EGRID_XY) { for (float fX = _gridDL; fX <= _gridDR; fX += _visGridSize) { bool bORIGIN = (fX == 0.0f); bool bhi = fmodf(fabs(fX), _visGridHiliteDiv) < Float::Epsilon(); pTARG->PushModColor(bORIGIN ? fcolor4::Green() : (bhi ? HiliGridColor : BaseGridColor)); // pTARG->IMI()->DrawLine( fvec4( fX, _gridDT, 0.0f, 1.0f ), fvec4( fX, _gridDB, 0.0f, 1.0f ) ); // pTARG->IMI()->QueFlush( false ); pTARG->PopModColor(); } for (float fY = _gridDT; fY <= _gridDB; fY += _visGridSize) { bool bORIGIN = (fY == 0.0f); bool bhi = fmodf(fabs(fY), _visGridHiliteDiv) < Float::Epsilon(); pTARG->PushModColor(bORIGIN ? fcolor4::Red() : (bhi ? HiliGridColor : BaseGridColor)); // pTARG->IMI()->DrawLine( fvec4( _gridDL, fY, 0.0f, 1.0f ), fvec4( _gridDR, fY, 0.0f, 1.0f ) ); // pTARG->IMI()->QueFlush( false ); pTARG->PopModColor(); } } else if (_gridMode == EGRID_XZ) { for (float fX = _gridDL; fX <= _gridDR; fX += _visGridSize) { bool bORIGIN = (fX == 0.0f); bool bhi = fmodf(fabs(fX), _visGridHiliteDiv) < Float::Epsilon(); pTARG->PushModColor(bORIGIN ? fcolor4::Blue() : (bhi ? HiliGridColor : BaseGridColor)); // pTARG->IMI()->DrawLine( fvec4( fX, 0.0f, _gridDT, 1.0f ), fvec4( fX, 0.0f, _gridDB, 1.0f ) ); // pTARG->IMI()->QueFlush( false ); pTARG->PopModColor(); } for (float fY = _gridDT; fY <= _gridDB; fY += _visGridSize) { bool bORIGIN = (fY == 0.0f); bool bhi = fmodf(fabs(fY), _visGridHiliteDiv) < Float::Epsilon(); pTARG->PushModColor(bORIGIN ? fcolor4::Red() : (bhi ? HiliGridColor : BaseGridColor)); // pTARG->IMI()->DrawLine( fvec4( _gridDL, 0.0f, fY, 1.0f ), fvec4( _gridDR, 0.0f, fY, 1.0f ) ); // pTARG->IMI()->QueFlush( false ); pTARG->PopModColor(); } } // FontMan::FlushQue(pTARG); pTARG->PopModColor(); } // pTARG->MTXI()->PopPMatrix(); // pTARG->MTXI()->PopVMatrix(); pTARG->MTXI()->PopMMatrix(); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// Grid2d::Grid2d() : _visGridDiv(5.0f) , _visGridHiliteDiv(25.0f) , _visGridSize(10) , _center(0.0f, 0.0f) , _extent(100.0f) , _zoomX(1.0f) , _zoomY(1.0f) , _snapCenter(false){ float base_grey(0.10f); float hilite_grey(0.40f); _baseColor = fvec3(base_grey, base_grey, base_grey); _hiliteColor = fvec3(hilite_grey, hilite_grey, hilite_grey); } /////////////////////////////////////////////////////////////////////////////// /* static const int kdiv_base = 240 * 4; static const int kfreqmult = 5; static const float klogbias = 0.3f; // adjust to change threshold of lod switch struct grid_calculator { int ispace; int il; int ir; int it; int ib; int ic; float flog; float filog; float flogb; grid_calculator( const Rectangle& devviewrect, float scale_factor ) { static const float div_base = kdiv_base; // base distance between gridlines at unity scale auto log_base = []( float base, float inp ) ->float { float rval = logf( inp ) / logf( base ); return rval; }; auto pow_base = []( float base, float inp ) ->float { float rval = powf( base, inp ); return rval; }; const float kfbase = kfreqmult; flogb = log_base( kfbase, div_base ); flog = log_base( kfbase, scale_factor ); flog = klogbias+std::round(flog*10.0f)/10.0f; flog = (flog<1.0f) ? 1.0f : flog; filog = pow_base( kfbase, flogb+std::floor(flog) ); filog = std::round(filog/kfbase)*kfbase; ispace = int(filog); il = (int(devviewrect.x-filog)/ispace)*ispace; ir = (int(devviewrect.x2+filog)/ispace)*ispace; it = (int(devviewrect.y-filog)/ispace)*ispace; ib = (int(devviewrect.y2+filog)/ispace)*ispace; ic = (ir-il)/ispace; printf( "scale_factor<%f> flog<%f> filog<%f> il<%d> ir<%d> ispace<%d> ic<%d>\n", scale_factor, flog, filog, il, ir, ispace, ic ); } }; */ //////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void Grid2d::ReCalc(int iw, int ih) { // float scale_factor = (dev_view_rect.y2 - dev_view_rect.y) / gmastercfg.ideviceH; // grid_calculator the_grid_calc(dev_view_rect,scale_factor); float ftW = float(iw); float ftH = float(ih); _aspect = ftH / ftW; _zoomedExtentX = _extent / _zoomX; _zoomedExtentY = _extent / _zoomY *_aspect; //float itx0 = _center.x - fnext * 0.5f; //float itx1 = _center.x + fnext * 0.5f; //float ity0 = _center.y - fnext * 0.5f * fASPECT; //float ity1 = _center.y + fnext * 0.5f * fASPECT; float fLOG = log_base(_visGridDiv, _zoomedExtentX); float fiLOG = pow_base(_visGridDiv, floor(fLOG)); //printf( "grid fLOG<%g> fiLOG<%g>\n", fLOG, fiLOG ); ///////////////////////////////////////////////////////////////// // get params for grid ///////////////////////////////////////////////////////////////// /*float fLEFT = itx0; float fRIGHT = itx1; float fTOP = ity0; float fBOTTOM = ity1; float fWIDTH = fRIGHT - fLEFT; float fHEIGHT = fBOTTOM - fTOP; //_visGridSize = clamp(fiLOG / _visGridDiv,10.0f,100.0f); //printf( "grid fLEFT<%g> fRIGHT<%g> fTOP<%g> fBOTTOM<%g> fLOG<%g> fiLOG<%g>\n", fLEFT, fRIGHT, fTOP, fBOTTOM, fLOG, fiLOG ); */ _topLeft.x = _center.x - _zoomedExtentX*0.5f; _topLeft.y= _center.y - _zoomedExtentY*0.5f; _botRight.x = _center.x + _zoomedExtentX*0.5f; _botRight.y = _center.y + _zoomedExtentY*0.5f; //printf( "grid _topLeft<%g %g> _botRight<%g %g>\n", _topLeft.x, _topLeft.y, _botRight.x, _botRight.y ); } /////////////////////////////////////////////////////////////////////////////// fvec2 Grid2d::Snap(fvec2 inp) const { float ffx = inp.x; float ffy = inp.y; float ffxm = fmodf(ffx, _visGridSize); float ffym = fmodf(ffy, _visGridSize); bool blx = (ffxm < (_visGridSize * 0.5f)); bool bly = (ffym < (_visGridSize * 0.5f)); float fnx = blx ? (ffx - ffxm) : (ffx - ffxm) + _visGridSize; float fny = bly ? (ffy - ffym) : (ffy - ffym) + _visGridSize; return fvec2(fnx, fny); } /////////////////////////////////////////////////////////////////////////////// void Grid2d::updateMatrices(Context* pTARG, int iw, int ih) { auto mtxi = pTARG->MTXI(); ReCalc(iw, ih); _mtxOrtho = mtxi->Ortho(_topLeft.x, _botRight.x, _botRight.y, _topLeft.y, 0.0f, 1.0f); } void Grid2d::pushMatrix(Context* pTARG){ auto mtxi = pTARG->MTXI(); mtxi->PushPMatrix(_mtxOrtho); mtxi->PushVMatrix(fmtx4::Identity()); mtxi->PushMMatrix(fmtx4::Identity()); } void Grid2d::popMatrix(Context* pTARG){ auto mtxi = pTARG->MTXI(); mtxi->PopPMatrix(); mtxi->PopVMatrix(); mtxi->PopMMatrix(); } /////////////////////////////////////////////////////////////////////////////// void Grid2d::Render(Context* pTARG, int iw, int ih) { auto mtxi = pTARG->MTXI(); lev2::DynamicVertexBuffer<lev2::SVtxV12C4T16>& VB = lev2::GfxEnv::GetSharedDynamicVB(); this->pushMatrix(pTARG); { static GfxMaterial3DSolid gridmat(pTARG); gridmat.SetColorMode(GfxMaterial3DSolid::EMODE_VERTEX_COLOR); gridmat._rasterstate.SetBlending(Blending::ADDITIVE); //////////////////////////////// // Grid int inumx = ceil(_zoomedExtentX*2.0/_visGridSize); int inumy = ceil(_zoomedExtentY*2.0/_visGridSize); float ftW = float(iw); float ftH = float(ih); float fASPECT = ftH / ftW; int count = (inumx + inumy) * 16; //printf( "inumx<%d> inumy<%d> count<%d>\n", inumx, inumy, count ); if (count) { float x1 = floor(_topLeft.x/_visGridSize)*_visGridSize; float x2 = ceil(_botRight.x/_visGridSize)*_visGridSize; float y1 = floor(_topLeft.y/_visGridSize)*_visGridSize; float y2 = ceil(_botRight.y/_visGridSize)*_visGridSize; bool draw_grid = (_drawmode!=EGrid2DDrawMode::NONE); if( draw_grid ){ bool origin_axis_only = _drawmode==EGrid2DDrawMode::ORIGIN_AXIS_ONLY; lev2::VtxWriter<lev2::SVtxV12C4T16> vw; vw.Lock(pTARG, &VB,count); fvec2 uv0(0.0f, 0.0f); for (float fx = x1; fx <= x2; fx += _visGridSize) { bool bORIGIN = (fabs(fx)<0.01); if( origin_axis_only and (not bORIGIN) ) continue; bool bhi = fmodf(fabs(fx), _visGridHiliteDiv) < Float::Epsilon(); auto color = bORIGIN ? fcolor3::Green()*0.5 : (bhi ? _hiliteColor : _baseColor ); u32 ucolor = color.GetVtxColorAsU32(); ork::lev2::SVtxV12C4T16 v0(fvec3(fx, y1, 0.0f), uv0, ucolor); ork::lev2::SVtxV12C4T16 v1(fvec3(fx, y2, 0.0f), uv0, ucolor); vw.AddVertex(v0); vw.AddVertex(v1); } for (float fy = y1; fy <= y2; fy += _visGridSize) { bool bORIGIN = (fabs(fy)<0.01); if( origin_axis_only and (not bORIGIN) ) continue; bool bhi = fmodf(fabs(fy), _visGridHiliteDiv) < Float::Epsilon(); auto color = bORIGIN ? fcolor3::Red()*0.5 : (bhi ? _hiliteColor : _baseColor ); u32 ucolor = color.GetVtxColorAsU32(); ork::lev2::SVtxV12C4T16 v0(fvec3(x1, fy, 0.0f), uv0, ucolor); ork::lev2::SVtxV12C4T16 v1(fvec3(x2, fy, 0.0f), uv0, ucolor); vw.AddVertex(v0); vw.AddVertex(v1); } vw.UnLock(pTARG); pTARG->GBI()->DrawPrimitive(&gridmat, vw, ork::lev2::PrimitiveType::LINES); } } } this->popMatrix(pTARG); } }} // namespace ork::lev2
34.324201
131
0.552814
[ "render" ]
b9514d9ace3383a15ffdef8e839b9e9f1f9deddb
6,042
hpp
C++
include/seller.hpp
larteyoh/neroshop
f8d9e6bc74b4b7e49abbe2dba657c4fb87c3af4b
[ "AML" ]
null
null
null
include/seller.hpp
larteyoh/neroshop
f8d9e6bc74b4b7e49abbe2dba657c4fb87c3af4b
[ "AML" ]
null
null
null
include/seller.hpp
larteyoh/neroshop
f8d9e6bc74b4b7e49abbe2dba657c4fb87c3af4b
[ "AML" ]
null
null
null
// filename: .hpp //#pragma once // use #ifndef _HPP, #define _HPP, and #endif instead #ifndef SELLER_HPP_NEROSHOP #define SELLER_HPP_NEROSHOP #include <cmath> // floor #include <random> #include "wallet.hpp" // seller will use wallet to generate a unique subaddress for each tx #include "user.hpp" #include "item.hpp"//#include "inventory.hpp" // item.hpp included here//#include "registry.hpp"//deprecated #include "converter.hpp" namespace neroshop { class Seller : public User { public: Seller(); Seller(const std::string& name); ~Seller(); void list_item(unsigned int item_id, unsigned int stock_qty, double sales_price = 0.00, std::string currency = "usd", double discount = 0.00, unsigned int discounted_items = 1, unsigned int discount_times = 1, std::string discount_expiry = ""/*"0000-00-00 00:00:00"*/, std::string condition = "new"); // adds an item to the inventory void list_item(const neroshop::Item& item, unsigned int stock_qty, double sales_price = 0.00, std::string currency = "usd", double discount = 0.00, unsigned int discounted_items = 1, unsigned int discount_times = 1, std::string discount_expiry = ""/*"0000-00-00 00:00:00"*/, std::string condition = "new"); void delist_item(unsigned int item_id); // deletes an item from the inventory void delist_item(const neroshop::Item& item); // setters - item and inventory-related stuff void set_stock_quantity(unsigned int item_id, unsigned int stock_qty); void set_stock_quantity(const neroshop::Item& item, unsigned int stock_qty); // setters - wallet-related stuff void set_wallet(const neroshop::Wallet& wallet);// temporary - delete ASAP // getters - seller rating system unsigned int get_good_ratings() const; // returns the total number of good ratings given to this seller by their customers unsigned int get_bad_ratings() const; // returns the total number of bad ratings given to this seller by their customers unsigned int get_ratings_count() const; // returns the total number of ratings given to this seller by their customers (includes both good and bad ratings) unsigned int get_total_ratings() const; // same as get_ratings_count unsigned int get_reputation() const; // returns a percentage of good ratings static std::vector<unsigned int> get_top_rated_sellers(unsigned int limit = 50); // returns a container of n seller_ids with the most positive (good) ratings // the default value of n is 50 // getters - wallet-related stuff neroshop::Wallet * get_wallet() const; // getters - order-related stuff unsigned int get_customer_order(unsigned int index) const; unsigned int get_customer_order_count() const; std::vector<int> get_pending_customer_orders(); // getters - sales and statistics-related stuff unsigned int get_sales_count() const; // returns the total number of items sold by this seller unsigned int get_units_sold(unsigned int item_id) const; // returns the total number of a specific item sold by this seller unsigned int get_units_sold(const neroshop::Item& item) const; double get_sales_profit() const; // returns the overall profit made from the sale of all items sold by this seller double get_profits_made(unsigned int item_id) const; // returns the overall profit made from the sale of a specific item sold by this seller double get_profits_made(const neroshop::Item& item) const; unsigned int get_item_id_with_most_sales() const; // returns the item_id with the most purchases (based on biggest sum of item_qty in "order_item") unsigned int get_item_id_with_most_orders() const; // returns the item_id with the mode (most occuring) or the most ordered item in "order_item" //Item * get_item_with_most_sales() const; //Item * get_item_with_most_orders() const; // boolean //bool is_verified() const; // returns true if seller is verified brand owner (or original manufacturer) bool has_listed(unsigned int item_id) const; // returns true if this seller has listed an item bool has_listed(const neroshop::Item& item) const; // returns true if this seller has listed an item bool has_stock(unsigned int item_id) const; // returns true if this seller has an item in stock bool has_stock(const neroshop::Item& item) const; bool has_wallet() const; // returns true if seller's wallet is opened bool has_wallet_synced() const; // returns true if seller's wallet is synced to a node // callbacks static neroshop::User * on_login(const std::string& username); void on_order_received(std::string& subaddress); // listening to orders void update_customer_orders(); // called multiple times // listens to and update customer orders protected: void load_customer_orders(); // called one-time when seller logs in private: std::unique_ptr<neroshop::Wallet> wallet; std::vector<int> customer_order_list; }; } #endif // images, price, search_terms // coupons should have a uuid hmm ... // create promotions such as: percent_off, free_shipping, giveaway, buy_one_get_one_free, coupon codes(time_limit, expire_date) => https://tinuiti.com/blog/amazon/amazon-promotions-for-sellers/ // coupon_min_percent = 2%, coupon_max_percent = 90% (amazon is 5%-80%) /* combining different promotions/coupons: Lightning Deal Discount: 20% Coupon Discount: 5% Total Discount: ($100 * 0.2) + ($100 * 0.05) = $25 */ /* Seller * seller = new Seller(); std::cout << "good_ratings: " << seller->get_good_ratings() << std::endl; std::cout << "bad_ratings: " << seller->get_bad_ratings() << std::endl; std::cout << "total_ratings: " << seller->get_total_ratings() << std::endl; std::cout << std::endl; std::cout << "reputation: " << seller->get_reputation() << "%" << std::endl; //std::cout << "good_percentage: " << seller->get_good_percentage() << "%" << std::endl; //std::cout << "bad_percentage: " << seller->get_bad_percentage() << "%" << std::endl; // total number of sellers std::cout << "\nnumber of sellers: " << Registry::get_seller_registry()->get_size() << std::endl; */ // list a product - name, code(upc, ean, isbn, etc.), description/bullet points,
60.42
334
0.740483
[ "vector" ]
b951a72f71b23b5428c34b75dbf70eb814006ed6
5,010
cc
C++
fast_k_means_2020/fast_k_means_main.cc
egonrian/google-research
8177adbe9ca0d7e5a9463b54581fe6dd27be0974
[ "Apache-2.0" ]
3
2021-01-18T04:46:49.000Z
2021-03-05T09:21:40.000Z
fast_k_means_2020/fast_k_means_main.cc
Alfaxad/google-research
2c0043ecd507e75e2df9973a3015daf9253e1467
[ "Apache-2.0" ]
7
2021-11-10T19:44:38.000Z
2022-02-10T06:48:39.000Z
fast_k_means_2020/fast_k_means_main.cc
Alfaxad/google-research
2c0043ecd507e75e2df9973a3015daf9253e1467
[ "Apache-2.0" ]
4
2021-02-08T10:25:45.000Z
2021-04-17T14:46:26.000Z
// Copyright 2020 The Google Research Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <math.h> #include <cstdint> #include <cstdio> #include <iostream> #include <vector> #include "compute_cost.h" #include "fast_k_means_algo.h" #include "kmeanspp_seeding.h" #include "rejection_sampling_lsh.h" using std::cout; using std::endl; using std::vector; namespace fast_k_means { vector<vector<double> > ReadInput() { int n, d; vector<vector<double> > input_point; FILE* fp; // Add the input file here. We expect the number of points and number of // dimension in the first line (space separated). Followed by one line for // each input point, describing the dimensions in double format // (space separated). Input example with three points each have 2 dimensions: // 3 2 // 1.00 2.50 // 3.30 4.12 // 0.0 -10.0 fp = fopen( "/usr/local/google/home/ashkannorouzi/Documents/fast-kmedian/dataset/" "cloud.data", "r"); fscanf(fp, "%d%d", &n, &d); cout << n << " " << d << endl; for (int i = 0; i < n; i++) { input_point.push_back(vector<double>(d)); for (int j = 0; j < d; j++) fscanf(fp, "%lf", &input_point[i][j]); } return input_point; } } // namespace fast_k_means // The variables of the algorithm. // Number of centers int k = 0; // Number of trees that we embed. int number_of_trees = 4; // The scalling factor of the input before casted to integer. double scaling_factor = 1.0; // Number of greedy samples in case one is runnig the greedy version of the // algorithms. int number_greedy_samples = 0; // Multiples the probability of accepting a center in rejection sampling by this // factor. We recommend to use sqrt(# of dimensions) or # of dimensions. double boosting_prob_factor = 1.0; // Fast k-means algorithm. The rest of the function are the same experiments for // different algorithms. void FastKmeansExperiment(const vector<vector<double>>& input_point) { fast_k_means::FastKMeansAlgo fast_algo; // Running the algotihm, the result is stored in fast_algo.centers_ vector. clock_t start_time = clock(); fast_algo.RunAlgorithm(input_point, k, number_of_trees, scaling_factor, number_greedy_samples + 1); cout << "Running time for the Fast Algorithm in seconds: " << static_cast<double>(clock() - start_time) / CLOCKS_PER_SEC << endl; // One can compute the cost of the solution as follows cout << "The cost of the solution is: " << fast_k_means::ComputeCost::GetCost(input_point, fast_algo.centers) << endl; } void RejectionSamplingLSHExperiment(const vector<vector<double>>& input_point) { clock_t start_time = clock(); fast_k_means::RejectionSamplingLSH rejsamplelsh_algo; rejsamplelsh_algo.RunAlgorithm(input_point, k, number_of_trees, scaling_factor, number_greedy_samples + 1, boosting_prob_factor); cout << "Running time for the Fast Algorithm in seconds: " << static_cast<double>(clock() - start_time) / CLOCKS_PER_SEC << endl; // One can compute the cost of the solution as follows cout << "The cost of the solution is: " << fast_k_means::ComputeCost::GetCost(input_point, rejsamplelsh_algo.centers) << endl; } void KMeansPPSeedingExperiment(const vector<vector<double>>& input_point) { clock_t start_time = clock(); fast_k_means::KMeansPPSeeding kmeanspp_algo; kmeanspp_algo.RunAlgorithm(input_point, k, number_greedy_samples + 1); cout << "Running time for the Fast Algorithm in seconds: " << static_cast<double>(clock() - start_time) / CLOCKS_PER_SEC << endl; // One can compute the cost of the solution as follows cout << "The cost of the solution is: " << fast_k_means::ComputeCost::GetCost(input_point, kmeanspp_algo.centers_) << endl; } int main() { vector<vector<double> > input_point = fast_k_means::ReadInput(); // Fixing the variables explained above. k = 10; boosting_prob_factor = sqrt(input_point[0].size()); // Call the functions here. // This part is supposed to be very short. cout << "Starting FastKmeans Experiment" << endl; FastKmeansExperiment(input_point); cout << "Starting Rejection Sampling LSH Experiment" << endl; RejectionSamplingLSHExperiment(input_point); cout << "Starting KMeans++ Seeding Experiment" << endl; KMeansPPSeedingExperiment(input_point); }
36.304348
80
0.691816
[ "vector" ]
b952c7c3503c17882c4b2eed86c10fa5f0a3f4e2
7,682
cpp
C++
src/webots/nodes/WbIndexedLineSet.cpp
yjf18340/webots
60d441c362031ab8fde120cc0cd97bdb1a31a3d5
[ "Apache-2.0" ]
1
2019-11-13T08:12:02.000Z
2019-11-13T08:12:02.000Z
src/webots/nodes/WbIndexedLineSet.cpp
chinakwy/webots
7c35a359848bafe81fe0229ac2ed587528f4c73e
[ "Apache-2.0" ]
null
null
null
src/webots/nodes/WbIndexedLineSet.cpp
chinakwy/webots
7c35a359848bafe81fe0229ac2ed587528f4c73e
[ "Apache-2.0" ]
1
2020-09-25T02:01:45.000Z
2020-09-25T02:01:45.000Z
// Copyright 1996-2019 Cyberbotics Ltd. // // 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 "WbIndexedLineSet.hpp" #include "WbBoundingSphere.hpp" #include "WbCoordinate.hpp" #include "WbField.hpp" #include "WbMFInt.hpp" #include "WbMFVector3.hpp" #include "WbNodeUtilities.hpp" #include "WbSFNode.hpp" #include "WbWrenMeshBuffers.hpp" #include "WbWrenRenderingContext.hpp" #include "WbWrenShaders.hpp" #include <wren/config.h> #include <wren/material.h> #include <wren/node.h> #include <wren/renderable.h> #include <wren/static_mesh.h> #include <wren/transform.h> void WbIndexedLineSet::init() { mCoord = findSFNode("coord"); mCoordIndex = findMFInt("coordIndex"); } WbIndexedLineSet::WbIndexedLineSet(WbTokenizer *tokenizer) : WbGeometry("IndexedLineSet", tokenizer) { init(); } WbIndexedLineSet::WbIndexedLineSet(const WbIndexedLineSet &other) : WbGeometry(other) { init(); } WbIndexedLineSet::WbIndexedLineSet(const WbNode &other) : WbGeometry(other) { init(); } WbIndexedLineSet::~WbIndexedLineSet() { wr_static_mesh_delete(mWrenMesh); } void WbIndexedLineSet::postFinalize() { WbGeometry::postFinalize(); connect(mCoord, &WbSFNode::changed, this, &WbIndexedLineSet::updateCoord); connect(mCoordIndex, &WbMFInt::changed, this, &WbIndexedLineSet::updateCoordIndex); if (coord()) connect(coord(), &WbCoordinate::fieldChanged, this, &WbIndexedLineSet::updateCoord, Qt::UniqueConnection); } WbCoordinate *WbIndexedLineSet::coord() const { return static_cast<WbCoordinate *>(mCoord->value()); } void WbIndexedLineSet::createWrenObjects() { WbGeometry::createWrenObjects(); updateCoord(); if (isInBoundingObject()) connect(WbWrenRenderingContext::instance(), &WbWrenRenderingContext::lineScaleChanged, this, &WbIndexedLineSet::updateLineScale); sanitizeFields(); buildWrenMesh(); emit wrenObjectsCreated(); } void WbIndexedLineSet::updateLineScale() { if (!isAValidBoundingObject()) return; float offset = wr_config_get_line_scale() / LINE_SCALE_FACTOR; float scale[] = {static_cast<float>(1.0 + offset), static_cast<float>(1.0 + offset), static_cast<float>(1.0 + offset)}; wr_transform_set_scale(wrenNode(), scale); } void WbIndexedLineSet::setWrenMaterial(WrMaterial *material, bool castShadows) { WbGeometry::setWrenMaterial(material, castShadows); if (material) wr_material_set_default_program(material, WbWrenShaders::lineSetShader()); } bool WbIndexedLineSet::sanitizeFields() { if (!coord() || coord()->point().isEmpty()) { warn(tr("A 'Coordinate' node should be present in the 'coord' field with at least two items.")); return false; } if (mCoordIndex->isEmpty() || estimateIndexCount() < 2) { warn(tr("The 'coordIndex' field should have at least two items.")); return false; } return true; } void WbIndexedLineSet::buildWrenMesh() { WbGeometry::deleteWrenRenderable(); wr_static_mesh_delete(mWrenMesh); mWrenMesh = NULL; WbGeometry::computeWrenRenderable(); wr_renderable_set_drawing_mode(mWrenRenderable, WR_RENDERABLE_DRAWING_MODE_LINES); // In the worst case we end up with 2 * mCoordIndex->size() - 1 coordinates float *coordsData = new float[mCoordIndex->size() * 6]; int coordsCount = computeCoordsData(coordsData); mWrenMesh = wr_static_mesh_line_set_new(coordsCount, coordsData, NULL); delete[] coordsData; wr_renderable_set_mesh(mWrenRenderable, WR_MESH(mWrenMesh)); } void WbIndexedLineSet::reset() { WbGeometry::reset(); WbNode *const c = mCoord->value(); if (c) c->reset(); } int WbIndexedLineSet::computeCoordsData(float *data) { WbMFInt::Iterator it(*mCoordIndex); int i = it.next(); int count = 0; WbVector3 v; QStringList invalidIndices; const int size = coord()->point().size(); while (it.hasNext()) { int j = it.next(); if (i >= 0 && j >= 0 && i < size && j < size) { v = coord()->point().item(i); data[3 * count] = v.x(); data[3 * count + 1] = v.y(); data[3 * count + 2] = v.z(); ++count; v = coord()->point().item(j); data[3 * count] = v.x(); data[3 * count + 1] = v.y(); data[3 * count + 2] = v.z(); ++count; } else { // i or j are invalid: log them. if (j < -1 || j >= size) invalidIndices << QString::number(j); if (i < -1 || i >= size) invalidIndices << QString::number(i); } i = j; } if (invalidIndices.size() > 0) { invalidIndices.removeDuplicates(); warn(tr("The following indices are out of the range of coordinates specified in the 'IndexedLineSet.coord' field: %1") .arg(invalidIndices.join(", "))); } return count; } void WbIndexedLineSet::updateCoord() { if (!sanitizeFields()) return; if (coord()) connect(coord(), &WbCoordinate::fieldChanged, this, &WbIndexedLineSet::updateCoord, Qt::UniqueConnection); if (areWrenObjectsInitialized()) buildWrenMesh(); if (mBoundingSphere && !isInBoundingObject()) mBoundingSphere->setOwnerSizeChanged(); emit changed(); } void WbIndexedLineSet::updateCoordIndex() { if (!sanitizeFields()) return; if (areWrenObjectsInitialized()) buildWrenMesh(); if (mBoundingSphere && !isInBoundingObject()) mBoundingSphere->setOwnerSizeChanged(); emit changed(); } int WbIndexedLineSet::estimateIndexCount(bool isOutlineMesh) const { int ni = 0; int s1 = coord()->point().size(); WbMFInt::Iterator it(*mCoordIndex); int i = it.next(); while (it.hasNext()) { int j = it.next(); if (i != -1 && j != -1 && i < s1 && j < s1) ni += 2; i = j; } return ni; } void WbIndexedLineSet::recomputeBoundingSphere() const { assert(mBoundingSphere); mBoundingSphere->empty(); if (!coord()) return; const WbMFVector3 &points = coord()->point(); if (points.size() == 0) return; // Ritter's bounding sphere approximation // (see description in WbIndexedFaceSet::recomputeBoundingSphere) WbMFInt::Iterator it(*mCoordIndex); WbVector3 p2(points.item(it.next())); WbVector3 p1; double maxDistance; // squared distance for (int i = 0; i < 2; ++i) { maxDistance = 0.0; p1 = p2; while (it.hasNext()) { const int index = it.next(); if (index >= 0 && index < points.size()) { // skip '-1' or other invalid indices. const WbVector3 &point = points.item(index); const double d = p1.distance2(point); if (d > maxDistance) { maxDistance = d; p2 = point; } } } it.toFront(); } mBoundingSphere->set((p2 + p1) * 0.5, sqrt(maxDistance) * 0.5); while (it.hasNext()) { const int index = it.next(); if (index >= 0 && index < points.size()) // skip '-1' or other invalid indices. mBoundingSphere->enclose(points.item(index)); } } //////////////////////// // Friction Direction // //////////////////////// WbVector3 WbIndexedLineSet::computeFrictionDirection(const WbVector3 &normal) const { warn(tr("A IndexedLineSet is used in a Bounding object using an asymmetric friction. IndexedLineSet does not support " "asymmetric friction")); return WbVector3(0, 0, 0); }
27.53405
122
0.670919
[ "object", "transform" ]
b952f6a3d3c1e3a007745868960ba18e90984b72
5,901
cpp
C++
src/cascadia/TerminalSettingsModel/FileUtils.cpp
tjrileywisc/terminal
4b45bb8df1f90e6fc463172cb861bf968e162e77
[ "MIT" ]
2
2021-08-10T07:17:40.000Z
2021-08-10T07:17:47.000Z
src/cascadia/TerminalSettingsModel/FileUtils.cpp
tjrileywisc/terminal
4b45bb8df1f90e6fc463172cb861bf968e162e77
[ "MIT" ]
2
2021-02-02T22:25:08.000Z
2021-05-05T00:19:43.000Z
src/cascadia/TerminalSettingsModel/FileUtils.cpp
tjrileywisc/terminal
4b45bb8df1f90e6fc463172cb861bf968e162e77
[ "MIT" ]
2
2021-02-02T22:12:35.000Z
2021-05-04T23:24:57.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "pch.h" #include "FileUtils.h" #include <appmodel.h> #include <shlobj.h> #include <WtExeUtils.h> static constexpr std::string_view Utf8Bom{ u8"\uFEFF" }; static constexpr std::wstring_view UnpackagedSettingsFolderName{ L"Microsoft\\Windows Terminal\\" }; namespace Microsoft::Terminal::Settings::Model { // Returns a path like C:\Users\<username>\AppData\Local\Packages\<packagename>\LocalState // You can put your settings.json or state.json in this directory. std::filesystem::path GetBaseSettingsPath() { static std::filesystem::path baseSettingsPath = []() { wil::unique_cotaskmem_string localAppDataFolder; // KF_FLAG_FORCE_APP_DATA_REDIRECTION, when engaged, causes SHGet... to return // the new AppModel paths (Packages/xxx/RoamingState, etc.) for standard path requests. // Using this flag allows us to avoid Windows.Storage.ApplicationData completely. THROW_IF_FAILED(SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_FORCE_APP_DATA_REDIRECTION, nullptr, &localAppDataFolder)); std::filesystem::path parentDirectoryForSettingsFile{ localAppDataFolder.get() }; if (!IsPackaged()) { parentDirectoryForSettingsFile /= UnpackagedSettingsFolderName; } // Create the directory if it doesn't exist std::filesystem::create_directories(parentDirectoryForSettingsFile); return parentDirectoryForSettingsFile; }(); return baseSettingsPath; } // Tries to read a file somewhat atomically without locking it. // Strips the UTF8 BOM if it exists. std::string ReadUTF8File(const std::filesystem::path& path) { // From some casual observations we can determine that: // * ReadFile() always returns the requested amount of data (unless the file is smaller) // * It's unlikely that the file was changed between GetFileSize() and ReadFile() // -> Lets add a retry-loop just in case, to not fail if the file size changed while reading. for (int i = 0; i < 3; ++i) { wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr) }; THROW_LAST_ERROR_IF(!file); const auto fileSize = GetFileSize(file.get(), nullptr); THROW_LAST_ERROR_IF(fileSize == INVALID_FILE_SIZE); // By making our buffer just slightly larger we can detect if // the file size changed and we've failed to read the full file. std::string buffer(static_cast<size_t>(fileSize) + 1, '\0'); DWORD bytesRead = 0; THROW_IF_WIN32_BOOL_FALSE(ReadFile(file.get(), buffer.data(), gsl::narrow<DWORD>(buffer.size()), &bytesRead, nullptr)); // This implementation isn't atomic as we'd need to use an exclusive file lock. // But this would be annoying for users as it forces them to close the file in their editor. // The next best alternative is to at least try to detect file changes and retry the read. if (bytesRead != fileSize) { // This continue is unlikely to be hit (see the prior for loop comment). std::this_thread::sleep_for(std::chrono::milliseconds(100)); continue; } // As mentioned before our buffer was allocated oversized. buffer.resize(bytesRead); if (til::starts_with(buffer, Utf8Bom)) { // Yeah this memmove()s the entire content. // But I don't really want to deal with UTF8 BOMs any more than necessary, // as basically not a single editor writes a BOM for UTF8. buffer.erase(0, Utf8Bom.size()); } return buffer; } THROW_WIN32_MSG(ERROR_READ_FAULT, "file size changed while reading"); } // Same as ReadUTF8File, but returns an empty optional, if the file couldn't be opened. std::optional<std::string> ReadUTF8FileIfExists(const std::filesystem::path& path) { try { return { ReadUTF8File(path) }; } catch (const wil::ResultException& exception) { if (exception.GetErrorCode() == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) { return {}; } throw; } } void WriteUTF8File(const std::filesystem::path& path, const std::string_view content) { wil::unique_hfile file{ CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr) }; THROW_LAST_ERROR_IF(!file); const auto fileSize = gsl::narrow<DWORD>(content.size()); DWORD bytesWritten = 0; THROW_IF_WIN32_BOOL_FALSE(WriteFile(file.get(), content.data(), fileSize, &bytesWritten, nullptr)); if (bytesWritten != fileSize) { THROW_WIN32_MSG(ERROR_WRITE_FAULT, "failed to write whole file"); } } void WriteUTF8FileAtomic(const std::filesystem::path& path, const std::string_view content) { auto tmpPath = path; tmpPath += L".tmp"; // Writing to a file isn't atomic, but... WriteUTF8File(tmpPath, content); // renaming one is (supposed to be) atomic. // Wait... "supposed to be"!? Well it's technically not always atomic, // but it's pretty darn close to it, so... better than nothing. std::filesystem::rename(tmpPath, path); } }
42.76087
171
0.620912
[ "model" ]
b9556956e57d9690c87916a73aa08a950f529e37
3,436
cc
C++
components/cryptauth/remote_device.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/cryptauth/remote_device.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/cryptauth/remote_device.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/cryptauth/remote_device.h" #include "base/base64.h" namespace cryptauth { namespace { // Returns true if both vectors are BeaconSeeds are equal. bool AreBeaconSeedsEqual(const std::vector<BeaconSeed> beacon_seeds1, const std::vector<BeaconSeed> beacon_seeds2) { if (beacon_seeds1.size() != beacon_seeds2.size()) { return false; } for (size_t i = 0; i < beacon_seeds1.size(); ++i) { const BeaconSeed& seed1 = beacon_seeds1[i]; const BeaconSeed& seed2 = beacon_seeds2[i]; if (seed1.start_time_millis() != seed2.start_time_millis() || seed1.end_time_millis() != seed2.end_time_millis() || seed1.data() != seed2.data()) { return false; } } return true; } } // namespace RemoteDevice::RemoteDevice() {} RemoteDevice::RemoteDevice(const std::string& user_id, const std::string& name, const std::string& public_key, const std::string& bluetooth_address, const std::string& persistent_symmetric_key, std::string sign_in_challenge) : user_id(user_id), name(name), public_key(public_key), bluetooth_address(bluetooth_address), persistent_symmetric_key(persistent_symmetric_key), sign_in_challenge(sign_in_challenge) {} RemoteDevice::RemoteDevice(const RemoteDevice& other) = default; RemoteDevice::~RemoteDevice() {} void RemoteDevice::LoadBeaconSeeds( const std::vector<BeaconSeed>& beacon_seeds) { this->are_beacon_seeds_loaded = true; this->beacon_seeds = beacon_seeds; } std::string RemoteDevice::GetDeviceId() const { std::string to_return; base::Base64Encode(public_key, &to_return); return to_return; } std::string RemoteDevice::GetTruncatedDeviceIdForLogs() const { return RemoteDevice::TruncateDeviceIdForLogs(GetDeviceId()); } bool RemoteDevice::operator==(const RemoteDevice& other) const { // Only compare |beacon_seeds| if they are loaded. bool are_beacon_seeds_equal = false; if (are_beacon_seeds_loaded) { are_beacon_seeds_equal = other.are_beacon_seeds_loaded && AreBeaconSeedsEqual(beacon_seeds, other.beacon_seeds); } else { are_beacon_seeds_equal = !other.are_beacon_seeds_loaded; } return user_id == other.user_id && name == other.name && public_key == other.public_key && bluetooth_address == other.bluetooth_address && persistent_symmetric_key == other.persistent_symmetric_key && sign_in_challenge == other.sign_in_challenge && are_beacon_seeds_equal; } bool RemoteDevice::operator<(const RemoteDevice& other) const { // |public_key| is the only field guaranteed to be set and is also unique to // each RemoteDevice. However, since it can contain null bytes, use // GetDeviceId(), which cannot contain null bytes, to compare devices. return GetDeviceId().compare(other.GetDeviceId()) < 0; } // static std::string RemoteDevice::TruncateDeviceIdForLogs(const std::string& full_id) { if (full_id.length() <= 10) { return full_id; } return full_id.substr(0, 5) + "..." + full_id.substr(full_id.length() - 5, full_id.length()); } } // namespace cryptauth
32.11215
80
0.686263
[ "vector" ]
b958dbc89c37f917ed745450b7c0f41b2b8be4f9
1,608
cpp
C++
D01 Demos/Singleton/Solution/Main.cpp
FeniulaPyra/DSA2
bedaa6c11c7e248a936bf5c0f07a7cb763178ed7
[ "MIT" ]
null
null
null
D01 Demos/Singleton/Solution/Main.cpp
FeniulaPyra/DSA2
bedaa6c11c7e248a936bf5c0f07a7cb763178ed7
[ "MIT" ]
null
null
null
D01 Demos/Singleton/Solution/Main.cpp
FeniulaPyra/DSA2
bedaa6c11c7e248a936bf5c0f07a7cb763178ed7
[ "MIT" ]
null
null
null
/*-------------------------------------------------------------------------------------------------- Programmer: labigm@rit.edu --------------------------------------------------------------------------------------------------*/ #include <ostream> class Foo { static Foo* instance; // will be shared among all objects instantiated of this class int var; private: Foo(){ var = 10; }; Foo(Foo const& other){}; Foo& operator=(Foo const& other){}; public: // Because of the static can be called even without instantiating an object of this class static Foo* GetInstance()//Will act as the constructor if the object is not defined { if (instance == nullptr)//Is the instance pointer empty? { instance = new Foo();//create a new pointer } return instance;//return the pointer whatever the case } static void ReleaseInstance()//Will act as the destructor if the object is already defined { if (instance != nullptr)//is the instance already allocated in memory? { delete instance;//it is! so delete it instance = nullptr;//make it point to a safe location } } }; Foo* Foo::instance = nullptr;//make the Foo pointer inside of the Foo class point to a safe location int main(void) { Foo* oFoo = Foo::GetInstance();//Get the instance so I can do something with it (or construct it if not existent) if (true)//just a way of placing the scope { Foo* oFoo1 = Foo::GetInstance();//Get the instance so I can do something with it (or construct it if not existent) } oFoo->ReleaseInstance();//This is the very last Foo object to access the class... Release the memory return 0; }
35.733333
116
0.623756
[ "object" ]
b95f6a28d956711809a2b78a22f23c544e0cca3f
2,014
cpp
C++
aws-cpp-sdk-securityhub/source/model/AwsElbLoadBalancerListenerDescription.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-securityhub/source/model/AwsElbLoadBalancerListenerDescription.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-securityhub/source/model/AwsElbLoadBalancerListenerDescription.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/securityhub/model/AwsElbLoadBalancerListenerDescription.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { AwsElbLoadBalancerListenerDescription::AwsElbLoadBalancerListenerDescription() : m_listenerHasBeenSet(false), m_policyNamesHasBeenSet(false) { } AwsElbLoadBalancerListenerDescription::AwsElbLoadBalancerListenerDescription(JsonView jsonValue) : m_listenerHasBeenSet(false), m_policyNamesHasBeenSet(false) { *this = jsonValue; } AwsElbLoadBalancerListenerDescription& AwsElbLoadBalancerListenerDescription::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Listener")) { m_listener = jsonValue.GetObject("Listener"); m_listenerHasBeenSet = true; } if(jsonValue.ValueExists("PolicyNames")) { Array<JsonView> policyNamesJsonList = jsonValue.GetArray("PolicyNames"); for(unsigned policyNamesIndex = 0; policyNamesIndex < policyNamesJsonList.GetLength(); ++policyNamesIndex) { m_policyNames.push_back(policyNamesJsonList[policyNamesIndex].AsString()); } m_policyNamesHasBeenSet = true; } return *this; } JsonValue AwsElbLoadBalancerListenerDescription::Jsonize() const { JsonValue payload; if(m_listenerHasBeenSet) { payload.WithObject("Listener", m_listener.Jsonize()); } if(m_policyNamesHasBeenSet) { Array<JsonValue> policyNamesJsonList(m_policyNames.size()); for(unsigned policyNamesIndex = 0; policyNamesIndex < policyNamesJsonList.GetLength(); ++policyNamesIndex) { policyNamesJsonList[policyNamesIndex].AsString(m_policyNames[policyNamesIndex]); } payload.WithArray("PolicyNames", std::move(policyNamesJsonList)); } return payload; } } // namespace Model } // namespace SecurityHub } // namespace Aws
24.26506
110
0.761172
[ "model" ]
b9600e8de57056d7229d0ea0ef8488628d22844c
1,528
hpp
C++
include/ohf/ssl/Handshake.hpp
Good-Pudge/OkHttpFork
b179350d6262f281c1c27d69d944c62f536fe1ba
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
10
2019-02-21T06:21:48.000Z
2022-02-22T08:01:24.000Z
include/ohf/ssl/Handshake.hpp
Good-Pudge/OkHttpFork
b179350d6262f281c1c27d69d944c62f536fe1ba
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
2
2018-02-04T20:16:46.000Z
2018-02-04T20:19:00.000Z
include/ohf/ssl/Handshake.hpp
Good-Pudge/OkHttpFork
b179350d6262f281c1c27d69d944c62f536fe1ba
[ "BSL-1.0", "Apache-2.0", "OpenSSL" ]
10
2018-10-15T10:17:00.000Z
2022-02-17T02:28:51.000Z
// // Created by Good_Pudge. // #ifndef OKHTTPFORK_SSL_HANDSHAKE_HPP #define OKHTTPFORK_SSL_HANDSHAKE_HPP #include <ohf/ssl/CipherSuite.hpp> #include <ohf/ssl/X509Certificate.hpp> #include <ohf/Principal.hpp> #include <ohf/TLSVersion.hpp> #include <ohf/ssl/SSL.hpp> #include <vector> namespace ohf { namespace ssl { class Handshake { public: Handshake() = default; explicit Handshake(SSL &ssl); Handshake(const TLSVersion &tlsVersion, const CipherSuite &cipherSuite, const std::vector<X509Certificate> &peerCertificates, const std::vector<X509Certificate> &localCertificates); CipherSuite cipherSuite(); bool operator ==(const Handshake &handshake) const; // static Handshake get(const SSLSession &session); static Handshake get(const TLSVersion &tlsVersion, const CipherSuite &cipherSuite, const std::vector<X509Certificate> &peerCertificates, const std::vector<X509Certificate> &localCertificates); std::vector<X509Certificate> localCertificates(); Principal localPrincipal(); std::vector<X509Certificate> peerCertificates(); Principal peerPrincipal(); TLSVersion tlsVersion(); private: TLSVersion mVersion; //CipherSuite mSuite; }; } } #endif //OKHTTPFORK_HANDSHAKE_HPP
27.781818
94
0.61322
[ "vector" ]
b965112cde62d8e1990e8f8adad914eedbfc3fff
14,960
cpp
C++
src/algorithms/LBSP/LBSP.cpp
saulocbarreto/bgslibrary
e1890b6b05cd40757ad00e1c71e8c1db13a74a2a
[ "MIT" ]
1,899
2015-01-04T01:13:30.000Z
2022-03-29T21:58:28.000Z
src/algorithms/LBSP/LBSP.cpp
saulocbarreto/bgslibrary
e1890b6b05cd40757ad00e1c71e8c1db13a74a2a
[ "MIT" ]
175
2015-01-25T16:14:03.000Z
2022-03-17T17:36:53.000Z
src/algorithms/LBSP/LBSP.cpp
saulocbarreto/bgslibrary
e1890b6b05cd40757ad00e1c71e8c1db13a74a2a
[ "MIT" ]
752
2015-01-04T01:34:29.000Z
2022-03-29T13:53:33.000Z
#include "LBSP.h" //using namespace bgslibrary::algorithms::lbsp; namespace bgslibrary { namespace algorithms { namespace lbsp { LBSP::LBSP(size_t nThreshold) : m_bOnlyUsingAbsThreshold(true) , m_fRelThreshold(0) // unused , m_nThreshold(nThreshold) , m_oRefImage() {} LBSP::LBSP(float fRelThreshold, size_t nThresholdOffset) : m_bOnlyUsingAbsThreshold(false) , m_fRelThreshold(fRelThreshold) , m_nThreshold(nThresholdOffset) , m_oRefImage() { CV_Assert(m_fRelThreshold >= 0); } LBSP::~LBSP() {} void LBSP::read(const cv::FileNode& /*fn*/) { // ... = fn["..."]; } void LBSP::write(cv::FileStorage& /*fs*/) const { //fs << "..." << ...; } void LBSP::setReference(const cv::Mat& img) { CV_DbgAssert(img.empty() || img.type() == CV_8UC1 || img.type() == CV_8UC3); m_oRefImage = img; } int LBSP::descriptorSize() const { return DESC_SIZE; } int LBSP::descriptorType() const { return CV_16U; } bool LBSP::isUsingRelThreshold() const { return !m_bOnlyUsingAbsThreshold; } float LBSP::getRelThreshold() const { return m_fRelThreshold; } size_t LBSP::getAbsThreshold() const { return m_nThreshold; } static inline void lbsp_computeImpl(const cv::Mat& oInputImg, const cv::Mat& oRefImg, const std::vector<cv::KeyPoint>& voKeyPoints, cv::Mat& oDesc, size_t _t) { CV_DbgAssert(oRefImg.empty() || (oRefImg.size == oInputImg.size && oRefImg.type() == oInputImg.type())); CV_DbgAssert(oInputImg.type() == CV_8UC1 || oInputImg.type() == CV_8UC3); CV_DbgAssert(LBSP::DESC_SIZE == 2); // @@@ also relies on a constant desc size const size_t nChannels = (size_t)oInputImg.channels(); const size_t _step_row = oInputImg.step.p[0]; const uchar* _data = oInputImg.data; const uchar* _refdata = oRefImg.empty() ? oInputImg.data : oRefImg.data; const size_t nKeyPoints = voKeyPoints.size(); if (nChannels == 1) { oDesc.create((int)nKeyPoints, 1, CV_16UC1); for (size_t k = 0; k < nKeyPoints; ++k) { const int _x = (int)voKeyPoints[k].pt.x; const int _y = (int)voKeyPoints[k].pt.y; const uchar _ref = _refdata[_step_row*(_y)+_x]; ushort& _res = oDesc.at<ushort>((int)k); #include "LBSP_16bits_dbcross_1ch.i" } } else { //nChannels==3 oDesc.create((int)nKeyPoints, 1, CV_16UC3); for (size_t k = 0; k < nKeyPoints; ++k) { const int _x = (int)voKeyPoints[k].pt.x; const int _y = (int)voKeyPoints[k].pt.y; const uchar* _ref = _refdata + _step_row*(_y)+3 * (_x); ushort* _res = ((ushort*)(oDesc.data + oDesc.step.p[0] * k)); #include "LBSP_16bits_dbcross_3ch1t.i" } } } static inline void lbsp_computeImpl(const cv::Mat& oInputImg, const cv::Mat& oRefImg, const std::vector<cv::KeyPoint>& voKeyPoints, cv::Mat& oDesc, float fThreshold, size_t nThresholdOffset) { CV_DbgAssert(oRefImg.empty() || (oRefImg.size == oInputImg.size && oRefImg.type() == oInputImg.type())); CV_DbgAssert(oInputImg.type() == CV_8UC1 || oInputImg.type() == CV_8UC3); CV_DbgAssert(LBSP::DESC_SIZE == 2); // @@@ also relies on a constant desc size CV_DbgAssert(fThreshold >= 0); const size_t nChannels = (size_t)oInputImg.channels(); const size_t _step_row = oInputImg.step.p[0]; const uchar* _data = oInputImg.data; const uchar* _refdata = oRefImg.empty() ? oInputImg.data : oRefImg.data; const size_t nKeyPoints = voKeyPoints.size(); if (nChannels == 1) { oDesc.create((int)nKeyPoints, 1, CV_16UC1); for (size_t k = 0; k < nKeyPoints; ++k) { const int _x = (int)voKeyPoints[k].pt.x; const int _y = (int)voKeyPoints[k].pt.y; const uchar _ref = _refdata[_step_row*(_y)+_x]; ushort& _res = oDesc.at<ushort>((int)k); const size_t _t = (size_t)(_ref*fThreshold) + nThresholdOffset; #include "LBSP_16bits_dbcross_1ch.i" } } else { //nChannels==3 oDesc.create((int)nKeyPoints, 1, CV_16UC3); for (size_t k = 0; k < nKeyPoints; ++k) { const int _x = (int)voKeyPoints[k].pt.x; const int _y = (int)voKeyPoints[k].pt.y; const uchar* _ref = _refdata + _step_row*(_y)+3 * (_x); ushort* _res = ((ushort*)(oDesc.data + oDesc.step.p[0] * k)); const size_t _t[3] = { (size_t)(_ref[0] * fThreshold) + nThresholdOffset,(size_t)(_ref[1] * fThreshold) + nThresholdOffset,(size_t)(_ref[2] * fThreshold) + nThresholdOffset }; #include "LBSP_16bits_dbcross_3ch3t.i" } } } static inline void lbsp_computeImpl2(const cv::Mat& oInputImg, const cv::Mat& oRefImg, const std::vector<cv::KeyPoint>& voKeyPoints, cv::Mat& oDesc, size_t _t) { CV_DbgAssert(oRefImg.empty() || (oRefImg.size == oInputImg.size && oRefImg.type() == oInputImg.type())); CV_DbgAssert(oInputImg.type() == CV_8UC1 || oInputImg.type() == CV_8UC3); CV_DbgAssert(LBSP::DESC_SIZE == 2); // @@@ also relies on a constant desc size const size_t nChannels = (size_t)oInputImg.channels(); const size_t _step_row = oInputImg.step.p[0]; const uchar* _data = oInputImg.data; const uchar* _refdata = oRefImg.empty() ? oInputImg.data : oRefImg.data; const size_t nKeyPoints = voKeyPoints.size(); if (nChannels == 1) { oDesc.create(oInputImg.size(), CV_16UC1); for (size_t k = 0; k < nKeyPoints; ++k) { const int _x = (int)voKeyPoints[k].pt.x; const int _y = (int)voKeyPoints[k].pt.y; const uchar _ref = _refdata[_step_row*(_y)+_x]; ushort& _res = oDesc.at<ushort>(_y, _x); #include "LBSP_16bits_dbcross_1ch.i" } } else { //nChannels==3 oDesc.create(oInputImg.size(), CV_16UC3); for (size_t k = 0; k < nKeyPoints; ++k) { const int _x = (int)voKeyPoints[k].pt.x; const int _y = (int)voKeyPoints[k].pt.y; const uchar* _ref = _refdata + _step_row*(_y)+3 * (_x); ushort* _res = ((ushort*)(oDesc.data + oDesc.step.p[0] * _y + oDesc.step.p[1] * _x)); #include "LBSP_16bits_dbcross_3ch1t.i" } } } static inline void lbsp_computeImpl2(const cv::Mat& oInputImg, const cv::Mat& oRefImg, const std::vector<cv::KeyPoint>& voKeyPoints, cv::Mat& oDesc, float fThreshold, size_t nThresholdOffset) { CV_DbgAssert(oRefImg.empty() || (oRefImg.size == oInputImg.size && oRefImg.type() == oInputImg.type())); CV_DbgAssert(oInputImg.type() == CV_8UC1 || oInputImg.type() == CV_8UC3); CV_DbgAssert(LBSP::DESC_SIZE == 2); // @@@ also relies on a constant desc size CV_DbgAssert(fThreshold >= 0); const size_t nChannels = (size_t)oInputImg.channels(); const size_t _step_row = oInputImg.step.p[0]; const uchar* _data = oInputImg.data; const uchar* _refdata = oRefImg.empty() ? oInputImg.data : oRefImg.data; const size_t nKeyPoints = voKeyPoints.size(); if (nChannels == 1) { oDesc.create(oInputImg.size(), CV_16UC1); for (size_t k = 0; k < nKeyPoints; ++k) { const int _x = (int)voKeyPoints[k].pt.x; const int _y = (int)voKeyPoints[k].pt.y; const uchar _ref = _refdata[_step_row*(_y)+_x]; ushort& _res = oDesc.at<ushort>(_y, _x); const size_t _t = (size_t)(_ref*fThreshold) + nThresholdOffset; #include "LBSP_16bits_dbcross_1ch.i" } } else { //nChannels==3 oDesc.create(oInputImg.size(), CV_16UC3); for (size_t k = 0; k < nKeyPoints; ++k) { const int _x = (int)voKeyPoints[k].pt.x; const int _y = (int)voKeyPoints[k].pt.y; const uchar* _ref = _refdata + _step_row*(_y)+3 * (_x); ushort* _res = ((ushort*)(oDesc.data + oDesc.step.p[0] * _y + oDesc.step.p[1] * _x)); const size_t _t[3] = { (size_t)(_ref[0] * fThreshold) + nThresholdOffset,(size_t)(_ref[1] * fThreshold) + nThresholdOffset,(size_t)(_ref[2] * fThreshold) + nThresholdOffset }; #include "LBSP_16bits_dbcross_3ch3t.i" } } } void LBSP::compute2(const cv::Mat& oImage, std::vector<cv::KeyPoint>& voKeypoints, cv::Mat& oDescriptors) const { CV_Assert(!oImage.empty()); cv::KeyPointsFilter::runByImageBorder(voKeypoints, oImage.size(), PATCH_SIZE / 2); cv::KeyPointsFilter::runByKeypointSize(voKeypoints, std::numeric_limits<float>::epsilon()); if (voKeypoints.empty()) { oDescriptors.release(); return; } if (m_bOnlyUsingAbsThreshold) lbsp_computeImpl2(oImage, m_oRefImage, voKeypoints, oDescriptors, m_nThreshold); else lbsp_computeImpl2(oImage, m_oRefImage, voKeypoints, oDescriptors, m_fRelThreshold, m_nThreshold); } void LBSP::compute2(const std::vector<cv::Mat>& voImageCollection, std::vector<std::vector<cv::KeyPoint> >& vvoPointCollection, std::vector<cv::Mat>& voDescCollection) const { CV_Assert(voImageCollection.size() == vvoPointCollection.size()); voDescCollection.resize(voImageCollection.size()); for (size_t i = 0; i < voImageCollection.size(); i++) compute2(voImageCollection[i], vvoPointCollection[i], voDescCollection[i]); } void LBSP::computeImpl(const cv::Mat& oImage, std::vector<cv::KeyPoint>& voKeypoints, cv::Mat& oDescriptors) const { CV_Assert(!oImage.empty()); cv::KeyPointsFilter::runByImageBorder(voKeypoints, oImage.size(), PATCH_SIZE / 2); cv::KeyPointsFilter::runByKeypointSize(voKeypoints, std::numeric_limits<float>::epsilon()); if (voKeypoints.empty()) { oDescriptors.release(); return; } if (m_bOnlyUsingAbsThreshold) lbsp_computeImpl(oImage, m_oRefImage, voKeypoints, oDescriptors, m_nThreshold); else lbsp_computeImpl(oImage, m_oRefImage, voKeypoints, oDescriptors, m_fRelThreshold, m_nThreshold); } void LBSP::reshapeDesc(cv::Size oSize, const std::vector<cv::KeyPoint>& voKeypoints, const cv::Mat& oDescriptors, cv::Mat& oOutput) { CV_DbgAssert(!voKeypoints.empty()); CV_DbgAssert(!oDescriptors.empty() && oDescriptors.cols == 1); CV_DbgAssert(oSize.width > 0 && oSize.height > 0); CV_DbgAssert(DESC_SIZE == 2); // @@@ also relies on a constant desc size CV_DbgAssert(oDescriptors.type() == CV_16UC1 || oDescriptors.type() == CV_16UC3); const size_t nChannels = (size_t)oDescriptors.channels(); const size_t nKeyPoints = voKeypoints.size(); if (nChannels == 1) { oOutput.create(oSize, CV_16UC1); oOutput = cv::Scalar_<ushort>(0); for (size_t k = 0; k < nKeyPoints; ++k) oOutput.at<ushort>(voKeypoints[k].pt) = oDescriptors.at<ushort>((int)k); } else { //nChannels==3 oOutput.create(oSize, CV_16UC3); oOutput = cv::Scalar_<ushort>(0, 0, 0); for (size_t k = 0; k < nKeyPoints; ++k) { ushort* output_ptr = (ushort*)(oOutput.data + oOutput.step.p[0] * (int)voKeypoints[k].pt.y); const ushort* const desc_ptr = (ushort*)(oDescriptors.data + oDescriptors.step.p[0] * k); const size_t idx = 3 * (int)voKeypoints[k].pt.x; for (size_t n = 0; n < 3; ++n) output_ptr[idx + n] = desc_ptr[n]; } } } void LBSP::calcDescImgDiff(const cv::Mat& oDesc1, const cv::Mat& oDesc2, cv::Mat& oOutput, bool bForceMergeChannels) { CV_DbgAssert(oDesc1.size() == oDesc2.size() && oDesc1.type() == oDesc2.type()); CV_DbgAssert(DESC_SIZE == 2); // @@@ also relies on a constant desc size CV_DbgAssert(oDesc1.type() == CV_16UC1 || oDesc1.type() == CV_16UC3); CV_DbgAssert(CV_MAT_DEPTH(oDesc1.type()) == CV_16U); CV_DbgAssert(DESC_SIZE * 8 <= UCHAR_MAX); CV_DbgAssert(oDesc1.step.p[0] == oDesc2.step.p[0] && oDesc1.step.p[1] == oDesc2.step.p[1]); const float fScaleFactor = (float)UCHAR_MAX / (DESC_SIZE * 8); const size_t nChannels = CV_MAT_CN(oDesc1.type()); const size_t _step_row = oDesc1.step.p[0]; if (nChannels == 1) { oOutput.create(oDesc1.size(), CV_8UC1); oOutput = cv::Scalar(0); for (int i = 0; i < oDesc1.rows; ++i) { const size_t idx = _step_row*i; const ushort* const desc1_ptr = (ushort*)(oDesc1.data + idx); const ushort* const desc2_ptr = (ushort*)(oDesc2.data + idx); for (int j = 0; j < oDesc1.cols; ++j) oOutput.at<uchar>(i, j) = (uchar)(fScaleFactor*hdist(desc1_ptr[j], desc2_ptr[j])); } } else { //nChannels==3 if (bForceMergeChannels) oOutput.create(oDesc1.size(), CV_8UC1); else oOutput.create(oDesc1.size(), CV_8UC3); oOutput = cv::Scalar::all(0); for (int i = 0; i < oDesc1.rows; ++i) { const size_t idx = _step_row*i; const ushort* const desc1_ptr = (ushort*)(oDesc1.data + idx); const ushort* const desc2_ptr = (ushort*)(oDesc2.data + idx); uchar* output_ptr = oOutput.data + oOutput.step.p[0] * i; for (int j = 0; j < oDesc1.cols; ++j) { for (size_t n = 0; n < 3; ++n) { const size_t idx2 = 3 * j + n; if (bForceMergeChannels) output_ptr[j] += (uchar)((fScaleFactor*hdist(desc1_ptr[idx2], desc2_ptr[idx2])) / 3); else output_ptr[idx2] = (uchar)(fScaleFactor*hdist(desc1_ptr[idx2], desc2_ptr[idx2])); } } } } } void LBSP::validateKeyPoints(std::vector<cv::KeyPoint>& voKeypoints, cv::Size oImgSize) { cv::KeyPointsFilter::runByImageBorder(voKeypoints, oImgSize, PATCH_SIZE / 2); } void LBSP::validateROI(cv::Mat& oROI) { CV_Assert(!oROI.empty() && oROI.type() == CV_8UC1); cv::Mat oROI_new(oROI.size(), CV_8UC1, cv::Scalar_<uchar>(0)); const size_t nBorderSize = PATCH_SIZE / 2; const cv::Rect nROI_inner(nBorderSize, nBorderSize, oROI.cols - nBorderSize * 2, oROI.rows - nBorderSize * 2); cv::Mat(oROI, nROI_inner).copyTo(cv::Mat(oROI_new, nROI_inner)); oROI = oROI_new; } } } }
45.333333
187
0.5875
[ "vector" ]
b969ed100aeb4baa67db0039070f62b03f67051f
15,212
cc
C++
node_modules/libxmljs/src/xml_element.cc
jonbaer/hn_reader
9b4ff39b3443cf23f13fec916c1ed79e0ce8817a
[ "Unlicense" ]
2
2016-10-27T14:40:27.000Z
2018-08-12T13:29:49.000Z
node_modules/libxmljs/src/xml_element.cc
jonbaer/hn_reader
9b4ff39b3443cf23f13fec916c1ed79e0ce8817a
[ "Unlicense" ]
null
null
null
node_modules/libxmljs/src/xml_element.cc
jonbaer/hn_reader
9b4ff39b3443cf23f13fec916c1ed79e0ce8817a
[ "Unlicense" ]
null
null
null
// Copyright 2009, Squish Tech, LLC. #include "xml_element.h" #include "xml_document.h" #include "xml_attribute.h" #include "xml_xpath_context.h" namespace libxmljs { #define NAME_SYMBOL v8::String::NewSymbol("name") #define CONTENT_SYMBOL v8::String::NewSymbol("content") v8::Persistent<v8::FunctionTemplate> XmlElement::constructor_template; // doc, name, attrs, content, callback v8::Handle<v8::Value> XmlElement::New(const v8::Arguments& args) { v8::HandleScope scope; // was created by BUILD_NODE if (args.Length() == 0 || args[0]->StrictEquals(v8::Null())) return scope.Close(args.This()); XmlDocument *document = LibXmlObj::Unwrap<XmlDocument>(args[0]->ToObject()); v8::String::Utf8Value name(args[1]); v8::Handle<v8::Function> callback; char* content = NULL; if(!args[3]->IsUndefined() && !args[3]->IsNull()) { v8::String::Utf8Value content_(args[3]); content = strdup(*content_); } if (args[4]->IsFunction()) callback = v8::Handle<v8::Function>::Cast(args[4]); xmlNode* elem = xmlNewDocNode(document->xml_obj, NULL, (const xmlChar*)*name, (const xmlChar*)content); UpdateV8Memory(); if(content) free(content); v8::Handle<v8::Object> obj = LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(elem); XmlElement *element = LibXmlObj::Unwrap<XmlElement>(obj); if (args[2]->IsObject()) { v8::Handle<v8::Object> attributes = args[2]->ToObject(); v8::Handle<v8::Array> props = attributes->GetPropertyNames(); for (unsigned int i = 0; i < props->Length(); i++) { v8::String::Utf8Value name( props->Get(v8::Number::New(i))); v8::String::Utf8Value value( attributes->Get(props->Get(v8::Number::New(i)))); element->set_attr(*name, *value); } } obj->Set(v8::String::NewSymbol("document"), args[0]->ToObject()); if (*callback && !callback->IsNull()) { v8::Handle<v8::Value> argv[1] = { obj }; *callback->Call(obj, 1, argv); } return scope.Close(obj); } v8::Handle<v8::Value> XmlElement::Name(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); if (args.Length() == 0) return scope.Close(element->get_name()); v8::String::Utf8Value name(args[0]->ToString()); element->set_name(*name); return scope.Close(args.This()); } v8::Handle<v8::Value> XmlElement::Attr(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); v8::Handle<v8::Object> attrs; switch (args.Length()) { case 1: // return the named attribute if (args[0]->IsString()) { v8::String::Utf8Value name(args[0]); return scope.Close(element->get_attr(*name)); // create a new attribute from a hash } else { attrs = args[0]->ToObject(); } break; // 1 argument only dude default: LIBXMLJS_THROW_EXCEPTION( "Bad argument(s): #attr(name) or #attr({name: value})"); } v8::Handle<v8::Array> properties = attrs->GetPropertyNames(); for (unsigned int i = 0; i < properties->Length(); i++) { v8::Local<v8::String> prop_name = properties->Get( v8::Number::New(i))->ToString(); if(attrs->HasRealNamedProperty(prop_name)) { v8::String::Utf8Value name(prop_name); v8::String::Utf8Value value(attrs->Get(prop_name)); element->set_attr(*name, *value); } } return scope.Close(args.This()); } v8::Handle<v8::Value> XmlElement::Attrs(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); return scope.Close(element->get_attrs()); } v8::Handle<v8::Value> XmlElement::AddChild(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); XmlElement *child = LibXmlObj::Unwrap<XmlElement>(args[0]->ToObject()); assert(child); child = element->import_element(child); if(child == NULL) { LIBXMLJS_THROW_EXCEPTION("Could not add child. Failed to copy node to new Document."); } element->add_child(child); return scope.Close(args.This()); } v8::Handle<v8::Value> XmlElement::Find(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); v8::String::Utf8Value xpath(args[0]); XmlXpathContext ctxt(element->xml_obj); if (args.Length() == 2) { if (args[1]->IsString()) { v8::String::Utf8Value uri(args[1]); ctxt.register_ns((const xmlChar*)"xmlns", (const xmlChar*)*uri); } else if (args[1]->IsObject()) { v8::Handle<v8::Object> namespaces = args[1]->ToObject(); v8::Handle<v8::Array> properties = namespaces->GetPropertyNames(); for (unsigned int i = 0; i < properties->Length(); i++) { v8::Local<v8::String> prop_name = properties->Get( v8::Number::New(i))->ToString(); v8::String::Utf8Value prefix(prop_name); v8::String::Utf8Value uri(namespaces->Get(prop_name)); ctxt.register_ns((const xmlChar*)*prefix, (const xmlChar*)*uri); } } } return scope.Close(ctxt.evaluate((const xmlChar*)*xpath)); } v8::Handle<v8::Value> XmlElement::NextElement(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); return scope.Close(element->get_next_element()); } v8::Handle<v8::Value> XmlElement::PrevElement(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); return scope.Close(element->get_prev_element()); } v8::Handle<v8::Value> XmlElement::Text(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); if (args.Length() == 0) { return scope.Close(element->get_content()); } else { element->set_content(*v8::String::Utf8Value(args[0])); } return scope.Close(args.This()); } v8::Handle<v8::Value> XmlElement::Child(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); double idx = 1; if (args.Length() > 0) { if (!args[0]->IsNumber()) { LIBXMLJS_THROW_EXCEPTION( "Bad argument: must provide #child() with a number"); } else { idx = args[0]->ToNumber()->Value(); } } return scope.Close(element->get_child(idx)); } v8::Handle<v8::Value> XmlElement::ChildNodes(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); if (args[0]->IsNumber()) return scope.Close(element->get_child(args[0]->ToNumber()->Value())); return scope.Close(element->get_child_nodes()); } v8::Handle<v8::Value> XmlElement::Path(const v8::Arguments& args) { v8::HandleScope scope; XmlElement *element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); return scope.Close(element->get_path()); } v8::Handle<v8::Value> XmlElement::AddPrevSibling(const v8::Arguments& args) { v8::HandleScope scope; XmlElement* element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); XmlElement* new_sibling = LibXmlObj::Unwrap<XmlElement>(args[0]->ToObject()); assert(new_sibling); new_sibling = element->import_element(new_sibling); element->add_prev_sibling(new_sibling); return scope.Close(args[0]); } v8::Handle<v8::Value> XmlElement::AddNextSibling(const v8::Arguments& args) { v8::HandleScope scope; XmlElement* element = LibXmlObj::Unwrap<XmlElement>(args.This()); assert(element); XmlElement* new_sibling = LibXmlObj::Unwrap<XmlElement>(args[0]->ToObject()); assert(new_sibling); new_sibling = element->import_element(new_sibling); element->add_next_sibling(new_sibling); return scope.Close(args[0]); } void XmlElement::set_name(const char* name) { xmlNodeSetName(xml_obj, (const xmlChar*)name); } v8::Handle<v8::Value> XmlElement::get_name() { if(xml_obj->name) return v8::String::New((const char*)xml_obj->name); else return v8::Undefined(); } // TODO(sprsquish) make these work with namespaces v8::Handle<v8::Value> XmlElement::get_attr(const char* name) { v8::HandleScope scope; xmlAttr* attr = xmlHasProp(xml_obj, (const xmlChar*)name); if (attr) { return scope.Close(LibXmlObj::GetMaybeBuild<XmlAttribute, xmlAttr>(attr)); } return v8::Null(); } // TODO(sprsquish) make these work with namespaces void XmlElement::set_attr(const char* name, const char* value) { v8::HandleScope scope; v8::Handle<v8::Value> argv[3] = { LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(xml_obj), v8::String::New(name), v8::String::New(value) }; XmlAttribute::constructor_template->GetFunction()->NewInstance(3, argv); } v8::Handle<v8::Value> XmlElement::get_attrs() { v8::HandleScope scope; xmlAttr* attr = xml_obj->properties; if (!attr) return scope.Close(v8::Array::New(0)); v8::Handle<v8::Array> attributes = v8::Array::New(); v8::Handle<v8::Function> push = v8::Handle<v8::Function>::Cast( attributes->Get(v8::String::NewSymbol("push"))); v8::Handle<v8::Value> argv[1]; do { argv[0] = LibXmlObj::GetMaybeBuild<XmlAttribute, xmlAttr>(attr); push->Call(attributes, 1, argv); } while ((attr = attr->next)); return scope.Close(attributes); } void XmlElement::add_child(XmlElement* child) { xmlAddChild(xml_obj, child->xml_obj); } v8::Handle<v8::Value> XmlElement::get_child(double idx) { v8::HandleScope scope; double i = 1; xmlNode* child = xml_obj->children; while (child && i < idx) { child = child->next; i++; } if (!child) return v8::Null(); return scope.Close(LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(child)); } v8::Handle<v8::Value> XmlElement::get_child_nodes() { v8::HandleScope scope; xmlNode* child = xml_obj->children; if (!child) return scope.Close(v8::Array::New(0)); xmlNodeSetPtr set = xmlXPathNodeSetCreate(child); do { xmlXPathNodeSetAdd(set, child); } while ((child = child->next)); v8::Handle<v8::Array> children = v8::Array::New(set->nodeNr); for (int i = 0; i < set->nodeNr; ++i) { xmlNode *node = set->nodeTab[i]; children->Set(v8::Number::New(i), LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(node)); } xmlXPathFreeNodeSet(set); return scope.Close(children); } v8::Handle<v8::Value> XmlElement::get_path() { xmlChar* path = xmlGetNodePath(xml_obj); const char* return_path = path ? reinterpret_cast<char*>(path) : ""; int str_len = xmlStrlen((const xmlChar*)return_path); v8::Handle<v8::String> js_obj = v8::String::New(return_path, str_len); xmlFree(path); return js_obj; } void XmlElement::set_content(const char* content) { xmlNodeSetContent(xml_obj, (const xmlChar*)content); } v8::Handle<v8::Value> XmlElement::get_content() { xmlChar* content = xmlNodeGetContent(xml_obj); if (content) { v8::Handle<v8::String> ret_content = v8::String::New((const char *)content); xmlFree(content); return ret_content; } return v8::String::Empty(); } v8::Handle<v8::Value> XmlElement::get_next_element() { v8::HandleScope scope; xmlNode *sibling; sibling = xml_obj->next; if (!sibling) return v8::Null(); while (sibling && sibling->type != XML_ELEMENT_NODE) sibling = sibling->next; if (sibling) { return scope.Close(LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(sibling)); } return v8::Null(); } v8::Handle<v8::Value> XmlElement::get_prev_element() { v8::HandleScope scope; xmlNode *sibling; sibling = xml_obj->prev; if (!sibling) return v8::Null(); while (sibling && sibling->type != XML_ELEMENT_NODE) { sibling = sibling->prev; } if (sibling) { return scope.Close(LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(sibling)); } return v8::Null(); } void XmlElement::add_prev_sibling(XmlElement* element) { xmlAddPrevSibling(xml_obj, element->xml_obj); } void XmlElement::add_next_sibling(XmlElement* element) { xmlAddNextSibling(xml_obj, element->xml_obj); } XmlElement * XmlElement::import_element(XmlElement *element) { xmlNode *new_child; if(element->xml_obj->type == XML_ELEMENT_NODE || xml_obj->doc == element->xml_obj->doc) { return element; } else { new_child = xmlDocCopyNode(element->xml_obj, xml_obj->doc, 1); if(new_child == NULL) { return NULL; } element->remove(); UpdateV8Memory(); v8::Handle<v8::Object> obj = LibXmlObj::GetMaybeBuild<XmlElement, xmlNode>(new_child); return LibXmlObj::Unwrap<XmlElement>(obj); } } void XmlElement::Initialize(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(New); constructor_template = v8::Persistent<v8::FunctionTemplate>::New(t); constructor_template->Inherit(XmlNode::constructor_template); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); LXJS_SET_PROTO_METHOD(constructor_template, "addChild", XmlElement::AddChild); LXJS_SET_PROTO_METHOD(constructor_template, "attr", XmlElement::Attr); LXJS_SET_PROTO_METHOD(constructor_template, "attrs", XmlElement::Attrs); LXJS_SET_PROTO_METHOD(constructor_template, "child", XmlElement::Child); LXJS_SET_PROTO_METHOD(constructor_template, "childNodes", XmlElement::ChildNodes); LXJS_SET_PROTO_METHOD(constructor_template, "find", XmlElement::Find); LXJS_SET_PROTO_METHOD(constructor_template, "nextElement", XmlElement::NextElement); LXJS_SET_PROTO_METHOD(constructor_template, "prevElement", XmlElement::PrevElement); LXJS_SET_PROTO_METHOD(constructor_template, "name", XmlElement::Name); LXJS_SET_PROTO_METHOD(constructor_template, "path", XmlElement::Path); LXJS_SET_PROTO_METHOD(constructor_template, "text", XmlElement::Text); LXJS_SET_PROTO_METHOD(constructor_template, "addPrevSibling", XmlElement::AddPrevSibling); LXJS_SET_PROTO_METHOD(constructor_template, "addNextSibling", XmlElement::AddNextSibling); target->Set(v8::String::NewSymbol("Element"), constructor_template->GetFunction()); } } // namespace libxmljs
27.115865
93
0.643374
[ "object" ]
b96bd5beaa4a9cef73108f4b6bfa487caadaed49
37,330
cc
C++
src/StateVector.cc
felicepantaleo/helix-fitting
d1540156430f0e4ea85a9fd0e0f08e3447f0ec3f
[ "Apache-2.0" ]
1
2018-06-04T03:44:24.000Z
2018-06-04T03:44:24.000Z
src/StateVector.cc
felicepantaleo/helix-fitting
d1540156430f0e4ea85a9fd0e0f08e3447f0ec3f
[ "Apache-2.0" ]
null
null
null
src/StateVector.cc
felicepantaleo/helix-fitting
d1540156430f0e4ea85a9fd0e0f08e3447f0ec3f
[ "Apache-2.0" ]
null
null
null
// $Id: StateVector.cc,v 1.1 2001/11/16 10:29:55 wwalten Exp $ // -*- C++ -*- #include <CLHEP/config/iostream.h> #include <CLHEP/config/CLHEP.h> #include <stdlib.h> #ifdef DEBUG #include <assert.h> #endif #include "defines.h" #include "Plane.h" #include "StateVector.h" #include "CLHEP/Random/RandGauss.h" #include "CLHEP/Matrix/Vector.h" #include "any2str.h" #ifdef GL #include <Inventor/nodes/SoTransform.h> #include <Inventor/nodes/SoSelection.h> #include <Inventor/nodes/SoMaterial.h> #include "hepvis/SoHelicalTrack.hh" vector <StateVector> sv_list; extern int hlx_shows; extern void addChild ( SoSelection *, SoNode *, string (*info)(int), int,bool); extern void addChild ( SoSelection *, SoNode *, string (*info)(int), int ); extern void addChild ( SoSelection *root, SoNode *node ); extern int matrix_prec; #endif /* ifdef GL */ extern void file_not_found (string filename); inline string del_leading_spaces(string line) { while (line.find_first_of(" ")==0) { line.erase(0,1); // delete leading spaces and tabs }; return line; }; inline HepDouble random_interval ( HepDouble min , HepDouble max ) { return drand48() * (max - min) + min; } inline HepDouble random_interval ( interval iv ) { if ( iv.max > iv.min ) return drand48() * (iv.max - iv.min) + iv.min; else { #ifdef DEBUG if (iv.max < iv.min ) { WARNING("iv.max " + any2str(iv.max) + " < iv.min " + any2str(iv.min)); }; #endif return iv.min; }; } HepDouble StateVector::Phi() { #ifdef DEBUG HepDouble delta=fmod ( _Phi - _phi + _beta, M_2PI); if ( fabs ( delta) > .0000000001 && fabs(delta) < M_2PI-.000000000001 ) { ERROR ("Consistency check failed. delta="+ any2str( delta , 11) + (string) " Phi="+any2str(_Phi)+ (string) " phi="+any2str(_phi)+ (string) " beta="+any2str(_beta)); }; #endif if (!useDelphi) CMS2Delphi(); return _Phi; }; HepDouble StateVector::phi() { if (!useDelphi) CMS2Delphi(); #ifdef DEBUG HepDouble delta=fmod ( _Phi - _phi + _beta, M_2PI); if ( fabs ( delta) > .0000000001 && fabs(delta) < M_2PI-.000000000001 ) { ERROR ("Consistency check failed: delta="+ any2str( delta )+ (string) " Phi="+any2str(_Phi)+ (string) " phi="+any2str(_phi)+ (string) " beta="+any2str(_beta) ); }; #endif return _phi; }; HepDouble StateVector::beta() { if (!useDelphi) CMS2Delphi(); #ifdef DEBUG HepDouble delta=fmod ( _Phi - _phi + _beta, M_2PI); if ( fabs ( delta) > .0000000001 && fabs(delta) < M_2PI-.000000000001 ) { ERROR ("Consistency check failed: delta="+ any2str(delta)+ (string) " Phi="+any2str(_Phi)+ (string) " phi="+any2str(_phi)+ (string) " beta="+any2str(_beta)); }; #endif return _beta; } HepDouble StateVector::kappa() { if (!useDelphi) CMS2Delphi(); return _kappa; } void StateVector::clear () { useDelphi=false; useCMS=false; _Phi=0; _beta=0; _kappa=0; _z=0; _theta=0; _psi=0; _a0=0; _kappa_cms=0; _phi=0; _x=0; _y=0; }; void StateVector::setDelphi ( const HepDouble & a, const HepDouble & b, const HepDouble & c ) { if ( _el.Type() == DIS ) { // a = Phi , b = r _x= b * cos (a); _y= b * sin (a); _phi = c; _Phi= a; _beta= _phi - _Phi; #ifdef DEBUG if ( _Phi < 0 ) { _Phi += M_2PI; WARNING ( "watch your Phi: Phi e [0, 2pi]" ); }; #endif } else { _Phi=a; _beta=b; _kappa=c; _z=0; _theta=0; _phi=_beta + _Phi; #ifdef DEBUG if ( _Phi < 0 ) { _Phi += M_2PI; WARNING ( "watch your Phi: Phi e [0, 2pi]" ); }; #endif }; if (_beta < - M_PI ) _beta += M_2PI; useDelphi=true; useCMS=false; }; void StateVector::setDelphi ( const HepDouble & a, const HepDouble & b, const HepDouble & c, const HepDouble & d, const HepDouble & e ) { if ( _el.Type() == DIS ) { _x=b * cos (a); _y=b * sin (a); _theta=c; _phi=d; _kappa=e; _Phi= a; if ( _Phi < 0 ) { MESSAGE (10, "Phi not element [0, 2pi]. Phi="+ any2str(_Phi)+" beta="+any2str(_beta) +" phi="+any2str(_phi) ); _Phi += M_2PI; }; if ( _phi < 0 ) { MESSAGE (15, "phi not element [0, 2pi]. Phi="+ any2str(_Phi)+" beta="+any2str(_beta) +" phi="+any2str(_phi) ); _phi += M_2PI; }; _beta = _phi - _Phi; } else { _Phi=a; _z=b; _theta=c; _beta=d; _kappa=e; if ( _Phi < 0 ) { MESSAGE (10, "Phi not element [0, 2pi]" ); _Phi += M_2PI; }; /* if ( _phi < 0 ) { _phi += M_2PI; MESSAGE (10, "phi not element [0, 2pi]. Phi="+ any2str(_Phi)+" beta="+any2str(_beta) +" phi="+any2str(_phi) ); }; */ _phi=_beta + _Phi; }; #ifdef DEBUG if (_beta < - M_PI ) { MESSAGE(10,"we just corrected beta."); _beta += M_2PI; }; #endif useDelphi=true; useCMS=false; }; void StateVector::setCMS ( const HepDouble & a0, const HepDouble & z, const HepDouble & theta, const HepDouble & psi,const HepDouble & kappa ) { _psi=psi; _a0=a0; _kappa_cms=kappa; _theta=theta, _z=z; useCMS=true; useDelphi=false; } void StateVector::setCMS ( const HepDouble & a0, const HepDouble & psi, const HepDouble & kappa ) { _psi=psi; _a0=a0; _kappa_cms=kappa; _z=0; _theta=0; useCMS=true; useDelphi=false; } void StateVector::Delphi2CMS () { #ifdef DEBUG if (!useDelphi) { ERROR ("cannot convert StateVector from Delphi to CMS"); exit (-1); }; #endif double PsiPrime; // D=beta+_Phi; PsiPrime=Phi()+beta(); HepDouble Xic = -1 * sin (PsiPrime) / _kappa; HepDouble Yic = cos (PsiPrime) / _kappa; HepDouble Xi = cos ( Phi() ) * R(); HepDouble Yi = sin ( Phi() ) * R(); HepDouble u0 = Xi + Xic; HepDouble v0 = Yi + Yic; HepDouble Rh = 1 / fabs ( kappa() ); HepDouble XY0_norm = norm(u0,v0); HepDouble nX0 = u0 / XY0_norm; // = nR0 HepDouble nY0 = v0 / XY0_norm; // = nR0 HepDouble RVecX = Rh *nX0; HepDouble RVecY = Rh *nY0; HepDouble XVecX = R() * cos ( Phi() ); // XXX HepDouble XVecY = R() * sin ( Phi() ); HepDouble a0VecX = u0 - Rh * nX0; HepDouble a0VecY = v0 - Rh * nY0; HepDouble XVecPrimeX= XVecX - a0VecX; HepDouble XVecPrimeY= XVecY - a0VecY; HepDouble norm_PsiVec = sign( XVecPrimeX * RVecY-XVecPrimeY*RVecX) / norm(RVecX, RVecY); HepDouble nPsiVecX = norm_PsiVec * RVecY; HepDouble nPsiVecY = - norm_PsiVec * RVecX; _psi=atan2(nPsiVecY,nPsiVecX); HepDouble sign_a0 = - sign ( a0VecX * nPsiVecY - a0VecY * nPsiVecX); _a0= sign_a0 * norm(a0VecX,a0VecY); _kappa_cms= - _kappa; useCMS=true; if (_el.Type() == DIS ) { HepDouble diff = fmod ( _phi - _psi + M_PI, M_2PI ) - M_PI; /* HepDouble diff = _phi - _psi; if ( diff < - M_PI ) diff += M_2PI; if ( diff > M_PI ) diff -= M_2PI;*/ _z= _el.Z()+diff * tan ( M_PI_2 - theta() ) / _kappa_cms; }; }; void StateVector::CMS2Delphi ( HepDouble myr ) { #ifdef DEBUG if (!useCMS) { ERROR ("cannot convert StateVector from CMS to Delphi"); exit (-1); }; #endif HepDouble koeff = _a0 - 1 / _kappa_cms; HepDouble Rh= 1 / fabs(_kappa_cms); HepDouble CosDeltaPhi; HepDouble acos_cosdeltaphi, alpha; HepDouble CentrePointx = - koeff * sin( _psi ); HepDouble CentrePointy = koeff * cos( _psi ); CosDeltaPhi = (sqr( Rh ) + sqr(CentrePointx)+sqr(CentrePointy) \ - sqr( myr ) ) / (2 * Rh * norm (CentrePointx,CentrePointy)); if (CosDeltaPhi>=1.) { // an ugly hack: acos(1.) is out of range! WARNING("problem with acos(" + any2str(CosDeltaPhi)+ ")"); acos_cosdeltaphi=0; } else { acos_cosdeltaphi=acos(CosDeltaPhi); }; HepDouble RPrime = sqrt ( 2* sqr(Rh)*(1-CosDeltaPhi)); HepDouble PsiPrime = _psi- sign(_kappa_cms)* acos_cosdeltaphi; alpha=PsiPrime; HepDouble PhiPrime=_psi-0.5*sign(_kappa_cms)*acos_cosdeltaphi; HepDouble xprime=RPrime*cos(PhiPrime); HepDouble yprime=RPrime*sin(PhiPrime); HepVector X = HepVector ( 2, 0); X(1)= -1 * _a0 * sin ( _psi )+ xprime; X(2)= _a0 * cos ( _psi )+ yprime; _x=X(1); _y=X(2); _Phi= atan2(X(2),X(1)); _Phi = _Phi < 0 ? _Phi + M_2PI : _Phi ; _beta= alpha - _Phi; // _beta = fmod ( _beta + M_PI , M_2PI ) - M_PI; _beta = _beta < - M_PI ? _beta + M_2PI : _beta; _phi = _Phi + _beta; // the M_PI part is a lie _kappa= - _kappa_cms; // FIXME is this true? useDelphi=true; } void StateVector::CMS2Delphi () { #ifdef DEBUG if (!useCMS) { ERROR ("cannot convert StateVector from CMS to Delphi"); exit (-1); }; #endif HepDouble myr; HepDouble koeff = _a0 - 1 / _kappa_cms; if ( _el.Type() == CYL ) { myr=R(); } else { HepDouble mphi = _psi + tan ( _theta ) * _kappa_cms * ( _z - _el.Z() ); HepDouble mx = - koeff * sin ( _psi ) - sin ( mphi ) / _kappa_cms; HepDouble my = koeff * cos ( _psi ) + cos ( mphi )/ _kappa_cms; myr = norm ( mx , my ); }; CMS2Delphi ( myr ); } void StateVector::getPlane ( Plane & pl , const DetElement & el, const HepDouble & r ) { #ifdef DEBUG if ( _el.Type() == UNK ) ERROR("5Vector uninitialized where it shouldnt be!"); #endif _el=el; _r=el.R(); // _z=el.Z(); HepDouble mz=pl.z, mtheta=pl.theta; setCMS ( pl.a0(), pl.psi(), pl.kappa() ); CMS2Delphi ( r ); HepDouble diff = fmod ( _phi - _psi + M_PI, M_2PI ) - M_PI; mz= mz+diff * tan ( M_PI_2 - mtheta ) / pl.kappa(); setCMS ( pl.a0(), mz, mtheta, pl.psi(), pl.kappa() ); CMS2Delphi(); }; void StateVector::getPlane ( Plane & pl ,const DetElement & el ) { #ifdef DEBUG if ( _el.Type() == UNK ) ERROR("5Vector uninitialized where it shouldnt be!"); #endif _el=el; _r=el.R(); // _z=el.Z(); setCMS ( pl.a0(), pl.z, pl.theta, pl.psi(), pl.kappa() ); CMS2Delphi(); }; HepDouble StateVector::pr() { return fabs ( CNV * _el.Bz() / kappa() / sin (theta())); }; // ----------------< write routines >---------- void StateVector::write_raw () { cout << "SV" << _el.TypeName() << short_id << " " << DelphiValues(8); }; void StateVector::write_raw (char *file ) { if (!strcmp(file,"")) { StateVector::write_raw(); // hm. How can we merge the two? } else { static ofstream fout(file,ios::app); fout << "SV" << _el.TypeName() << short_id << " " << DelphiValues(8); }; }; void StateVector::write() { writeDelphi(); }; void StateVector::writeDelphi() { cout << identifier << " (Delphi):"; if (_el.Type()==CYL) { cout << " Element #" << _el.num << " el.R()=" << R() << endl << " Phi=" << setprecision(9) << C_GREEN << Phi() << C_DEFAULT << " z=" << C_GREEN << z() << C_DEFAULT << " theta=" << C_GREEN << theta() << C_DEFAULT << " beta=" << C_GREEN << beta() << C_DEFAULT << " kappa=" << C_GREEN << kappa() << C_DEFAULT << endl; } else { cout << " Element #" << _el.num << " el.Z()=" << _el.Z() << endl << setprecision(9) << " Phi=" << C_GREEN << Phi() << C_DEFAULT << " R=" << C_GREEN << R() << C_DEFAULT << " theta=" << C_GREEN << theta() << C_DEFAULT << " phi=" << C_GREEN << phi() << C_DEFAULT << " kappa=" << C_GREEN << kappa() << C_DEFAULT << endl; #ifdef DEBUG if (_el.Type()==CYL) WARNING ("this phi should only occur with DIS coordinates."); #endif }; }; void StateVector::writeCMS() { cout << identifier << " (CMS):" << " Element #" << _el.num; if ( _el.Type() == CYL ) { cout << " el.R()=" << _el.R() << endl; } else { cout << " el.Z()=" << _el.Z() << endl; }; cout << " a0=" << C_GREEN << a0() << C_DEFAULT << " z=" << C_GREEN << z() << C_DEFAULT << " theta=" << C_GREEN << theta() << C_DEFAULT << " psi=" << C_GREEN << psi() << C_DEFAULT << " kappa_cms=" << C_GREEN << kappa_cms() << C_DEFAULT << endl; }; HepVector StateVector::Delphi() { HepVector d(5,0); if (_el.Type()==CYL) { d(1)=Phi(); d(2)=z(); d(3)=theta(); d(4)=beta(); d(5)=kappa(); } else { d(1)=Phi(); d(2)=R(); d(3)=theta(); d(4)=phi(); d(5)=kappa(); }; return d; }; // scatter deterministically, if det == true void StateVector::Scatter ( bool det ) { if (!det) { Scatter(); return; }; HepDouble Bz=_el.Bz(); /// \bug Again, ashamed and embarrassed I specify to B={0,0,Bz} HepDouble pT, p, X, sigms_sim; // , randa,randb; pT= CNV * Bz / _kappa; p= pT / sin( _theta ) ; X= eff_thick(); // _el.Thick() / sin ( _theta ); sigms_sim=0.015 / fabs (p) * sqrt (X) * ( 1+.038 * log (X)); HepDouble ran1=sigms_sim; HepDouble ran2=sigms_sim / sin ( _theta); _theta=_theta+ran1; if ( _el.Type() == CYL ) { _beta += ran2; _phi = _beta + _Phi; } else { _phi += ran2; _beta = _phi - _Phi; // unneccessary? }; pT=p*sin(_theta); _kappa=CNV * Bz / pT; }; void StateVector::Scatter ( ) { HepDouble Bz=_el.Bz(); HepDouble pT, p, X, sigms_sim; // , randa,randb; pT= CNV * Bz / _kappa; p= pT / sin( _theta ) ; X= eff_thick(); // _el.Thick() / sin ( _theta ); sigms_sim=0.015 / fabs ( p ) * sqrt (X) * ( 1+.038 * log (X)); HepDouble ran1 = RandGauss::shoot(0,sigms_sim); HepDouble ran2 = RandGauss::shoot(0,sigms_sim / sin (_theta)); _theta=_theta+ran1; if ( _el.Type() == CYL ) { _beta += ran2; _phi = _beta + _Phi; } else { _phi += ran2; _beta = _phi - _Phi; // unneccessary? }; pT=p*sin(_theta); _kappa=CNV * Bz / pT; }; StateVector StateVector::Propagate ( const DetElement & nxt , bool Drvtvs ) { switch (_el.Type()) { case CYL: return PropagateCyl ( nxt, Drvtvs ); case DIS: return PropagateDis ( nxt, Drvtvs ); default: ERROR("dunno what kinda element this is."); }; exit (-1); }; string StateVector::DelphiValues() { return DelphiValues ( 7 ); }; string StateVector::CMSValues() { return CMSValues ( 7 ); }; string StateVector::DelphiValues( char pre ) { char line[80]; if ( Element().Type() == CYL ) { snprintf(line,80,"%.*e %.*e %.*e %.*e %.*e\n",pre,Phi() ,pre,z(),pre, theta(),pre, beta(),pre, kappa()); } else { snprintf(line,80,"%.*e %.*e %.*e %.*e %.*e\n",pre,Phi() ,pre,R(),pre, theta(),pre, phi(),pre, kappa()); }; return line; }; string StateVector::CMSValues( char pre ) { char line[80]; snprintf(line,80,"%.*e %.*e %.*e %.*e %.*e\n",pre,a0() ,pre,z(),pre, theta(),pre, psi(),pre, kappa_cms()); return line; }; string StateVector::DelphiValues( StateVector tv) { char line[80]; if ( Element().Type() == CYL ) { snprintf(line,80,"%.7e %.7e %.7e %.7e %.7e\n",Phi()-tv.Phi() ,z()-tv.z(), theta()-tv.theta(), beta()-tv.beta(), kappa()-tv.kappa() ); } else { snprintf(line,80,"%.7e %.7e %.7e %.7e %.7e\n",Phi()-tv.Phi() ,R()-tv.R(), theta()-tv.theta(), phi()-tv.phi(), kappa()-tv.kappa() ); }; return line; }; string StateVector::CMSValues( StateVector tv) { char line[80]; snprintf(line,80,"%.7e %.7e %.7e %.7e %.7e\n",a0()-tv.a0() ,z()-tv.z(), theta()-tv.theta(), psi()-tv.psi(), kappa_cms()-tv.kappa_cms() ); return line; }; HepDouble StateVector::R() const { if ( _el.Type() == CYL ) { return _r; } else { return norm(_x,_y); }; }; void StateVector::unwrapPhi( StateVector *prev ) { if ( prev->Phi() - _Phi > M_PI ) _Phi += M_2PI; if ( _Phi - prev->Phi() > M_PI ) _Phi -= M_2PI; if ( prev->phi() - _phi > M_PI ) _phi += M_2PI; if ( _phi - prev->phi() > M_PI ) _phi -= M_2PI; if ( prev->beta() - _beta > M_PI ) _beta += M_2PI; if ( _beta - prev->beta() > M_PI ) _beta -= M_2PI; } StateVector StateVector::PropagateDis ( const DetElement & nxt , bool Drvtvs ) ///< Propagates a StateVector { #ifdef DEBUG if (!useDelphi) { // this one is based on Delphi coordinates. CMS2Delphi(); WARNING("Oops! we need to convert here! Change the code."); }; #endif StateVector _neu; #ifdef DEBUG if (nxt.Type()==UNK || nxt.Type()==NON) { // we cannot propagate any further. ERROR ("could not determine next detector element.\n element #" + any2str(_el.num) + " type " + _el.TypeName()); return _neu; }; HepDouble rmin=-200, rmax=200; #endif HepDouble dphimn=pow(10,-4); HepDouble dz=nxt.Z()-_el.Z(); HepDouble tanth=tan(theta()); HepDouble rdphi=dz*tanth; HepDouble rtrk= 1 / kappa(); HepDouble cosf0 = cos ( phi() ); HepDouble sinf0 = sin ( phi() ); HepDouble xc=x()-rtrk*sinf0; HepDouble yc=y()+rtrk*cosf0; HepDouble dphi=kappa()*rdphi; HepDouble phi1=fmod (phi()+dphi, M_2PI ); HepDouble cosf1=cos(phi1); HepDouble sinf1=sin(phi1); HepDouble x1=xc+rtrk*sinf1; HepDouble y1=yc-rtrk*cosf1; #ifdef DEBUG HepDouble r1=norm ( x1,y1); if (r1 < rmin || r1 > rmax) { ERROR("Did not intersect: " + any2str(rmin) + " " + any2str(r1) + " " + any2str(rmax)); exit (-1); }; #endif _neu=StateVector( nxt ); _neu._x = x1; _neu._y = y1; _neu._theta = theta(); _neu._phi = phi1; if (phi1 < 0. ) _neu._phi += M_2PI; _neu._Phi = myatan ( y1 , x1); if (_neu._Phi < 0 ) _neu._Phi += M_2PI; _neu._beta = phi1 - _neu._Phi; _neu._kappa = kappa(); if (Drvtvs) { // ---------- computation of derivatives ----------- _neu._Deriv=HepMatrix(5,5,1); HepDouble ct2inv=1.+sqr(tanth); _neu._Deriv(1,3)=ct2inv*dz*cosf1; _neu._Deriv(2,3)=ct2inv*dz*sinf1; _neu._Deriv(4,3)=dz*kappa()*ct2inv; _neu._Deriv(4,5)=rdphi; if ( fabs(dphi) >= dphimn ) { HepDouble dcosf=cosf1-cosf0; HepDouble dsinf=sinf1-sinf0; _neu._Deriv(1,4)=rtrk*dcosf; _neu._Deriv(1,5)=sqr(rtrk)*(dphi*cosf1-dsinf); _neu._Deriv(2,4)=rtrk*dsinf; _neu._Deriv(2,5)=sqr(rtrk)*(dphi*sinf1+dcosf); } else { _neu._Deriv(1,4)=-rdphi*sinf0; _neu._Deriv(1,5)=.5*rdphi*_neu._Deriv(1,4); _neu._Deriv(2,4)=rdphi*cosf0; _neu._Deriv(2,5)=.5*rdphi*_neu._Deriv(2,4); }; // transform to Phi, R. // FIXME optimize it? HepMatrix Ti ( 5,5,1), Tf (5,5,1); Ti(1,1)=-R() * sin (Phi()); Ti(2,2)= sin (Phi() ); Ti(1,2)= cos ( Phi() ); Ti(2,1)= R() * cos ( Phi()); Tf(1,1)=- sin (_neu.Phi()) / _neu.R(); Tf(2,2)= sin ( _neu.Phi() ); Tf(1,2)= cos ( _neu.Phi() ) / _neu.R(); Tf(2,1)= cos ( _neu.Phi()); _neu._Deriv = Tf * _neu._Deriv * Ti; _neu._Der=_neu._Deriv * _Der; // chain rule }; _neu.useDelphi=true; _neu.useCMS=false; #ifdef GL _neu.Delphi2CMS(); _neu.identifier="Propagated StateVector"; _neu.short_id="PS"; #endif // _neu.unwrapPhi ( this ); return _neu; }; StateVector StateVector::PropagateCyl ( const DetElement & nxt , bool Drvtvs ) ///< Propagates a StateVector { // this one is based on Delphi coordinates. #ifdef DEBUG if (!useDelphi) { CMS2Delphi(); WARNING("oops! we needa convert here!"); }; #endif // default values #ifdef DEBUG HepDouble sinbmx=0.9, zmin= -200, zmax = 200; #endif // end default values // HepDouble dphimn=pow(10,-4); HepDouble cosb, sinb, cotth, rtrk, xc, yc, rc2, rrr, delt; HepDouble phif, zf, xf, yf, tth, alff, dr2, rcosb, radi, phii, radf; HepDouble dphi, alrphi, pph, sinf, cosf, sinbf, dcosf, aa, dsinf, rdphi; StateVector _neu; #ifdef DEBUG if (nxt.Type()==UNK || nxt.Type()==NON) { // we cannot propagate any further. ERROR ("could not determine next detector element.\n element #" + any2str(_el.num) + " type " + _el.TypeName()); return _neu; }; #endif _neu=StateVector( nxt ); cosb= cos(_beta); sinb= sin(_beta); cotth=(1/tan(_theta)); rtrk= 1/ _kappa; // FIXME we dont need this one phii= _Phi; radf=_neu.R(); radi = _el.R(); xc=radi-rtrk*sinb; yc=rtrk*cosb; rc2=pow(xc,2)+pow(yc,2); rrr=(pow(radf,2)-pow(rtrk,2)-rc2) / ( 2 * rtrk ); delt = rc2 - pow(rrr,2); #ifdef DEBUG if (delt <=0 ) { ERROR("did not intersect. delt = " + any2str(delt) + "< 0"); exit (-1); }; #endif delt=sqrt(delt); sinf=(xc*rrr+yc*delt)/rc2; cosf=(xc*delt-yc*rrr)/rc2; xf=xc+rtrk*sinf; yf=yc-rtrk*cosf; sinbf=(sinf*xf-cosf*yf)/radf; #ifdef DEBUG if ( fabs ( sinbf) > sinbmx ) { // FIXME is this ok? ERROR("Beta too large"); exit (-1); }; #endif alff=atan2(sinf,cosf); dphi=alff-_beta; alrphi=rtrk*dphi; if ( fabs( dphi )>=dphimn ) { // FIXME is this ok? zf=_z+cotth*rtrk*dphi; tth= M_PI / 2 - atan (zf / radf); phif=atan2 (yf, xf); pph=phif; if ( pph < 0 ) {pph=pph+ M_2PI;}; #ifdef DEBUG if (zf < zmin || zf > zmax ) { ERROR("z not in the given interval (z=" + any2str(zf) + " zmin,zmax=" + any2str(zmin)+ ", " + any2str(zmax)+")"); exit (-1); }; #endif _neu._Phi = fmod(phii + phif + M_2PI, M_2PI); _neu._z = zf; _neu._theta = _theta; _neu._beta = alff-phif; _neu._kappa = _kappa; _neu._phi = _neu._Phi + _neu._beta; if (Drvtvs) { // ---------- computation of derivatives ----------- _neu._Deriv=HepMatrix(5,5,1); // for (int i=1;i<6; i++) {_neu._Deriv(i,i)=1;}; HepDouble cosbf = sqrt(1-sqr(sinbf)); HepDouble ccpsi = radi- rtrk * sinb; HepDouble scpsi = rtrk * cosb; HepDouble ccpsf = radf-rtrk*sinbf; // HepDouble scpsf = rtrk*cosbf; HepDouble cpsii = rtrk- radi*sinb; HepDouble spsii = -radi*cosb; HepDouble cpsif = rtrk - radf * sinbf; HepDouble spsif = -radf * cosbf; HepDouble sdphi = sin ( dphi ); HepDouble cdphi = cos ( dphi ); HepDouble fact = - rtrk / spsif; _neu._Deriv(1,4)=sdphi*fact; _neu._Deriv(1,5)=fact*rtrk*(1-cdphi); _neu._Deriv(2,3)=-rtrk*dphi*(1+sqr(cotth)); _neu._Deriv(2,4)=rtrk*cotth*(radf*ccpsf*spsii/spsif-radi*ccpsi)/rc2; _neu._Deriv(2,5)=sqr(rtrk)*cotth*(-dphi+sinbf/cosbf- \ (radi*scpsi+radf*ccpsf*cpsii/spsif)/rc2); _neu._Deriv(4,4)=spsii/spsif; _neu._Deriv(4,5)=rtrk*(cpsif-cpsii)/spsif; _neu._Der=_neu._Deriv * _Der; // chain rule }; } else { dr2=pow(radf,2)-pow(radi,2); rcosb=radi*cosb; aa=1-radi*sinb/rtrk; delt=pow(rcosb,2)+aa*dr2; #ifdef DEBUG if (delt<=0) { ERROR("rcsob=" + any2str(rcosb) + " _neu-r=" + any2str(_neu.R())+ " r=" + any2str(_r)+ " aa=" + any2str(aa) + " dr2=" + any2str(dr2) + "did not intersect. delt = " + any2str(delt)+ "< 0"); return StateVector(); }; #endif rdphi=(sqrt(delt)-rcosb)/aa; dphi=rdphi/rtrk; dcosf= - sinb - .5 *cosb*dphi; cosf=cosb+dcosf*dphi; yf=-rdphi*dcosf; dsinf=cosb-.5*sinb*dphi; sinf=sinb+dsinf*dphi; xf=radi+rdphi*dsinf; sinbf=(sinf*xf-cosf*yf)/radf; zf=_z+cotth*rdphi; tth=M_PI_2-atan(zf/radf); phif=atan2(yf,xf); pph=phif; if (pph < 0) { pph=pph + M_2PI;}; #ifdef DEBUG if (zf < zmin || zf > zmax ) { ERROR("z not in the given interval (z=" + any2str(zf) + " zmin,zmax=" + any2str(zmin) + ", " + any2str(zmax)+")"); exit (-1); }; #endif phif = atan2(yf,xf); _neu._Phi = fmod ( _Phi + phif + M_2PI, M_2PI ); _neu._z = zf; _neu._theta = _theta; _neu._beta = _beta+dphi-phif; _neu._kappa = _kappa; _neu._phi = _neu._Phi + _neu._beta; if (Drvtvs) { // ------------- computation of derivatives --------- //_neu._Deriv=HepMatrix(5,5,1); whiy not? for (int i=1;i<6; i++) {_neu._Deriv(i,i)=1;}; HepDouble cosbf = sqrt(1-sqr(sinbf)); HepDouble sphif = yf / radf; _neu._Deriv(1,4) = rdphi / ( radf * cosbf ); _neu._Deriv(1,5)=.5*rdphi*_Deriv(1,4); _neu._Deriv(2,3)=-rdphi*(1.+sqr(cotth)); _neu._Deriv(2,4)=radi*cotth*sphif/cosbf; _neu._Deriv(2,5)=.5*rdphi*_Deriv(2,4); _neu._Deriv(4,4)=(radi*cosb)/(radf*cosbf); _neu._Deriv(4,5)=.5*rdphi*(1.+_Deriv(4,4)); _neu._Der=_neu._Deriv * _Der; // chain rule }; }; _neu.useDelphi=true; _neu.useCMS=false; #ifdef GL _neu.Delphi2CMS(); _neu.identifier="Propagated StateVector"; _neu.short_id="PS"; #endif return _neu; }; StateVector::StateVector() { _Phi=0; _theta=0; _beta=0; _kappa=0; _z=0; _r=0; _a0=0; _psi=0; _kappa_cms=0; _phi=0; useCMS=false; useDelphi=false; _Deriv=HepSymMatrix(5,0); _Der=HepSymMatrix(5,1); #ifdef GL identifier="zero StateVector"; short_id="0"; #endif }; HepDouble StateVector::eff_thick() { /* HepDouble coeff; if (_el.Type() == CYL ) { coeff = 1 / sin(theta()); } else { coeff = 1 / cos(theta()); }; return _el.Thick() * coeff; */ if (_el.Type() == CYL ) { return _el.Thick() / sin(theta()); } else { return _el.Thick() / cos(theta()); }; }; #ifdef GL string StateVector::getInfo ( int what ) { switch (what) { case 0: // CMS case 1: case 2: case 4: // all cms return identifierCMS(); case 3: // delphi return identifierDelphi(); case 99: return identifierCMS(); default: return "error"; }; }; string getsvInfo (int a) { if (hlx_shows < 5) return sv_list[a].getInfo(hlx_shows); }; void StateVector::drawonDis ( SoSelection *root , string idnt, HepDouble lngth ) { SoHelicalTrack *newHelix = new SoHelicalTrack; if (!(psi()<M_2PI) || !(theta() < M_2PI) ) { // FIXME I actually wanted an (SoText3) question mark here, // but this did not work on the Red (Dread) Hat 6.1/6.2 newHelix->inverseRadius= 0; newHelix->phi0=M_PI; newHelix->z0=0; newHelix->d0=0; newHelix->cotTheta= 0; newHelix->s1=lngth; sv_list.push_back(*this); identifier=idnt+" !illegal!!"; addChild ( root, newHelix , (getsvInfo) , sv_list.size()-1 , true ); } else { newHelix->inverseRadius= 1 / Radius(); newHelix->phi0= psi(); // -M_PI; HepDouble diff=phi()-psi() ; if (diff > M_PI ) diff -= M_2PI; if (diff < - M_PI ) diff += M_2PI; newHelix->z0= _el.Z() + diff * tan ( M_PI_2 - theta() ) / kappa_cms (); newHelix->d0= - a0(); newHelix->cotTheta= Z_SCALE / tan(theta()); // yes, scaling is that easy newHelix->s1=lngth; sv_list.push_back(*this); identifier=idnt; short_id=idnt; addChild ( root, newHelix , (getsvInfo) , sv_list.size()-1 , true ); }; }; void StateVector::drawonCyl ( SoSelection *root , string idnt, HepDouble lngth ) { SoHelicalTrack *newHelix = new SoHelicalTrack; if (!(psi()<M_2PI) || !(theta() < M_2PI) ) { // FIXME I actually wanted an (SoText3) question mark here, // but this did not work on the Red (Dread) Hat 6.1/6.2 newHelix->inverseRadius= 0; newHelix->phi0=0; newHelix->z0=0; newHelix->d0=0; newHelix->cotTheta= 0; newHelix->s1=lngth; sv_list.push_back(*this); identifier=idnt+" !illegal!!"; addChild ( root, newHelix , (getsvInfo) , sv_list.size()-1 , true ); } else { newHelix->inverseRadius= 1 / Radius(); newHelix->phi0=psi() - M_PI; // the tan theta is the correction for teh difference z(R=0) // and z(R=R(DetEl1)) // FIXME sometime we should implement a // FullVector sitting at R=0 newHelix->z0= (z() - _el.R() / tan(theta())) * Z_SCALE; newHelix->d0=a0(); newHelix->cotTheta= Z_SCALE / tan(theta()); // yes, scaling is that easy newHelix->s1=lngth; sv_list.push_back(*this); identifier=idnt; short_id=idnt; addChild ( root, newHelix , (getsvInfo) , sv_list.size()-1 , true ); }; }; void StateVector::GLdraw ( SoSelection *root ,HepDouble r, HepDouble g,\ HepDouble b, HepDouble lngth ) { GLinitMaterial ( root, r , g , b ); if ( _el.Type() == CYL ) { drawonCyl ( root , "Track.", lngth ); } else { drawonDis ( root , "Track.", lngth ); }; }; void StateVector::GLdraw ( SoSelection *root , HepDouble lngth ) { // GLinitMaterial ( root ); if ( _el.Type() == CYL ) { drawonCyl ( root , "Track.", lngth ); } else { drawonDis ( root , "Track.", lngth ); }; }; void StateVector::GLdraw ( SoSelection *root , const string & idn , HepDouble r, \ HepDouble g, HepDouble b , HepDouble lngth ) { GLinitMaterial ( root, r , g , b ); if ( _el.Type() == CYL ) { drawonCyl ( root , idn, lngth ); } else { drawonDis ( root , idn, lngth ); }; }; void StateVector::GLdraw ( SoSelection *root , const string & idn , HepDouble lngth ) { // GLinitMaterial ( root ); if ( _el.Type() == CYL ) { drawonCyl ( root , idn, lngth ); } else { drawonDis ( root , idn, lngth ); }; }; void StateVector::GLinitMaterial ( SoSelection *root ) const { SoMaterial *myMaterial = new SoMaterial; myMaterial->diffuseColor.setValue(0.2, 0.3, 0.7); myMaterial->emissiveColor.setValue(0.2, 0.3, 0.7); addChild(root,myMaterial); }; void StateVector::GLinitMaterial ( SoSelection *root, HepDouble red, \ HepDouble green , HepDouble blue ) const { SoMaterial *myMaterial = new SoMaterial; myMaterial->diffuseColor.setValue ( red, green, blue ); myMaterial->emissiveColor.setValue( red, green, blue ); addChild(root,myMaterial); }; #endif StateVector::StateVector ( const DetElement & el, const HepDouble & Phi , const HepDouble & z , const HepDouble & theta, const HepDouble & beta, const HepDouble & kappa ) { _el=el; _a0=0; _psi=0; if ( _el.Type() == CYL ) { _r=_el.R(); _Phi=Phi; _theta=theta; _beta=beta; _kappa=kappa; _z=z; _phi=_Phi+_beta; } else { ERROR ("not implemented"); }; _kappa_cms=0; useCMS=false; useDelphi=true; _Deriv=HepSymMatrix(5,0); _Der=HepSymMatrix(5,1); #ifdef GL identifier="'initialized' StateVector"; short_id="0"; #endif }; StateVector::StateVector( const DetElement & elm ) { _el=elm; // _s=0; if (_el.Type() == DIS) { _r=0; _z=_el.Z(); } else { _r=_el.R(); _z=0; }; _Phi=0; _theta=0; _beta=0; _kappa=0; _kappa_cms=0; _phi=0; _a0=0; _psi=0; useCMS=false; useDelphi=true; _Deriv=HepSymMatrix(5,0); _Der=HepSymMatrix(5,1); #ifdef GL identifier="zero StateVector on DetEl"; short_id="0"; #endif }; HepVector StateVector::XY0() { // coc: center of circle // wrong // return R()*cos(Phi()) - 1/ kappa() * sin (beta() + Phi()) HepDouble r=_el.R(); // FIXME HepVector ret= HepVector ( 2, 0); HepDouble Rh = 1 / fabs ( kappa() ); HepDouble CentreX = ( - a0() + 1 / kappa() ) * sin(psi()); HepDouble CentreY = ( a0() - 1 / kappa() ) * cos (psi()); HepDouble CosDeltaPhi = ( sqr(Rh)+sqr(CentreX) + sqr(CentreY) - sqr(r)) / \ (2 * Rh * norm (CentreX, CentreY)); HepDouble RPrime = sqrt ( 2*sqr(Rh)*(1-CosDeltaPhi)); HepDouble PhiPrime=psi()-0.5*sign(kappa()) * acos(CosDeltaPhi); HepDouble xprime = RPrime * cos (PhiPrime); HepDouble yprime = RPrime * sin (PhiPrime); ret(1)= -1 * a0() * sin (psi() )+ xprime; ret(2)= a0() * cos ( psi() )+ yprime; return ret; }; HepDouble StateVector::a0() { if (!(useCMS)) Delphi2CMS(); return _a0; }; HepDouble StateVector::psi() { if (!(useCMS)) Delphi2CMS(); return _psi; }; HepDouble StateVector::kappa_cms() { if (!(useCMS)) Delphi2CMS(); return _kappa_cms; }; void StateVector::writeParam() { if ( _el.Type() == CYL ) { cout << Phi() << " " << z() << " " << theta() << " " << beta() << " " << kappa() << endl; } else { cout << Phi() << " " << R() << " " << theta() << " " << phi() << " " << kappa() << endl; }; }; HepDouble StateVector::Radius() const { if (useDelphi) { return 1 / _kappa; } else if (useCMS) { return 1 / fabs (_kappa_cms); }; ERROR("cannot determine which coordinate system is used here."); exit (-1); }; void StateVector::Randomize( interval a, interval b, interval c, interval d, interval e ) { /* #ifdef DEBUG assert ( a.min>0 ); #endif */ HepDouble B=_el.Bz(); HepDouble pT = random_interval ( a ); // GeV #ifdef GL // char name[109]; identifier="Randomized StateVector"; short_id="RS"; #endif if ( _el.Type() == DIS ) { /* * Randomize disc */ _phi=random_interval( c ); if (_phi < 0) _Phi+=_Phi; _theta=random_interval ( b ); _x=random_interval ( d ); _y=random_interval ( e ); _Phi = myatan ( _y , _x ); _kappa=CNV * B / pT; // / sin ( _theta ); if (_Phi < 0) _Phi+=_Phi; _beta= fmod ( _phi - _Phi + M_PI_2 , M_2PI ) - M_PI_2; // okay. this is a little different here. we // have to propagate now to the first element. // (above values are for z=0) DetElement dummy_el ( DIS , 0 , 0 , 0 , 0 ); StateVector sv ( dummy_el ); sv.setDelphi ( Phi() , R() , theta() , phi() , kappa() ); StateVector nv=sv.PropagateDis ( Element(), false ); // now take nv values as initial values. _x= nv.x() ; _y= nv.y(); _theta=nv.theta(); _phi=nv.phi(); _Phi = nv.Phi(); _beta= _phi - _Phi; _kappa=nv.kappa(); if ( _Phi < 0 ) _Phi += M_2PI; if ( _Phi > M_2PI ) _Phi -= M_2PI; _beta= fmod ( _phi - _Phi + M_PI_2 , M_2PI ) - M_PI_2; _kappa=CNV * B / pT; // / sin (_theta ); } else { /* * Randomize Cylinder */ // FIXME this is currently specific to Br=0, Bphi=0 // _Phi= random_interval ( c ); _theta=random_interval ( b ); _z = random_interval ( d ); _beta= random_interval ( e ); // is this good? _kappa = CNV * B / pT; // / sin ( _theta ); _phi=_beta+_Phi; // _z = 0; _Phi=3; _theta=1; }; // HepDouble eps = pow(10,-15); // precision of the calculations useDelphi=true; useCMS=false; MESSAGE(10,"[random] Random TrueVector generated.\n '-> "+DelphiFixedString()); }; void StateVector::Randomize( const string & filename ) { if (filename == "") { MESSAGE(5,"[random] Using the hard coded intervals. Fix this."); Randomize(); return; }; static bool ronce=false; if (!ronce) { MESSAGE(5,"[random] intervals: "+filename); ronce=true; }; ifstream fin(filename.c_str()); if (!fin) file_not_found(filename); char word[MLC]; string line; string nxtword, min_val, max_val; HepDouble mmin, mmax; interval a,b,c,d,e; a.min=0; a.max=0; b.min=0; b.max=0; c.min=0; c.max=0; d.min=0; d.max=0; e.min=0; e.max=0; /// get the description from the file. /// parse init file!! while (fin.getline(word,MLC)) { line=word; line=del_leading_spaces(line); line=line.substr(0,line.find("#")); // delete comments nxtword=line.substr(0,line.find(" ")); min_val=""; if (nxtword.size()) { line=del_leading_spaces(line); line.erase(0,line.find_first_of(" ")+1); line=del_leading_spaces(line); min_val=line.substr(0,line.find(" ")); max_val=min_val; if (min_val.size()) { line=del_leading_spaces(line); line.erase(0,line.find_first_of(" ")+1); line=del_leading_spaces(line); max_val=line.substr(0,line.find(" ")); max_val=del_leading_spaces(max_val); if (max_val=="") max_val=min_val; }; mmin=atof(min_val.c_str()); mmax=atof(max_val.c_str()); if (nxtword == "p" ) { ERROR("we dont use p anymore. Use pT!"); a.min=mmin; a.max=mmax; } else if (nxtword == "pT" ) { a.min=mmin; a.max=mmax; } else if (nxtword == "theta" ) { b.min=mmin; b.max=mmax; } else if (nxtword == "phi" && Element().Type()==DIS ) { c.min=mmin; c.max=mmax; } else if (nxtword == "x" && Element().Type()==DIS ) { d.min=mmin; d.max=mmax; } else if (nxtword == "y" && Element().Type()==DIS ) { e.min=mmin; e.max=mmax; } else if (nxtword == "Phi" && Element().Type()==CYL ) { c.min=mmin; c.max=mmax; } else if (nxtword == "z" && Element().Type()==CYL ) { d.min=mmin; d.max=mmax; } else if (nxtword == "beta" && Element().Type()==CYL ) { e.min=mmin; e.max=mmax; } else { ERROR("unknown argument in init file"); }; }; }; Randomize( a, b, c, d, e); } void StateVector::Randomize( ) { interval p, theta; p.min=1.5; p.max=p.min; if ( _el.Type() == DIS ) { interval phi, x, y; phi.min=M_PI_4; phi.max=phi.min; theta.min=.5; theta.max=theta.min; x.min=.02; x.max=x.min; y.min=.01; y.max=y.min; Randomize ( p , theta, phi, x , y ); } else { interval Phi, z, beta; Phi.min=3; Phi.max=3; theta.min=1; theta.max=1; z.min=0; z.max=0; beta.min = 0; beta.max = 0; Randomize ( p , theta, Phi, z , beta ); }; }; HepDouble StateVector::zVth_fak() const { if ( Element().Type() == CYL ) { return pow ( sin ( theta() ) , -4); } else { return pow ( cos ( theta() ) , -4); }; }; string StateVector::DelphiFixedString() { char out[255]; if ( _el.Type()==CYL ) { snprintf(out,255,"Phi=%.4f z=%.4f theta=%.4f beta=%.4f kappa=%.4f", Phi(), z(), theta(), beta(), kappa() ); } else { snprintf(out,255,"Phi=%.4f R=%.4f theta=%.4f phi=%.4f kappa=%.4f", Phi(), R(), theta(), phi(), kappa() ); }; return (string) out; }; #ifdef GL string StateVector::DelphiString() { char out[255]; if ( _el.Type()==CYL ) { snprintf(out,255,"Phi=%.*f z=%.*f theta=%.*f beta=%.*f kappa=%.*f", matrix_prec+3, Phi(), matrix_prec+3, z(), matrix_prec+3, theta(), matrix_prec+3, beta(), matrix_prec+3, kappa() ); } else { snprintf(out,255,"Phi=%.*f R=%.*f theta=%.*f phi=%.*f kappa=%.*f", matrix_prec+3, Phi(), matrix_prec+3, R(), matrix_prec+3, theta(), matrix_prec+3, phi(), matrix_prec+3, kappa() ); }; return (string) out; }; string StateVector::CMSString() { char out[255]; snprintf(out,255,"a0=%.*f z=%.*f theta=%.*f psi=%.*f kappa=%.*f", matrix_prec+3, a0(), matrix_prec+3, z(), matrix_prec+3, theta(), matrix_prec+3, psi(), matrix_prec+3, kappa()); return (string) out; }; string StateVector::DelphiShortString() { char out[255]; if ( _el.Type()==CYL ) { snprintf(out,255,"%.*f %.*f %.*f %.*f %.*f", matrix_prec+3, Phi(), matrix_prec+3, z(), matrix_prec+3, theta(), matrix_prec+3, beta(), matrix_prec+3, kappa() ); } else { snprintf(out,255,"%.*f %.*f %.*f %.*f %.*f", matrix_prec+3, Phi(), matrix_prec+3, R(), matrix_prec+3, theta(), matrix_prec+3, phi(), matrix_prec+3, kappa() ); }; return (string) out; }; string StateVector::identifierDelphi() { return identifier+" (Delphi)\n "+DelphiString(); }; string StateVector::identifierCMS() { return identifier+" (CMS)\n "+CMSString(); }; string StateVector::identifierDeriv() { return any2str ( identifier + " (Deriv, Delphi)\n Der=", _Deriv , matrix_prec+3 ); }; string StateVector::identifierDer() { return any2str ( identifier + " (Der, Delphi)\n Der=", _Der, matrix_prec+3 ); }; string StateVector::CMSShortString() { char out[255]; snprintf(out,255,"%.*f %.*f %.*f %.*f %.*f", matrix_prec+3, a0(), matrix_prec+3, z(), matrix_prec+3, theta(), matrix_prec+3, psi(), matrix_prec+3, kappa()); return (string) out; }; #endif
26.475177
87
0.603134
[ "vector", "transform" ]
b96c5a608d356f15a4d9f143a37fe59cafc85621
4,057
cc
C++
src/algs/ags/local_optimizer.cc
bowie7070/nlopt
95df031058531d84fe9c0727458129f773d22959
[ "MIT-0", "MIT" ]
1,224
2015-01-14T22:56:04.000Z
2022-03-30T18:52:57.000Z
nlopt/src/algs/ags/local_optimizer.cc
yjjuan/automl_cplusplus
7c427584ed94915b549d31a2097f952c3cfdef36
[ "Apache-2.0" ]
349
2015-01-16T22:22:32.000Z
2022-03-29T18:30:05.000Z
nlopt/src/algs/ags/local_optimizer.cc
yjjuan/automl_cplusplus
7c427584ed94915b549d31a2097f952c3cfdef36
[ "Apache-2.0" ]
437
2015-02-20T07:40:41.000Z
2022-03-30T15:21:01.000Z
/* Copyright (C) 2018 Sovrasov V. - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license. * You should have received a copy of the MIT license with * this file. If not visit https://opensource.org/licenses/MIT */ #include "local_optimizer.hpp" #include <cmath> #include <algorithm> #include <limits> using namespace ags; #define MAX_LOCAL_ITERATIONS_NUMBER 20 void HookeJeevesOptimizer::SetParameters(double eps, double step, double stepMult) { NLP_SOLVER_ASSERT(eps > 0 && step > 0 && stepMult > 0, "Wrong papameters of the local optimizer"); mEps = eps; mStep = step; mStepMultiplier = stepMult; } Trial HookeJeevesOptimizer::Optimize(std::shared_ptr<IGOProblem<double>> problem, const Trial& startPoint, std::vector<unsigned>& trialsCounters) { mProblem = problem; mStartPoint = startPoint; mTrialsCounters = std::vector<unsigned>(mProblem->GetConstraintsNumber() + 1, 0); int k = 0, i=0; bool needRestart = true; /* currentFvalue will be initialized below, init here to avoid maybe-uninitialized warning */ double currentFValue = 0.0, nextFValue; while (i < MAX_LOCAL_ITERATIONS_NUMBER) { i++; if (needRestart) { k = 0; mCurrentPoint = mStartPoint; mCurrentResearchDirection = mStartPoint; currentFValue = ComputeObjective(mCurrentPoint.y); needRestart = false; } std::swap(mPreviousResearchDirection, mCurrentResearchDirection); mCurrentResearchDirection = mCurrentPoint; nextFValue = MakeResearch(mCurrentResearchDirection.y); if (currentFValue > nextFValue) { DoStep(); k++; currentFValue = nextFValue; } else if (mStep > mEps) { if (k != 0) std::swap(mStartPoint, mPreviousResearchDirection); else mStep /= mStepMultiplier; needRestart = true; } else break; } mPreviousResearchDirection.idx = 0; while (mPreviousResearchDirection.idx < mProblem->GetConstraintsNumber()) { mTrialsCounters[mPreviousResearchDirection.idx]++; mPreviousResearchDirection.g[mPreviousResearchDirection.idx] = mProblem->Calculate(mPreviousResearchDirection.y, mPreviousResearchDirection.idx); if (mPreviousResearchDirection.g[mPreviousResearchDirection.idx] > 0) break; mPreviousResearchDirection.idx++; } if (mPreviousResearchDirection.idx == mProblem->GetConstraintsNumber()) { mPreviousResearchDirection.g[mPreviousResearchDirection.idx] = mProblem->Calculate(mPreviousResearchDirection.y, mPreviousResearchDirection.idx); mTrialsCounters[mPreviousResearchDirection.idx]++; } for(size_t i = 0; i < mTrialsCounters.size(); i++) trialsCounters[i] += mTrialsCounters[i]; return mPreviousResearchDirection; } void HookeJeevesOptimizer::DoStep() { for (int i = 0; i < mProblem->GetDimension(); i++) mCurrentPoint.y[i] = (1 + mStepMultiplier)*mCurrentResearchDirection.y[i] - mStepMultiplier*mPreviousResearchDirection.y[i]; } double HookeJeevesOptimizer::ComputeObjective(const double* x) const { for (int i = 0; i <= mProblem->GetConstraintsNumber(); i++) { double value = mProblem->Calculate(x, i); mTrialsCounters[i]++; if (i < mProblem->GetConstraintsNumber() && value > 0) return std::numeric_limits<double>::max(); else if (i == mProblem->GetConstraintsNumber()) return value; } return std::numeric_limits<double>::max(); } double HookeJeevesOptimizer::MakeResearch(double* startPoint) { double bestValue = ComputeObjective(startPoint); for (int i = 0; i < mProblem->GetDimension(); i++) { startPoint[i] += mStep; double rightFvalue = ComputeObjective(startPoint); if (rightFvalue > bestValue) { startPoint[i] -= 2 * mStep; double leftFValue = ComputeObjective(startPoint); if (leftFValue > bestValue) startPoint[i] += mStep; else bestValue = leftFValue; } else bestValue = rightFvalue; } return bestValue; }
29.613139
100
0.695095
[ "vector" ]
b96c6f9410e1877de7313adb7a8b4788ea910588
5,497
cc
C++
algorithms/vi-map-helpers/src/vi-map-stats.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
1,936
2017-11-27T23:11:37.000Z
2022-03-30T14:24:14.000Z
algorithms/vi-map-helpers/src/vi-map-stats.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
353
2017-11-29T18:40:39.000Z
2022-03-30T15:53:46.000Z
algorithms/vi-map-helpers/src/vi-map-stats.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
661
2017-11-28T07:20:08.000Z
2022-03-28T08:06:29.000Z
#include "vi-map-helpers/vi-map-stats.h" #include <fstream> // NOLINT #include <sstream> // NOLINT #include <maplab-common/file-system-tools.h> #include <maplab-common/progress-bar.h> #include <posegraph/unique-id.h> #include <vi-map/vi-map.h> namespace vi_map_helpers { VIMapStats::VIMapStats(const vi_map::VIMap& map) : map_(map), map_queries_(map) {} std::string VIMapStats::toString() const { std::ostringstream oss; statistics::Accumulatord landmark_associated_keypoint_ratio; getLandmarkAssociatedKeypointsRatio(&landmark_associated_keypoint_ratio); oss << "Keypoints per Vertex associated with a landmark: " << landmark_associated_keypoint_ratio.min() << " " << landmark_associated_keypoint_ratio.Mean() << " " << landmark_associated_keypoint_ratio.max() << std::endl; statistics::Accumulatord landmark_observer_count; getLandmarkObserverCount(&landmark_observer_count); oss << "Observations per landmark: " << landmark_observer_count.min() << " " << landmark_observer_count.Mean() << " " << landmark_observer_count.max() << std::endl; std::unordered_map<vi_map::MissionId, bool> are_landmark_associations_track_scoped; areLandmarkAssociationsTrackScoped(&are_landmark_associations_track_scoped); for (const std::unordered_map<vi_map::MissionId, bool>::value_type& mission_result : are_landmark_associations_track_scoped) { if (mission_result.second) { oss << "Landmark associations of mission " << mission_result.first << " are track scoped." << std::endl; } else { oss << "Landmark associations of mission " << mission_result.first << " are NOT track scoped." << std::endl; } } return oss.str(); } void VIMapStats::getLandmarkAssociatedKeypointsRatio( statistics::Accumulatord* accumulator) const { CHECK_NOTNULL(accumulator); map_.forEachVisualFrame( [accumulator]( const aslam::VisualFrame& visual_frame, const vi_map::Vertex& vertex, size_t frame_idx) { const Eigen::Matrix2Xd& image_points_distorted = visual_frame.getKeypointMeasurements(); statistics::Accumulatord this_frame_ratio; for (int i = 0; i < image_points_distorted.cols(); ++i) { const vi_map::LandmarkId& landmark_id = vertex.getObservedLandmarkId(frame_idx, i); this_frame_ratio.Add((landmark_id.isValid() ? 1. : 0.)); } accumulator->Add(this_frame_ratio.Mean()); }); } void VIMapStats::getLandmarkObserverCount( statistics::Accumulatord* accumulator) const { CHECK_NOTNULL(accumulator); map_.forEachLandmark([accumulator](const vi_map::Landmark& landmark) { accumulator->Add(landmark.numberOfObservations()); }); } void VIMapStats::areLandmarkAssociationsTrackScoped( std::unordered_map<vi_map::MissionId, bool>* result) const { CHECK_NOTNULL(result)->clear(); vi_map::MissionIdList all_mission_ids; map_.getAllMissionIds(&all_mission_ids); for (const vi_map::MissionId& mission_id : all_mission_ids) { result->emplace(mission_id, areLandmarkAssociationsTrackScoped(mission_id)); } } bool VIMapStats::areLandmarkAssociationsTrackScoped( const vi_map::MissionId& mission_id) const { CHECK(map_.hasMission(mission_id)); enum class State { kTracking, kComplete }; typedef std::unordered_map<vi_map::LandmarkId, State> LandmarkStateMap; LandmarkStateMap landmark_states; bool result = true; map_queries_.forIdsOfObservedLandmarksOfEachVertexAlongGraphWhile( mission_id, [&](const vi_map::LandmarkIdSet& landmark_ids) -> bool { for (const vi_map::LandmarkId& landmark_id : landmark_ids) { LandmarkStateMap::iterator found = landmark_states.find(landmark_id); if (found != landmark_states.end()) { if (found->second == State::kComplete) { result = false; return false; } } else { landmark_states[landmark_id] = State::kTracking; } } for (LandmarkStateMap::value_type& landmark_state : landmark_states) { if (landmark_ids.count(landmark_state.first) == 0) { landmark_state.second = State::kComplete; } } return true; }); return result; } void VIMapStats::getNumLandmarksObservedByOtherMissionsForEachVertexAlongGraph( const vi_map::MissionId& mission_id, std::vector<size_t>* result) const { CHECK_NOTNULL(result)->clear(); pose_graph::VertexIdList ordered_vertices_of_mission; map_.getAllVertexIdsInMissionAlongGraph( mission_id, &ordered_vertices_of_mission); result->resize(ordered_vertices_of_mission.size()); VLOG(3) << "Counting amount of landmarks observed by other missions..."; common::ProgressBar progress_bar(ordered_vertices_of_mission.size()); // DO NOT PARALLELIZE (not worth due to cache mutexes)! for (size_t i = 0u; i < ordered_vertices_of_mission.size(); ++i) { VIMapQueries::VertexCommonLandmarksCountVector common_landmarks; map_queries_.getVerticesWithCommonLandmarks( ordered_vertices_of_mission[i], 0, &common_landmarks); (*result)[i] = 0u; for (const VIMapQueries::VertexCommonLandmarksCount& count : common_landmarks) { if (map_.getVertex(count.vertex_id).getMissionId() != mission_id) { (*result)[i] += count.in_common; } } progress_bar.increment(); } } } // namespace vi_map_helpers
36.892617
80
0.7002
[ "vector" ]
b96d554de4031dd72ee3a1d67d16df51bd3b7c84
14,169
cpp
C++
framework/render/video/glRender/GLRender.cpp
chenzheng102/CicadaPlayer
c4cc07dfb091052ea5c61243b81bed5d88a2407d
[ "MIT" ]
3
2020-03-28T08:21:09.000Z
2020-10-25T23:10:43.000Z
framework/render/video/glRender/GLRender.cpp
chenzheng102/CicadaPlayer
c4cc07dfb091052ea5c61243b81bed5d88a2407d
[ "MIT" ]
null
null
null
framework/render/video/glRender/GLRender.cpp
chenzheng102/CicadaPlayer
c4cc07dfb091052ea5c61243b81bed5d88a2407d
[ "MIT" ]
null
null
null
// // Created by lifujun on 2019/8/12. // #define LOG_TAG "GLRender" #include "render_system/EGL/gl_context_factory.h" #include "GLRender.h" #include <utils/timer.h> #include <utils/AFMediaType.h> #include <cassert> #include <cstdlib> using namespace std; static const int MAX_IN_SIZE = 3; #ifdef __ANDROID__ #include "OESProgramContext.h" #elif TARGET_OS_IPHONE #include "CV420PProgramContext.h" #include <base/media/PBAFFrame.h> #endif #include "render/video/vsync/VSyncFactory.h" #include "YUVProgramContext.h" using namespace Cicada; GLRender::GLRender(float Hz) { mVSync = VSyncFactory::create(*this, Hz); mHz = 0; mVSyncPeriod = static_cast<int64_t>(1000000 / Hz); #if TARGET_OS_IPHONE IOSNotificationManager::Instance()->RegisterObserver(this, 0); setenv("METAL_DEVICE_WRAPPER_TYPE", "0", 1); // setenv("CG_CONTEXT_SHOW_BACKTRACE", "1", 1); #endif } GLRender::~GLRender() { #if TARGET_OS_IPHONE IOSNotificationManager::Instance()->RemoveObserver(this); #endif AF_LOGE("~GLRender"); // MUST delete Vsync here,because it has callback mVSync = nullptr; } int GLRender::init() { AF_LOGD("-----> init ."); mVSync->start(); // std::unique_lock<std::mutex> locker(mInitMutex); // mInitCondition.wait(locker, [this]() -> int { // return mInitRet != INT32_MIN; // }); // return mInitRet; return 0; } int GLRender::clearScreen() { AF_LOGD("-----> clearScreen"); mClearScreenOn = true; return 0; } int GLRender::renderFrame(std::unique_ptr<IAFFrame> &frame) { // AF_LOGD("-----> renderFrame"); if (mInitRet != INT32_MIN && mInitRet != 0) { return -EINVAL; } if (frame == nullptr) { // do flush mVSync->pause(); std::unique_lock<std::mutex> locker(mFrameMutex); while (!mInputQueue.empty()) { dropFrame(); } mVSync->start(); return 0; } std::unique_lock<std::mutex> locker(mFrameMutex); mInputQueue.push(move(frame)); return 0; } void GLRender::dropFrame() { int64_t framePts = mInputQueue.front()->getInfo().pts; AF_LOGI("drop a frame pts = %lld ", framePts); mInputQueue.front()->setDiscard(true); mInputQueue.pop(); if (mRenderResultCallback != nullptr) { mRenderResultCallback(framePts, false); } } int GLRender::setRotate(IVideoRender::Rotate rotate) { AF_LOGD("-----> setRotate"); mRotate = rotate; return 0; } void GLRender::setVideoRotate(Rotate rotate) { mVideoRotate = rotate; } int GLRender::setFlip(IVideoRender::Flip flip) { AF_LOGD("-----> setFlip"); mFlip = flip; return 0; } int GLRender::setScale(IVideoRender::Scale scale) { AF_LOGD("-----> setScale"); mScale = scale; return 0; } int GLRender::onVSync(int64_t tick) { if (mInitRet == INT32_MIN) { VSyncOnInit(); if (mInitRet == INT32_MIN) { return 0; } else if (mInitRet != 0) { AF_LOGE("VSyncOnInit error"); return -EINVAL; } } if (mHz == 0) { mHz = mVSync->getHz(); if (mHz == 0) { mHz = 60; } mVSyncPeriod = static_cast<int64_t>(1000000 / mHz); } { std::unique_lock<std::mutex> locker(mFrameMutex); if (!mInputQueue.empty()) { if (mInputQueue.size() >= MAX_IN_SIZE) { while (mInputQueue.size() >= MAX_IN_SIZE) { dropFrame(); } mRenderClock.set(mInputQueue.front()->getInfo().pts); mRenderClock.start(); } else { assert(mInputQueue.front() != nullptr); if (mRenderClock.get() == 0) { mRenderClock.set(mInputQueue.front()->getInfo().pts); mRenderClock.start(); } int64_t late = mInputQueue.front()->getInfo().pts - mRenderClock.get(); if (llabs(late) > 100000) { mRenderClock.set(mInputQueue.front()->getInfo().pts); } else if (late - mVSyncPeriod * mRenderClock.getSpeed() > 0) { // AF_LOGD("mVSyncPeriod is %lld\n", mVSyncPeriod); // AF_LOGD("mRenderClock.get() is %lld\n", mRenderClock.get()); // AF_LOGD("mInputQueue.front()->getInfo().pts is %lld\n", mInputQueue.front()->getInfo().pts); calculateFPS(tick); return 0; } } } } if (renderActually()) { mRenderCount++; } calculateFPS(tick); return 0; } void GLRender::calculateFPS(int64_t tick) { if ((tick / uint64_t(mHz)) != mRendertimeS) { if (mRendertimeS == 0 || 1) { mRendertimeS = tick / uint64_t(mHz); } else { mRendertimeS++; } AF_LOGD("video fps is %llu\n", mRenderCount); mFps = mRenderCount; mRenderCount = 0; } } int GLRender::VSyncOnInit() { if (mInBackground) { return 0; } mContext = GLContextFactory::NewInstance(); mInitRet = mContext->Init(nullptr); mInitCondition.notify_all(); if (mInitRet != 0) { AF_LOGE("GLContext init failed. ret = %d ", mInitRet); return -EINVAL; } return 0; } void GLRender::VSyncOnDestroy() { mPrograms.clear(); assert(mContext != nullptr); mContext->DestroyView(); mContext->DestroySurface(mGLSurface); mGLSurface = nullptr; mContext->Destroy(); delete mContext; mContext = nullptr; } bool GLRender::renderActually() { if (mInBackground) { // AF_LOGD("renderActurally .. InBackground .."); return false; } // AF_LOGD("renderActually ."); bool rendered = true; int64_t renderStartTime = af_getsteady_ms(); #ifdef __ANDROID__ if (needCreateOutTexture) { IProgramContext *programContext = getProgram(AF_PIX_FMT_CICADA_MEDIA_CODEC); programContext->createSurface(); needCreateOutTexture = false; mCreateOutTextureCondition.notify_all(); } #endif assert(mContext != nullptr); bool displayViewChanged = false; { unique_lock<mutex> viewLock(mViewMutex); displayViewChanged = mContext->SetView(mDisplayView); bool viewSizeChanged = mContext->IsViewSizeChanged(); if (viewSizeChanged || displayViewChanged || (mGLSurface == nullptr && mDisplayView != nullptr)) { createGLSurface(); } else { mContext->MakeCurrent(mGLSurface); } } mWindowWidth = mContext->GetWidth(); mWindowHeight = mContext->GetHeight(); if (mGLSurface == nullptr) { // AF_LOGE("0918 renderActurally return mGLSurface = null.."); return false; } std::unique_ptr<IAFFrame> frame = nullptr; { std::unique_lock<std::mutex> locker(mFrameMutex); if (!mInputQueue.empty()) { frame = move(mInputQueue.front()); mInputQueue.pop(); } else { rendered = false; } } if (frame != nullptr) { mProgramFormat = frame->getInfo().format; mProgramContext = getProgram(mProgramFormat, frame.get()); } if (mProgramContext == nullptr) { mProgramFormat = -1; return false; } int64_t framePts = INT64_MIN; if (frame != nullptr) { framePts = frame->getInfo().pts; } Rotate finalRotate = Rotate_None; int tmpRotate = (mRotate + mVideoRotate) % 360; if (tmpRotate == 0) { finalRotate = Rotate_None; } else if (tmpRotate == 90) { finalRotate = Rotate_90; } else if (tmpRotate == 180) { finalRotate = Rotate_180; } else if (tmpRotate == 270) { finalRotate = Rotate_270; } mProgramContext->updateScale(mScale); mProgramContext->updateRotate(finalRotate); mProgramContext->updateWindowSize(mWindowWidth, mWindowHeight, displayViewChanged); mProgramContext->updateFlip(mFlip); int ret = mProgramContext->updateFrame(frame); //work around for glReadPixels is upside-down. { std::unique_lock<std::mutex> locker(mCaptureMutex); if (mCaptureOn && mCaptureFunc != nullptr) { //if need capture , update flip and other if (mFlip == Flip_None ) { mProgramContext->updateFlip(Flip_Vertical); } else if (mFlip == Flip_Vertical) { mProgramContext->updateFlip(Flip_None); } else if ( mFlip == Flip_Horizontal) { mProgramContext->updateFlip(Flip_Both); } if (finalRotate == Rotate_90) { mProgramContext->updateRotate(Rotate_270); } else if (finalRotate == Rotate_270) { mProgramContext->updateRotate(Rotate_90); } std::unique_ptr<IAFFrame> dummyFrame = nullptr; mProgramContext->updateFrame(dummyFrame); captureScreen(); //reset flip and other mProgramContext->updateFlip(mFlip); mProgramContext->updateRotate(finalRotate); mProgramContext->updateFrame(dummyFrame); } } if (ret == 0) { //if frame not change, don`t need present surface mContext->Present(mGLSurface); if ((INT64_MIN != framePts) && (mRenderResultCallback != nullptr)) { mRenderResultCallback(framePts, true); } } if (mClearScreenOn) { glViewport(0, 0, mWindowWidth, mWindowHeight); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); mContext->Present(mGLSurface); if (mProgramContext != nullptr) { mProgramFormat = -1; mProgramContext = nullptr; } mClearScreenOn = false; } int64_t end = af_getsteady_ms(); if (end - renderStartTime > 100) { AF_LOGD("renderActually use:%lld", end - renderStartTime); } // AF_LOGD(" cost time : render = %d ms", (af_getsteady_ms() - renderStartTime)); return rendered; } void GLRender::captureScreen() { int64_t captureStartTime = af_getsteady_ms(); GLint pView[4]; glGetIntegerv(GL_VIEWPORT, pView); int width = pView[2]; int height = pView[3]; GLsizei bufferSize = width * height * sizeof(GLubyte) * 4; //RGBA GLubyte *bufferData = (GLubyte *) malloc(bufferSize); memset(bufferData, 0, bufferSize); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glReadPixels(pView[0], pView[1], pView[2], pView[3], GL_RGBA, GL_UNSIGNED_BYTE, bufferData); int64_t captureEndTime = af_getsteady_ms(); AF_LOGD("capture cost time : capture = %d ms", (captureEndTime - captureStartTime)); mCaptureFunc(bufferData, width, height); free(bufferData); mCaptureOn = false; } int GLRender::setDisPlay(void *view) { AF_LOGD("-----> setDisPlay view = %p", view); unique_lock<mutex> viewLock(mViewMutex); mDisplayView = view; return 0; } void GLRender::createGLSurface() { if (mContext == nullptr) { return; } GLContext *pGLContext = mContext; pGLContext->DestroySurface(mGLSurface); pGLContext->MakeCurrent(nullptr); mGLSurface = pGLContext->CreateSurface(); if (mGLSurface == nullptr) { AF_LOGE("createGLSurface fail "); } pGLContext->MakeCurrent(mGLSurface); } void GLRender::captureScreen(std::function<void(uint8_t *, int, int)> func) { { std::unique_lock<std::mutex> locker(mCaptureMutex); mCaptureFunc = func; mCaptureOn = true; } } void *GLRender::getSurface() { #ifdef __ANDROID__ { std::unique_lock<std::mutex> locker(mCreateOutTextureMutex); needCreateOutTexture = true; mCreateOutTextureCondition.wait(locker, [this]() -> int { return !needCreateOutTexture; }); } IProgramContext *programContext = getProgram(AF_PIX_FMT_CICADA_MEDIA_CODEC); if (programContext == nullptr) { return nullptr; } return programContext->getSurface(); #endif return nullptr; } IProgramContext *GLRender::getProgram(int frameFormat, IAFFrame *frame) { if (mPrograms.count(frameFormat) > 0) { return mPrograms[frameFormat].get(); } unique_ptr<IProgramContext> targetProgram{nullptr}; #ifdef __ANDROID__ if (frameFormat == AF_PIX_FMT_CICADA_MEDIA_CODEC) { targetProgram = unique_ptr<IProgramContext>(new OESProgramContext()); } else #elif TARGET_OS_IPHONE if (frameFormat == AF_PIX_FMT_APPLE_PIXEL_BUFFER && frame != nullptr) { CVPixelBufferRef pixelBuffer = (dynamic_cast<PBAFFrame *>(frame))->getPixelBuffer(); OSType pixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer); if (pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange || pixelFormat == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange) { targetProgram = unique_ptr<IProgramContext>(new CV420PProgramContext(mContext->GetContext())); } } else #endif if (frameFormat == AF_PIX_FMT_YUV420P || frameFormat == AF_PIX_FMT_YUVJ420P) { targetProgram = unique_ptr<IProgramContext>(new YUVProgramContext()); } if (targetProgram == nullptr) { return nullptr; } int ret = targetProgram->initProgram(); if (ret == 0) { mPrograms[frameFormat] = move(targetProgram); return mPrograms[frameFormat].get(); } else { return nullptr; } } void GLRender::setSpeed(float speed) { mRenderClock.setSpeed(speed); } #if TARGET_OS_IPHONE void GLRender::AppWillResignActive() { mInBackground = true; AF_LOGE("0919, mInBackground = true"); mVSync->pause(); }; void GLRender::AppDidBecomeActive() { mInBackground = false; AF_LOGE("0919, mInBackground = false"); mVSync->start(); } #endif float GLRender::getRenderFPS() { return mFps; } void GLRender::setRenderResultCallback(function<void(int64_t, bool)> renderResultCallback) { mRenderResultCallback = renderResultCallback; };
25.575812
114
0.609288
[ "render" ]
b971642287bd35ce1d582d719f3e0106730e6269
641
cpp
C++
atcoder/contests/dp/B.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
atcoder/contests/dp/B.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
atcoder/contests/dp/B.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Educational DP Contest - B - Frog 2 https://atcoder.jp/contests/dp/tasks/dp_b */ #include <bits/stdc++.h> using namespace std; #define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL) int main() { FAST_INP; int n, k; cin >> n >> k; vector<int> h(n), dp(n,1e9+5); for(int i=0;i<n;i++) cin >> h[i]; dp[0]=0; for(int i=0;i<n;i++) { // current stone for(int j=i+1;j<=i+k;j++){ // target stone if(j<n){ // check if it is out of bound dp[j]=min(dp[j],dp[i]+abs(h[j]-h[i])); // store min cost jumping to stone j from stone i } } } cout << dp[n-1] << "\n"; return 0; }
22.103448
95
0.547582
[ "vector" ]
b9740868864ed114c5d1be990b7e542fd34a6f18
1,635
cpp
C++
hackerrank.com/#hourrank/15/C.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
hackerrank.com/#hourrank/15/C.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
hackerrank.com/#hourrank/15/C.cpp
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<set> using namespace std; const long long MOD = 1000000000+9; int getAns(int pairs, int unpaired, vector<vector<int>> & mA, vector<vector<int>> & mB, int allowed = 0) { if(pairs==0&&unpaired==0) return 1; if(unpaired<0||pairs<0) return 0; if(allowed==0&&mA[pairs][unpaired]!=-1) return mA[pairs][unpaired]; if(allowed==1&&mB[pairs][unpaired]!=-1) return mB[pairs][unpaired]; long long res = 0; res+=((unpaired-allowed)*(long long)getAns(pairs, unpaired-1, mA,mB))%MOD; if(pairs) res+=(pairs*(long long)getAns(pairs-1, unpaired+1, mA, mB, 1))%MOD; res%=MOD; if(allowed==0) return mA[pairs][unpaired] = res; else return mB[pairs][unpaired] = res; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int q; cin >> q; while(q--) { int n; cin >> n; set<int> usedOnce, usedTwice; int tmp; for(int i = 0; i<n; i++) { cin >> tmp; if(usedOnce.count(tmp)) { usedOnce.erase(tmp); usedTwice.insert(tmp); } else { usedOnce.insert(tmp); } } vector<vector<int> > memorizedA(2005, vector<int>(2005,-1)); vector<vector<int> > memorizedB(2005, vector<int>(2005,-1)); cout << getAns(usedTwice.size(), usedOnce.size(), memorizedA, memorizedB) << '\n'; } return 0; }
21.513158
105
0.498471
[ "vector" ]
b9763610e4660097bb8b957bd177c83a59350cc0
1,444
hpp
C++
GhostEngine/VDeleter.hpp
KamenBlackRX/GhostEngine
e9ea94a499916efc86094645509eb962a9782344
[ "MIT" ]
2
2018-10-18T09:11:37.000Z
2019-09-03T14:56:08.000Z
GhostEngine/VDeleter.hpp
KamenBlackRX/GhostEngine
e9ea94a499916efc86094645509eb962a9782344
[ "MIT" ]
null
null
null
GhostEngine/VDeleter.hpp
KamenBlackRX/GhostEngine
e9ea94a499916efc86094645509eb962a9782344
[ "MIT" ]
null
null
null
/* * Clean all Vulkan objects. */ template<typename T> class VDeleter { public: VDeleter() : VDeleter([](T, VkAllocationCallbacks*) {}) { PRINT("logWarning: ","Now Deleting objects.\n"); } VDeleter(std::function<void(T, VkAllocationCallbacks*)> deletef) { PRINT("logWarning: ","Now Deleting Callbacks\n"); this->deleter = [=](T obj) { deletef(obj, nullptr); }; } VDeleter(const VDeleter<VkInstance>& instance, std::function<void(VkInstance, T, VkAllocationCallbacks*)> deletef) { PRINT("logWarning: ", "Now Deleting Instances.\n"); this->deleter = [&instance, deletef](T obj) { deletef(instance, obj, nullptr); }; } VDeleter(const VDeleter<VkDevice>& device, std::function<void(VkDevice, T, VkAllocationCallbacks*)> deletef) { PRINT("logWarning: ", "Now Deleting Devices\n"); this->deleter = [&device, deletef](T obj) { deletef(device, obj, nullptr); }; } ~VDeleter() { cleanup(); } const T* operator &() const { return &object; } T* replace() { cleanup(); return &object; } operator T() const { return object; } void operator=(T rhs) { if (rhs != object) { cleanup(); object = rhs; } } template<typename V> bool operator==(V rhs) { return object == T(rhs); } private: T object{ VK_NULL_HANDLE }; std::function<void(T)> deleter; void cleanup() { if (object != VK_NULL_HANDLE) { deleter(object); } object = VK_NULL_HANDLE; } };
16.044444
115
0.632271
[ "object" ]
b97804d16bed1392f5e9b33808ef27d8a7fad0b7
2,604
cc
C++
projects/projects/code/GraphicsNode.cc
klu0711/S0006E
b477f99930070aad976409b61decc3bb788fdf93
[ "MIT" ]
null
null
null
projects/projects/code/GraphicsNode.cc
klu0711/S0006E
b477f99930070aad976409b61decc3bb788fdf93
[ "MIT" ]
null
null
null
projects/projects/code/GraphicsNode.cc
klu0711/S0006E
b477f99930070aad976409b61decc3bb788fdf93
[ "MIT" ]
null
null
null
#include "GraphicsNode.h" GraphicsNode::GraphicsNode() { transform = Matrix4::rotY(1); } GraphicsNode::~GraphicsNode() { this->shader = 0; this->meshResource = 0; this->textureResource = 0; } /// Set the shader pointer to an instance void GraphicsNode::setShaderClass(std::shared_ptr<Shader> shader) { this->shader = shader; } /// Set the texture pointer to an instance void GraphicsNode::setTextureclass(std::shared_ptr<TextureResource> textureResource) { this->textureResource = textureResource; } /// Set the mesh pointer to an instance void GraphicsNode::setMeshCLass(std::shared_ptr<MeshResource> meshResource) { this->meshResource = meshResource; } /// Return the shader pointer Shader* GraphicsNode::getShader() { return shader.get(); } /// Return the texture pointer TextureResource* GraphicsNode::getTextureResource() { return textureResource.get(); } /// Return the mesh pointer MeshResource* GraphicsNode::getMeshResource() { return meshResource.get(); } /// return the stored transform Matrix4 GraphicsNode::getTransform() { return transform; } /// Change the stored transform void GraphicsNode::setTransform(Matrix4 mat) { transform = mat; } /// Run all the functions that need to be run to draw something but only the functions that don't need to be ran every frame void GraphicsNode::load(std::string filename, std::string vertexShaderName, std::string fragmentShaderName, int texture) { shader.get()->loadVertexShader(vertexShaderName.c_str()); shader.get()->loadFragmentShader(fragmentShaderName.c_str()); shader.get()->linkShaders(); //meshResource.get()->setupHandles(); //meshResource.get()->loadOBJFile(vertices, uv, normals); //combinedbuffer = meshResource.get()->combineBuffers(vertices, uv, normals); //meshResource.get()->convertToFloatPointer(vertices, indicies, normals); textureResource.get()->bind(texture); light = LightingNode(Vector4D(5, 2, 0, 1), Vector4D(0.5f, 0.5f, 0.5f, 1), 1); shader.get()->useProgram(); } /// This functions runs every frame to draw something to the screen void GraphicsNode::draw() { rend.clearZbuffer(); shader.get()->modifyUniformMatrix("transform", transform.getPointer()); shader->modifyUniformVector("lightPos", light.getPosition()); shader->modifyUniformVector("lightColor", light.getColor()); shader->modifyUniformFloat("intensity", light.getIntensity()); meshResource.get()->bind(); int test = meshResource->getIndexSize(); glDrawElements(GL_TRIANGLES, meshResource->getIndexSize(), GL_UNSIGNED_INT, 0); //glDrawArrays(GL_TRIANGLES, 0, vertices.size()); meshResource.get()->unBindBuffers(); }
28.304348
124
0.748848
[ "mesh", "transform" ]
b9852d50687b142c075d0d20d5004575338f7f09
249
hpp
C++
include/ContainsDuplicateII.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
include/ContainsDuplicateII.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
include/ContainsDuplicateII.hpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#ifndef CONTAINS_DUPLICATE_II_HPP_ #define CONTAINS_DUPLICATE_II_HPP_ #include <vector> using namespace std; class ContainsDuplicateII { public: bool containsNearbyDuplicate(vector<int> &nums, int k); }; #endif // CONTAINS_DUPLICATE_II_HPP_
17.785714
59
0.799197
[ "vector" ]
b98704a62f09ee9fdb5ba4785609a6b2a2f7233e
7,809
cc
C++
builtin/filtered_dataset.cc
mldbai/mldb
0554aa390a563a6294ecc841f8026a88139c3041
[ "Apache-2.0" ]
665
2015-12-09T17:00:14.000Z
2022-03-25T07:46:46.000Z
builtin/filtered_dataset.cc
mldbai/mldb
0554aa390a563a6294ecc841f8026a88139c3041
[ "Apache-2.0" ]
797
2015-12-09T19:48:19.000Z
2022-03-07T02:19:47.000Z
builtin/filtered_dataset.cc
mldbai/mldb
0554aa390a563a6294ecc841f8026a88139c3041
[ "Apache-2.0" ]
103
2015-12-25T04:39:29.000Z
2022-02-03T02:55:22.000Z
// This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. /** filtered_dataset.cc -*- C++ -*- Guy Dumais, September 18th, 2015 Copyright (c) 2015 mldb.ai inc. All rights reserved. */ #include "mldb/engine/dataset_collection.h" #include "mldb/sql/sql_expression.h" #include "mldb/core/dataset_scope.h" #include "mldb/core/analytics.h" #include "filtered_dataset.h" #include "mldb/types/any_impl.h" using namespace std; namespace MLDB { namespace { struct BetweenFilter { bool notBetween; Date lower, upper; BetweenFilter(bool notBetween, const Date& lower, const Date& upper) : notBetween(notBetween), lower(lower), upper(upper) {} FilteredDataset::TupleFilter eval() { // prevent the this pointer from being captured allowing syntax like BetweenFilter(...).eval() Date lower_ = lower; Date upper_ = upper; bool notBetween_ = notBetween; return [lower_, upper_, notBetween_](const CellValue & value, const Date & date) { //cerr << "between " << lower_ << " " << upper_ << " " << date << endl; if (date < lower_) return notBetween_; if (date > upper_) return notBetween_; return !notBetween_; }; } }; typedef std::function<bool(const Date & leftDate, const Date & rightDate)> CompareOp; struct CompareFilter { CompareOp op; Date constantDate; CompareFilter(const CompareOp & op, const Date& date) : op(op), constantDate(date) {} FilteredDataset::TupleFilter eval() { // prevent the this pointer from being captured allowing syntax like CompareFilter(...).eval() CompareOp op_ = op; Date constantDate_ = constantDate; return [op_, constantDate_](const CellValue & value, const Date & date) { //cerr << "compare " << date << " " << constantDate_ << endl; return op_(date, constantDate_); }; } }; typedef std::function<bool(const bool &, const bool &)> BooleanOp; struct BooleanFilter { BooleanOp op; FilteredDataset::TupleFilter left, right; BooleanFilter(const BooleanOp & op, const FilteredDataset::TupleFilter & left, const FilteredDataset::TupleFilter & right) : op(op), left(left), right(right) {} FilteredDataset::TupleFilter eval() { // prevent the this pointer from being captured allowing syntax like BooleanFilter(...).eval() FilteredDataset::TupleFilter left_ = left; FilteredDataset::TupleFilter right_ = right; BooleanOp op_ = op; return [op_, left_, right_](const CellValue & value, const Date & date) { //cerr << "boolean " << value << endl; return op_(left_(value, date), right_(value, date)); }; } }; } /*****************************************************************************/ /* FILTERED DATASET INTERNAL REPRESENTATION */ /*****************************************************************************/ struct FilteredDataset::Itl : public MatrixView, public ColumnIndex { std::shared_ptr<MatrixView> matrixView; std::shared_ptr<ColumnIndex> columnIndex; const TupleFilter filter; Itl(std::shared_ptr<MatrixView> matrixView, std::shared_ptr<ColumnIndex> columnIndex, const TupleFilter& filter) : matrixView(matrixView), columnIndex(columnIndex), filter(filter) { } ~Itl() { } /** MatrixView */ virtual RowPath getRowPath(const RowHash & rowHash) const { return matrixView->getRowPath(rowHash); } virtual ColumnPath getColumnPath(ColumnHash column) const { return matrixView->getColumnPath(column); } virtual std::vector<RowPath> getRowPaths(ssize_t start = 0, ssize_t limit = -1) const { return matrixView->getRowPaths(start, limit); } virtual std::vector<RowHash> getRowHashes(ssize_t start = 0, ssize_t limit = -1) const { return matrixView->getRowHashes(start, limit); } virtual uint64_t getRowCount() const { return matrixView->getRowCount(); } virtual bool knownRow(const RowPath & rowName) const { return matrixView->knownRow(rowName); } virtual MatrixNamedRow getRow(const RowPath & rowName) const { MatrixNamedRow matrixRow = matrixView->getRow(rowName); std::vector<std::tuple<ColumnPath, CellValue, Date> > columns; auto filterColumn = [=] (const std::tuple<ColumnPath, CellValue, Date> & tuple) { return filter(get<1>(tuple), get<2>(tuple)); }; std::copy_if(matrixRow.columns.begin(), matrixRow.columns.end(), std::back_inserter(columns), filterColumn); return {matrixRow.rowHash, matrixRow.rowName, columns }; } virtual bool knownColumn(const ColumnPath & column) const { return matrixView->knownColumn(column); } virtual std::vector<ColumnPath> getColumnPaths(ssize_t offset, ssize_t limit) const { return matrixView->getColumnPaths(offset, limit); } virtual size_t getColumnCount() const { return matrixView->getColumnCount(); } virtual const ColumnStats & getColumnStats(const ColumnPath & ch, ColumnStats & toStoreResult) const { return columnIndex->getColumnStats(ch, toStoreResult); } virtual MatrixColumn getColumn(const ColumnPath & columnHash) const { MatrixColumn matrixColumn = columnIndex->getColumn(columnHash); std::vector<std::tuple<RowPath, CellValue, Date> > rows; auto filterRow = [=] (const std::tuple<RowHash, CellValue, Date> & tuple) { return filter(get<1>(tuple), get<2>(tuple)); }; std::copy_if(matrixColumn.rows.begin(), matrixColumn.rows.end(), std::back_inserter(rows), filterRow); return {matrixColumn.columnHash, matrixColumn.columnName, rows}; } virtual std::vector<std::tuple<RowPath, CellValue> > getColumnValues(const ColumnPath & columnName, const std::function<bool (const CellValue &)> & filter) const { // TODO apply the predicate here return columnIndex->getColumnValues(columnName, filter); } // Duplicated methods in interfaces - Implemented as part of MatrixView //virtual bool knownColumn(ColumnHash column) const //virtual std::vector<ColumnPath> getColumnPaths() const }; /*****************************************************************************/ /* FILTERED DATASET */ /*****************************************************************************/ FilteredDataset:: FilteredDataset(const Dataset& dataset, const FilteredDataset::TupleFilter& filter) : Dataset(dataset.engine), dataset(dataset) { itl.reset(new Itl(dataset.getMatrixView(), dataset.getColumnIndex(), filter)); } FilteredDataset:: ~FilteredDataset() { } Any FilteredDataset:: getStatus() const { return Any(); } KnownColumn FilteredDataset:: getKnownColumnInfo(const ColumnPath & columnName) const { return dataset.getKnownColumnInfo(columnName); } BoundFunction FilteredDataset:: overrideFunction(const Utf8String & tableName, const Utf8String & functionName, SqlBindingScope & context) const { return dataset.overrideFunction(tableName, functionName, context); } std::shared_ptr<MatrixView> FilteredDataset:: getMatrixView() const { return itl; } std::shared_ptr<ColumnIndex> FilteredDataset:: getColumnIndex() const { return itl; } } // namespace MLDB
29.692015
128
0.614035
[ "vector" ]
b98779c3fea25c0b1c9286b10bf8c911fd7f497e
1,792
cc
C++
Samples/1_ImGui/Source/FGuiHelloWorld.cc
liliilli/SH-D3D11
1ffb4639d5d9dd06d08b2aa21ebc781ee22fb26c
[ "Unlicense", "MIT" ]
null
null
null
Samples/1_ImGui/Source/FGuiHelloWorld.cc
liliilli/SH-D3D11
1ffb4639d5d9dd06d08b2aa21ebc781ee22fb26c
[ "Unlicense", "MIT" ]
null
null
null
Samples/1_ImGui/Source/FGuiHelloWorld.cc
liliilli/SH-D3D11
1ffb4639d5d9dd06d08b2aa21ebc781ee22fb26c
[ "Unlicense", "MIT" ]
null
null
null
/// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// 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 <FGuiHelloWorld.h> #include <imgui.h> #include <Profiling/MTimeChecker.h> FGuiHelloWorld::FGuiHelloWorld() { this->mModel = std::make_unique<DModelHelloWorld>(); this->SetVisibility(true); } void FGuiHelloWorld::Render() { auto& model = static_cast<DModelHelloWorld&>(this->GetModel()); // Create a window called "Hello, world!" and append into it. ImGui::Begin("Hello, world!"); // Display some text (you can use a format strings too) ImGui::Text("This is some useful text."); // Edit 1 float using a slider from 0.0f to 1.0f ImGui::SliderFloat("float", &model.f, 0.0f, 1.0f); if (ImGui::Button("Button")) { model.counter++; } ImGui::SameLine(); ImGui::Text("counter = %d", model.counter); ImGui::Text( "Application average of ImGui %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Text("CPU Average frame %.3f ms/frame", MTimeChecker::Get("CpuFrame").GetAverage().count() * 1000.0); if (MTimeChecker::GetGpuD3D11("GpuFrame").HasFragment("Overall") == true) { ImGui::Text("GPU Frame %.3f ms/frame", MTimeChecker::GetGpuD3D11("GpuFrame")["Overall"].GetRecent().count() * 1000.0); } ImGui::End(); }
32.581818
85
0.682478
[ "render", "model" ]
b98809d7a430184bf7229ff77b9d6db023101bdd
5,090
cpp
C++
Samples/2.0/Tutorials/Tutorial_TextureBaking/Tutorial_TextureBaking.cpp
coolzoom/ogre-next
31ec929356e40becafcdef31686bc90cd6da7530
[ "MIT" ]
1
2021-05-12T18:01:21.000Z
2021-05-12T18:01:21.000Z
Samples/2.0/Tutorials/Tutorial_TextureBaking/Tutorial_TextureBaking.cpp
coolzoom/ogre-next
31ec929356e40becafcdef31686bc90cd6da7530
[ "MIT" ]
null
null
null
Samples/2.0/Tutorials/Tutorial_TextureBaking/Tutorial_TextureBaking.cpp
coolzoom/ogre-next
31ec929356e40becafcdef31686bc90cd6da7530
[ "MIT" ]
null
null
null
#include "GraphicsSystem.h" #include "Tutorial_TextureBakingGameState.h" #include "OgreSceneManager.h" #include "OgreCamera.h" #include "OgreRoot.h" #include "OgreWindow.h" #include "OgreConfigFile.h" #include "Compositor/OgreCompositorManager2.h" #include "OgreHlmsManager.h" #include "OgreHlmsPbs.h" //Declares WinMain / main #include "MainEntryPointHelper.h" #include "System/Android/AndroidSystems.h" #include "System/MainEntryPoints.h" #if OGRE_PLATFORM != OGRE_PLATFORM_ANDROID #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32 INT WINAPI WinMainApp( HINSTANCE hInst, HINSTANCE hPrevInstance, LPSTR strCmdLine, INT nCmdShow ) #else int mainApp( int argc, const char *argv[] ) #endif { return Demo::MainEntryPoints::mainAppSingleThreaded( DEMO_MAIN_ENTRY_PARAMS ); } #endif namespace Demo { class Tutorial_TextureBakingGraphicsSystem : public GraphicsSystem { virtual Ogre::CompositorWorkspace* setupCompositor() { Ogre::CompositorManager2 *compositorManager = mRoot->getCompositorManager2(); mWorkspace = compositorManager->addWorkspace( mSceneManager, mRenderWindow->getTexture(), mCamera, "ShadowMapDebuggingWorkspace", true ); return mWorkspace; } virtual void setupResources(void) { GraphicsSystem::setupResources(); Ogre::ConfigFile cf; cf.load( AndroidSystems::openFile( mResourcePath + "resources2.cfg" ) ); Ogre::String originalDataFolder = cf.getSetting( "DoNotUseAsResource", "Hlms", "" ); if( originalDataFolder.empty() ) originalDataFolder = AndroidSystems::isAndroid() ? "/" : "./"; else if( *(originalDataFolder.end() - 1) != '/' ) originalDataFolder += "/"; const char *c_locations[] = { "2.0/scripts/materials/Tutorial_TextureBaking", "2.0/scripts/materials/Tutorial_TextureBaking/GLSL", "2.0/scripts/materials/Tutorial_TextureBaking/HLSL", "2.0/scripts/materials/Tutorial_TextureBaking/Metal" }; for( size_t i=0; i<sizeof(c_locations) / sizeof(c_locations[0]); ++i ) { Ogre::String dataFolder = originalDataFolder + c_locations[i]; addResourceLocation( dataFolder, getMediaReadArchiveType(), "General" ); } } virtual void loadResources(void) { GraphicsSystem::loadResources(); Ogre::Hlms *hlms = mRoot->getHlmsManager()->getHlms( Ogre::HLMS_PBS ); OGRE_ASSERT_HIGH( dynamic_cast<Ogre::HlmsPbs*>( hlms ) ); Ogre::HlmsPbs *hlmsPbs = static_cast<Ogre::HlmsPbs*>( hlms ); hlmsPbs->loadLtcMatrix(); } public: Tutorial_TextureBakingGraphicsSystem( GameState *gameState ) : GraphicsSystem( gameState ) { } }; void MainEntryPoints::createSystems( GameState **outGraphicsGameState, GraphicsSystem **outGraphicsSystem, GameState **outLogicGameState, LogicSystem **outLogicSystem ) { Tutorial_TextureBakingGameState *gfxGameState = new Tutorial_TextureBakingGameState( "Shows how to bake the render result of Ogre into a texture (e.g. for lightmaps).\n" "You can either bake all lights, or bake just the most expensive lights to\n" "later combine it with more dynamic (non-baked) lights while using light masks\n" "to filter lights.\n" "This can be a simple yet very effective way to increase performance with a high\n" "number of lights.\n" "Note that specular lighting is dependent on camera location; thus camera position when \n" "baking IS important. We left specular on to show this effect, which you can experiment\n" "by pressing F4, then F5, then moving the camera.\n" "Also note that if the baked plane goes out of camera, it will get culled!!!.\n" "This sample depends on the media files:\n" " * Samples/Media/2.0/scripts/Compositors/UvBaking.compositor\n" " * Samples/Media/2.0/materials/Tutorial_TextureBaking/*\n" "\n" ); GraphicsSystem *graphicsSystem = new Tutorial_TextureBakingGraphicsSystem( gfxGameState ); gfxGameState->_notifyGraphicsSystem( graphicsSystem ); *outGraphicsGameState = gfxGameState; *outGraphicsSystem = graphicsSystem; } void MainEntryPoints::destroySystems( GameState *graphicsGameState, GraphicsSystem *graphicsSystem, GameState *logicGameState, LogicSystem *logicSystem ) { delete graphicsSystem; delete graphicsGameState; } const char* MainEntryPoints::getWindowTitle(void) { return "Texture Baking"; } }
38.560606
105
0.623379
[ "render" ]