blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
29b199ca97fd542560d6f68db55873c60c4f0032
f76bf9fe835800bf84a7fbde30b4fc3bfa40565f
/delay.hpp
f41ffdbf2c250ef656ac2ae86f42e953f1dae6c2
[ "MIT" ]
permissive
shunsukeaihara/ssp
e4c12a7521568c30370a3ea9875cd16157482369
ba562000c9c51109a68eb905ef01e5666ef9f484
refs/heads/master
2020-05-05T04:55:11.365019
2019-04-24T05:52:49
2019-04-24T05:52:49
179,730,102
8
0
null
null
null
null
UTF-8
C++
false
false
970
hpp
#ifndef SSP_DELAY_H_ #define SSP_DELAY_H_ #include <common.hpp> #include <iostream> #include <ringbuffer.hpp> namespace ssp { template <typename T> class Delay { public: Delay(const T delayMs, const int delayCount, const T decay, const T fs) : _buffer(int((delayMs / 1000.0 * fs) * delayCount + 1)) { _delayCount = delayCount; _delaySamples = int(delayMs / 1000.0 * fs); _decay = decay; } virtual ~Delay() {} inline T filterOne(const T in) { T x = in; _buffer.push(in); for (int i = 1; i <= _delayCount; i++) { x += _buffer[-(_delaySamples * i)] * pow(_decay, i); } return x; } inline void filter(T *in, const int len) { for (int i = 0; i < len; i++) { in[i] = filterOne(in[i]); } } private: int _delaySamples; int _delayCount; T _decay; RingBuffer<T> _buffer; }; } // namespace ssp #endif /* SSP_DELAY_H_ */
[ "s.aihara@gmail.com" ]
s.aihara@gmail.com
3dd9adae7c9fc521901f68e80cfda7e880f7e8e4
dac5254630fefae851da7c843dcab7f6a6af9703
/MacOS/Sources/Application/Preferences_Dialog/Sub-panels/Attachment_Panels/CPrefsAttachmentsSend.cp
da4593c2fa0625c513093b15d80863230bb6b268
[ "Apache-2.0" ]
permissive
gpreviato/Mulberry-Mail
dd4e3618468fff36361bd2aeb0a725593faa0f8d
ce5c56ca7044e5ea290af8d3d2124c1d06f36f3a
refs/heads/master
2021-01-20T03:31:39.515653
2017-09-21T13:09:55
2017-09-21T13:09:55
18,178,314
5
2
null
null
null
null
UTF-8
C++
false
false
5,389
cp
/* Copyright (c) 2007 Cyrus Daboo. 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. */ // Source for CPrefsLetter class #include "CPrefsAttachmentsSend.h" #include "CPreferences.h" #include "CStringUtils.h" #include "CTextDisplay.h" #include <LCheckBox.h> #include <LCheckBoxGroupBox.h> #include <LPopupButton.h> #include <LRadioButton.h> // __________________________________________________________________________________________________ // C L A S S __ C P R E F S A T T A C H M E N T S // __________________________________________________________________________________________________ // C O N S T R U C T I O N / D E S T R U C T I O N M E T H O D S // Default constructor CPrefsAttachmentsSend::CPrefsAttachmentsSend() { } // Constructor from stream CPrefsAttachmentsSend::CPrefsAttachmentsSend(LStream *inStream) : CPrefsTabSubPanel(inStream) { } // Default destructor CPrefsAttachmentsSend::~CPrefsAttachmentsSend() { } // O T H E R M E T H O D S ____________________________________________________________________________ // Get details of sub-panes void CPrefsAttachmentsSend::FinishCreateSelf(void) { // Do inherited CPrefsTabSubPanel::FinishCreateSelf(); // Get menu and radios mDefaultEncoding = (LPopupButton*) FindPaneByID(paneid_EncodingMenu); mEncodingAlways = (LRadioButton*) FindPaneByID(paneid_EncodingAlways); mEncodingWhenNeeded = (LRadioButton*) FindPaneByID(paneid_EncodingWhenNeeded); mCheckDefaultMailClient = (LCheckBox*) FindPaneByID(paneid_CheckDefaultMailClient); mWarnMailtoFiles = (LCheckBox*) FindPaneByID(paneid_WarnMailtoFiles); mCheckDefaultWebcalClient = (LCheckBox*) FindPaneByID(paneid_CheckDefaultWebcalClient); mWarnMissingAttachments = (LCheckBoxGroupBox*) FindPaneByID(paneid_WarnMissingAttachments); mMissingAttachmentSubject = (LCheckBox*) FindPaneByID(paneid_MissingAttachmentSubject); mMissingAttachmentWords = (CTextDisplay*) FindPaneByID(paneid_MissingAttachmentWords); } // Set prefs void CPrefsAttachmentsSend::SetData(void* data) { // Save ref to prefs CPreferences* copyPrefs = (CPreferences*) data; // Copy info switch(copyPrefs->mDefault_mode.GetValue()) { case eUUMode: mDefaultEncoding->SetValue(menu_PrefsAttachmentsUU); break; case eBinHex4Mode: mDefaultEncoding->SetValue(menu_PrefsAttachmentsBinHex); break; case eAppleSingleMode: mDefaultEncoding->SetValue(menu_PrefsAttachmentsAS); break; case eAppleDoubleMode: default: mDefaultEncoding->SetValue(menu_PrefsAttachmentsAD); break; } mEncodingAlways->SetValue(copyPrefs->mDefault_Always.GetValue()); mEncodingWhenNeeded->SetValue(!copyPrefs->mDefault_Always.GetValue()); mCheckDefaultMailClient->SetValue(copyPrefs->mCheckDefaultMailClient.GetValue()); mWarnMailtoFiles->SetValue(copyPrefs->mWarnMailtoFiles.GetValue()); mCheckDefaultWebcalClient->SetValue(copyPrefs->mCheckDefaultWebcalClient.GetValue()); mWarnMissingAttachments->SetValue(copyPrefs->mWarnMissingAttachments.GetValue()); mMissingAttachmentSubject->SetValue(copyPrefs->mMissingAttachmentSubject.GetValue()); cdstring words; for(cdstrvect::const_iterator iter = copyPrefs->mMissingAttachmentWords.GetValue().begin(); iter != copyPrefs->mMissingAttachmentWords.GetValue().end(); iter++) { words += *iter; words += os_endl; } mMissingAttachmentWords->SetText(words); } // Force update of prefs void CPrefsAttachmentsSend::UpdateData(void* data) { CPreferences* copyPrefs = (CPreferences*) data; // Copy info from panel into prefs switch(mDefaultEncoding->GetValue()) { case menu_PrefsAttachmentsUU: copyPrefs->mDefault_mode.SetValue(eUUMode); break; case menu_PrefsAttachmentsBinHex: copyPrefs->mDefault_mode.SetValue(eBinHex4Mode); break; case menu_PrefsAttachmentsAS: copyPrefs->mDefault_mode.SetValue(eAppleSingleMode); break; case menu_PrefsAttachmentsAD: default: copyPrefs->mDefault_mode.SetValue(eAppleDoubleMode); break; } copyPrefs->mDefault_Always.SetValue((mEncodingAlways->GetValue() == 1)); copyPrefs->mCheckDefaultMailClient.SetValue(mCheckDefaultMailClient->GetValue() == 1); copyPrefs->mWarnMailtoFiles.SetValue(mWarnMailtoFiles->GetValue() == 1); copyPrefs->mCheckDefaultWebcalClient.SetValue(mCheckDefaultWebcalClient->GetValue() == 1); copyPrefs->mMissingAttachmentSubject.SetValue(mMissingAttachmentSubject->GetValue() == 1); copyPrefs->mWarnMissingAttachments.SetValue(mWarnMissingAttachments->GetValue() == 1); // Only copy text if dirty if (mMissingAttachmentWords->IsDirty()) { // Copy handle to text with null terminator cdstring txt; mMissingAttachmentWords->GetText(txt); char* s = ::strtok(txt.c_str_mod(), CR); cdstrvect accumulate; while(s) { cdstring copyStr(s); accumulate.push_back(copyStr); s = ::strtok(nil, CR); } copyPrefs->mMissingAttachmentWords.SetValue(accumulate); } }
[ "svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132" ]
svnusers@a91246af-f21b-0410-bd1c-c3c7fc455132
f72fa607c70d713c536cb34c362889be74937d05
57e9be685bf91a7c51393a5b1b470c77ec5da8de
/src/point3d.h
40251922b606dccef756c4ce3e5322f443782c96
[]
no_license
foolchi/QuickHull3D
04df84f8b3898106ea4455cd124494d22a2f2482
ece450c5b569313f68139e64cd00d6ae8ac186e6
refs/heads/master
2020-04-06T04:29:04.783494
2014-10-29T18:47:34
2014-10-29T18:47:34
18,773,495
2
0
null
null
null
null
UTF-8
C++
false
false
849
h
#ifndef POINT3D_H #define POINT3D_H /** * @file point3d.h * @brief point in 3D */ #include "vector3d.h" /** * @brief Point in 3D */ class Point3D: public Vector3D{ public: /** * @brief Constructor */ Point3D(){} /** * @brief Constructor * @param v another point or vector */ Point3D(Vector3D v){ x = v.x; y = v.y; z = v.z; } /** * @brief Constructor * @param v pointer of another point or vector */ Point3D(Vector3D* v){ x = v->x; y = v->y; z = v->z; } /** * @brief Constructor * @param x coordinate x * @param y coordinate y * @param z coordinate z */ Point3D(double x, double y, double z){ this->x = x; this->y = y; this->z = z; } }; #endif // POINT3D_H
[ "foolchi@outlook.com" ]
foolchi@outlook.com
135313a61ae71ffea82ee4b752754c9f139af19c
e1e43f3e90aa96d758be7b7a8356413a61a2716f
/datacommsserver/esockserver/test/TE_Socket/SocketTestSection19.h
a4169563cd523b14f8d4ca9f5a5e0de195e37365
[]
no_license
SymbianSource/oss.FCL.sf.os.commsfw
76b450b5f52119f6bf23ae8a5974c9a09018fdfa
bc8ac1a6d5273cbfa7852bbb8ce27d6ddc076984
refs/heads/master
2021-01-18T23:55:06.285537
2010-10-03T23:21:43
2010-10-03T23:21:43
72,773,202
0
1
null
null
null
null
UTF-8
C++
false
false
890
h
// Copyright (c) 1997-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // #if (!defined __SOCKETTEST_18_H) #define __SOCKETTEST_19_H #include "TestStepSocket.h" class CSocketTest19_1 : public CSocketTestStep_OOMCapable { public: static const TDesC& GetTestName(); virtual enum TVerdict InternalDoTestStepL(); }; class CSocketTest19_2 : public CSocketTestStep_OOMCapable { public: static const TDesC& GetTestName(); virtual enum TVerdict InternalDoTestStepL(); }; #endif //(__SOCKETTEST_19_H)
[ "kirill.dremov@nokia.com" ]
kirill.dremov@nokia.com
00a07b33bbbfab4517c14027d842051dcacbfda9
33d9ed93403ae8aab5c043afa138a331020203d1
/src/can/canread.cpp
709b0f8d66d02241d7ce66098581205173f8d28c
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
dangomc/vi-firmware
47cd544633d481d145d3fbf3f989901fb993955f
d0db9620435af68b32930500296892d37c4e1422
refs/heads/master
2021-01-16T23:02:00.614373
2014-07-15T07:24:31
2014-07-15T07:24:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,107
cpp
#include <stdlib.h> #include <canutil/read.h> #include <pb_encode.h> #include "can/canread.h" #include "config.h" #include "util/log.h" #include "util/timer.h" using openxc::util::log::debug; using openxc::pipeline::MessageClass; using openxc::pipeline::Pipeline; using openxc::config::getConfiguration; using openxc::pipeline::publish; namespace pipeline = openxc::pipeline; namespace time = openxc::util::time; float openxc::can::read::parseSignalBitfield(CanSignal* signal, const CanMessage* message) { return bitfield_parse_float(message->data, CAN_MESSAGE_SIZE, signal->bitPosition, signal->bitSize, signal->factor, signal->offset); } openxc_DynamicField openxc::can::read::noopDecoder(CanSignal* signal, CanSignal* signals, int signalCount, Pipeline* pipeline, float value, bool* send) { return payload::wrapNumber(value); } openxc_DynamicField openxc::can::read::booleanDecoder(CanSignal* signal, CanSignal* signals, int signalCount, Pipeline* pipeline, float value, bool* send) { return payload::wrapBoolean(value == 0.0 ? false : true); } openxc_DynamicField openxc::can::read::ignoreDecoder(CanSignal* signal, CanSignal* signals, int signalCount, Pipeline* pipeline, float value, bool* send) { *send = false; openxc_DynamicField decodedValue = {0}; return decodedValue; } openxc_DynamicField openxc::can::read::stateDecoder(CanSignal* signal, CanSignal* signals, int signalCount, Pipeline* pipeline, float value, bool* send) { openxc_DynamicField decodedValue = {0}; decodedValue.has_type = true; decodedValue.type = openxc_DynamicField_Type_STRING; decodedValue.has_string_value = true; const CanSignalState* signalState = lookupSignalState(value, signal); if(signalState != NULL) { strcpy(decodedValue.string_value, signalState->name); } else { *send = false; } return decodedValue; } static void buildBaseTranslated(openxc_VehicleMessage* message, const char* name) { message->has_type = true; message->type = openxc_VehicleMessage_Type_TRANSLATED; message->has_translated_message = true; message->translated_message = {0}; message->translated_message.has_name = true; strcpy(message->translated_message.name, name); message->translated_message.has_type = true; } void openxc::can::read::publishVehicleMessage(const char* name, openxc_DynamicField* value, openxc_DynamicField* event, openxc::pipeline::Pipeline* pipeline) { openxc_VehicleMessage message = {0}; buildBaseTranslated(&message, name); if(event == NULL) { switch(value->type) { case openxc_DynamicField_Type_STRING: message.translated_message.type = openxc_TranslatedMessage_Type_STRING; break; case openxc_DynamicField_Type_NUM: message.translated_message.type = openxc_TranslatedMessage_Type_NUM; break; case openxc_DynamicField_Type_BOOL: message.translated_message.type = openxc_TranslatedMessage_Type_BOOL; break; } } else { switch(event->type) { case openxc_DynamicField_Type_STRING: message.translated_message.type = openxc_TranslatedMessage_Type_EVENTED_STRING; break; case openxc_DynamicField_Type_NUM: message.translated_message.type = openxc_TranslatedMessage_Type_EVENTED_NUM; break; case openxc_DynamicField_Type_BOOL: message.translated_message.type = openxc_TranslatedMessage_Type_EVENTED_BOOL; break; } } if(value != NULL) { message.translated_message.has_value = true; message.translated_message.value = *value; } if(event != NULL) { message.translated_message.has_event = true; message.translated_message.event = *event; } pipeline::publish(&message, pipeline); } void openxc::can::read::publishVehicleMessage(const char* name, openxc_DynamicField* value, openxc::pipeline::Pipeline* pipeline) { publishVehicleMessage(name, value, NULL, pipeline); } void openxc::can::read::publishNumericalMessage(const char* name, float value, openxc::pipeline::Pipeline* pipeline) { openxc_DynamicField decodedValue = payload::wrapNumber(value); publishVehicleMessage(name, &decodedValue, pipeline); } void openxc::can::read::publishStringMessage(const char* name, const char* value, openxc::pipeline::Pipeline* pipeline) { openxc_DynamicField decodedValue = payload::wrapString(value); publishVehicleMessage(name, &decodedValue, pipeline); } void openxc::can::read::publishBooleanMessage(const char* name, bool value, openxc::pipeline::Pipeline* pipeline) { openxc_DynamicField decodedValue = payload::wrapBoolean(value); publishVehicleMessage(name, &decodedValue, pipeline); } void openxc::can::read::passthroughMessage(CanBus* bus, CanMessage* message, CanMessageDefinition* messages, int messageCount, Pipeline* pipeline) { bool send = true; CanMessageDefinition* messageDefinition = lookupMessageDefinition(bus, message->id, message->format, messages, messageCount); if(messageDefinition == NULL) { if(registerMessageDefinition(bus, message->id, message->format, messages, messageCount)) { debug("Added new message definition for message %d on bus %d", message->id, bus->address); // else you couldn't add it to the list for some reason, but don't // spam the log about it. } } else if(time::conditionalTick(&messageDefinition->frequencyClock) || (memcmp(message->data, messageDefinition->lastValue, CAN_MESSAGE_SIZE) && messageDefinition->forceSendChanged)) { send = true; } else { send = false; } size_t adjustedSize = message->length == 0 ? CAN_MESSAGE_SIZE : message->length; if(send) { openxc_VehicleMessage vehicleMessage = {0}; vehicleMessage.has_type = true; vehicleMessage.type = openxc_VehicleMessage_Type_RAW; vehicleMessage.has_raw_message = true; vehicleMessage.raw_message = {0}; vehicleMessage.raw_message.has_message_id = true; vehicleMessage.raw_message.message_id = message->id; vehicleMessage.raw_message.has_bus = true; vehicleMessage.raw_message.bus = bus->address; vehicleMessage.raw_message.has_data = true; vehicleMessage.raw_message.data.size = adjustedSize; memcpy(vehicleMessage.raw_message.data.bytes, message->data, adjustedSize); pipeline::publish(&vehicleMessage, pipeline); } if(messageDefinition != NULL) { memcpy(messageDefinition->lastValue, message->data, adjustedSize); } } void openxc::can::read::translateSignal(CanSignal* signal, const CanMessage* message, CanSignal* signals, int signalCount, openxc::pipeline::Pipeline* pipeline) { if(signal == NULL || message == NULL) { return; } float value = parseSignalBitfield(signal, message); bool send = true; // Must call the decoders every time, regardless of if we are going to // decide to send the signal or not. openxc_DynamicField decodedValue = openxc::can::read::decodeSignal(signal, value, signals, signalCount, &send); if(send && shouldSend(signal, value)) { if(send) { openxc::can::read::publishVehicleMessage(signal->genericName, &decodedValue, pipeline); } } signal->lastValue = value; } bool openxc::can::read::shouldSend(CanSignal* signal, float value) { bool send = true; if(time::conditionalTick(&signal->frequencyClock) || (value != signal->lastValue && signal->forceSendChanged)) { if(send && (!signal->received || signal->sendSame || value != signal->lastValue)) { signal->received = true; } else { send = false; } } else { send = false; } return send; } openxc_DynamicField openxc::can::read::decodeSignal(CanSignal* signal, float value, CanSignal* signals, int signalCount, bool* send) { SignalDecoder decoder = signal->decoder == NULL ? noopDecoder : signal->decoder; openxc_DynamicField decodedValue = decoder(signal, signals, signalCount, NULL, value, send); return decodedValue; } openxc_DynamicField openxc::can::read::decodeSignal(CanSignal* signal, const CanMessage* message, CanSignal* signals, int signalCount, bool* send) { float value = parseSignalBitfield(signal, message); return decodeSignal(signal, value, signals, signalCount, send); }
[ "chris.peplin@rhubarbtech.com" ]
chris.peplin@rhubarbtech.com
d9e1e67c4dde2a2e270f8ff3a36f262ce5f2b4fd
0642f612dfc7c357dfd4972a67499793cf24f04c
/lims2_modules/common/register/Utilities/ShiftScaleRGBImage.cxx
bc12b3770a81421a55a9d46c2cb9ccb5063cfb75
[ "BSD-2-Clause" ]
permissive
AllenInstitute/stpt_registration
1e0e6dfac5520c841064bcab78e0d541293c7065
a0595c98a7621a6fb1c1408bcd663407f2c59bd3
refs/heads/master
2022-04-03T11:34:18.954147
2020-02-14T05:10:12
2020-02-14T05:10:12
239,768,678
5
1
null
null
null
null
UTF-8
C++
false
false
2,895
cxx
/*========================================================================= ShiftScaleRGBImage.cxx Copyright (c) Allen Institute for Brain Science. All rights reserved. =========================================================================*/ #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkRGBPixel.h" #include <string> #include "itkNthElementPixelAccessor.h" #include "itkShiftScaleImageFilter.h" #include "itkImageAdaptor.h" #include "itkImageRegionIterator.h" #include <vector> int main( int argc, char *argv[] ) { if (argc < 5 ) { std::cout << "Usage: " << argv[0] << " "; std::cout << "inputImage outputImage shift scale"; std::cout << std::endl; return EXIT_FAILURE; } typedef itk::RGBPixel< unsigned char > PixelType; typedef itk::Image< PixelType, 2 > ImageType; typedef itk::Image< unsigned char, 2 > UCharImageType; std::string inputFile = argv[1]; std::string outputFile = argv[2]; double shift = atof( argv[3] ); double scale = atof( argv[4] ); try { typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( inputFile.c_str() ); reader->Update(); ImageType::Pointer image = reader->GetOutput(); image->DisconnectPipeline(); ImageType::RegionType region = image->GetBufferedRegion(); typedef itk::NthElementPixelAccessor< unsigned char, PixelType > AccessorType; typedef itk::ImageAdaptor< ImageType, AccessorType > AdaptorType; typedef itk::ShiftScaleImageFilter< AdaptorType, UCharImageType > FilterType; for ( int k = 0; k < 3; k++ ) { AdaptorType::Pointer adaptor = AdaptorType::New(); adaptor->SetImage( image ); adaptor->GetPixelAccessor().SetElementNumber( k ); FilterType::Pointer filter = FilterType::New(); filter->SetInput( adaptor ); filter->SetShift( shift ); filter->SetScale( scale ); filter->Update(); typedef itk::ImageRegionIterator< UCharImageType > InputIterator; typedef itk::ImageRegionIterator< ImageType > OutputIterator; InputIterator it( filter->GetOutput(), region ); OutputIterator ot( image, region ); while( !it.IsAtEnd() ) { PixelType p = ot.Get(); p[k] = it.Get(); ot.Set( p ); ++it; ++ot; } } typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetInput( image ); writer->SetFileName( outputFile.c_str() ); writer->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << excp << std::endl; return EXIT_FAILURE; } catch( ... ) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
[ "lydian@alleninstitute.org" ]
lydian@alleninstitute.org
3b59f94d244bb1cb861c25a3de2dc6c02496544b
9e02c151f257584592d7374b0045196a3fd2cf53
/AtCoder/ABC/124/A.cpp
3475bd9891933027d3d6a625664f3df47dc84749
[]
no_license
robertcal/cpp_competitive_programming
891c97f315714a6b1fc811f65f6be361eb642ef2
0bf5302f1fb2aa8f8ec352d83fa6281f73dec9b5
refs/heads/master
2021-12-13T18:12:31.930186
2021-09-29T00:24:09
2021-09-29T00:24:09
173,748,291
0
0
null
null
null
null
UTF-8
C++
false
false
315
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 1e9; const int MOD = 1e9 + 7; const ll LINF = 1e18; int main() { int a, b; cin >> a >> b; int ma = max(a, b); if (a == b) { cout << ma + ma << endl; } else { cout << ma + ma - 1 << endl; } }
[ "robertcal900@gmail.com" ]
robertcal900@gmail.com
b6725485d9e8dd9f4a31ee99c331b53333f3c3a8
9c0987e2a040902a82ed04d5e788a074a2161d2f
/cpp/platform/impl/windows/generated/winrt/impl/Windows.Data.Xml.Xsl.1.h
1bc559c43fd3c78b522114571a230927d9e6a696
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
l1kw1d/nearby-connections
ff9119338a6bd3e5c61bc2c93d8d28b96e5ebae5
ea231c7138d3dea8cd4cd75692137e078cbdd73d
refs/heads/master
2023-06-15T04:15:54.683855
2021-07-12T23:05:16
2021-07-12T23:06:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,887
h
// Copyright 2020 Google LLC // // 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 // // https://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. // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.210505.3 #ifndef WINRT_Windows_Data_Xml_Xsl_1_H #define WINRT_Windows_Data_Xml_Xsl_1_H #include "winrt/impl/Windows.Data.Xml.Xsl.0.h" WINRT_EXPORT namespace winrt::Windows::Data::Xml::Xsl { struct __declspec(empty_bases) IXsltProcessor : winrt::Windows::Foundation::IInspectable, impl::consume_t<IXsltProcessor> { IXsltProcessor(std::nullptr_t = nullptr) noexcept {} IXsltProcessor(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IXsltProcessor(IXsltProcessor const&) noexcept = default; IXsltProcessor(IXsltProcessor&&) noexcept = default; IXsltProcessor& operator=(IXsltProcessor const&) & noexcept = default; IXsltProcessor& operator=(IXsltProcessor&&) & noexcept = default; }; struct __declspec(empty_bases) IXsltProcessor2 : winrt::Windows::Foundation::IInspectable, impl::consume_t<IXsltProcessor2> { IXsltProcessor2(std::nullptr_t = nullptr) noexcept {} IXsltProcessor2(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IXsltProcessor2(IXsltProcessor2 const&) noexcept = default; IXsltProcessor2(IXsltProcessor2&&) noexcept = default; IXsltProcessor2& operator=(IXsltProcessor2 const&) & noexcept = default; IXsltProcessor2& operator=(IXsltProcessor2&&) & noexcept = default; }; struct __declspec(empty_bases) IXsltProcessorFactory : winrt::Windows::Foundation::IInspectable, impl::consume_t<IXsltProcessorFactory> { IXsltProcessorFactory(std::nullptr_t = nullptr) noexcept {} IXsltProcessorFactory(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} IXsltProcessorFactory(IXsltProcessorFactory const&) noexcept = default; IXsltProcessorFactory(IXsltProcessorFactory&&) noexcept = default; IXsltProcessorFactory& operator=(IXsltProcessorFactory const&) & noexcept = default; IXsltProcessorFactory& operator=(IXsltProcessorFactory&&) & noexcept = default; }; } #endif
[ "copybara-worker@google.com" ]
copybara-worker@google.com
f28ff41c6ab3b64ca1762fcb1233b0fbc7c9855d
5d2df4909b9fe75fc038cbfb5b39c4701c7289f5
/DS/infix_2_postfix/infix_2_postfix/Source.cpp
5a578e33b043dfd251cc23a584ff55f5640b9af8
[]
no_license
rameshkrishna0805/ncrwork-1
021aaa8a9032952f7f2939b3f5dfb74829ca258f
0455a5c9d5abeb04716ed9c6c11f18083a574cc3
refs/heads/master
2020-04-27T09:04:32.080382
2019-03-06T17:53:23
2019-03-06T17:53:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,009
cpp
#include<iostream> using namespace std; int prec(char c) { if (c == '*' || c == '/') return 10; else if (c == '+' || c == '-') return 9; else if (c == '{' || c == '(' || c == '[') return 15; else return 0; } struct stack1 { int size; char *s; int top; }; class stack2 { stack1 stk; public: stack2() { stk.size = 0; stk.s = NULL; stk.top = -1; } void getsize(int n) { stk.size = n; stk.s = new char[n]; } void push(char ele) { if (!IsFull()) stk.s[++stk.top] = ele; else cout << "Overflow" << endl; } bool IsFull() { /*cout << stk.size << endl; cout << stk.top;*/ return(stk.top == (stk.size - 1)); } char pop() { if (!Isempty()) return(stk.s[stk.top--]); else cout << "UnderflowA"; } bool Isempty() { return (stk.top == -1); } char peek() { return(stk.s[stk.top]); } void display() { for (int i = 0; i <= stk.top; i++) cout << stk.s[i] << endl; } char getele(int n) { return(stk.s[n]); } int givetop() { return stk.top; } }; void main() { stack2 st; int j= 0,size,c=0; char str[20],ch,strop[20]; cout << "Enter the string"; cin >> str; cout << "Enter the size"; cin >> size; st.getsize(size); for (int i = 0; i < strlen(str); i++) { ch = str[i]; if (isalpha(ch)) { //cout << "hello"; strop[j] = ch; j++; } else { if (st.Isempty()) { //cout << "hello"; st.push(ch); } else if (ch == ')') { while (st.peek() != '(' && !st.Isempty()) { strop[j] = st.pop(); //cout << strop[j] << endl; j++; } st.pop(); } else if ((prec(st.peek()) >= prec(ch))) { while ((prec(st.peek()) >= prec(ch))) { strop[j] = st.pop(); j++; } st.push(ch); } else { st.push(ch); cout << "pushed-----" << ch << endl; st.display(); } } } while (!st.Isempty()) { strop[j] = st.pop(); j++; } c = j; //cout << "j=" << j << endl; for (j = 0;j<c ; j++) cout << strop[j]; system("pause"); }
[ "nsragvi@gmail.com" ]
nsragvi@gmail.com
c9d2f693c978b1f56b2e404ad52333269b624161
804cc6764d90fdd7424fa435126c7fe581111562
/AK/JsonParser.h
e8d3c5181d78aea7e989bb74f2e9dd0a33894b8b
[ "BSD-2-Clause" ]
permissive
NukeWilliams/prana-os
96abeed02f33f87c74dd066a5fa7b2d501cb2c62
c56c230d3001a48c342361733dc634a5afaf35f9
refs/heads/master
2023-06-17T18:39:22.394466
2021-07-02T13:37:47
2021-07-02T13:37:47
358,167,671
1
0
null
null
null
null
UTF-8
C++
false
false
831
h
/* * Copyright (c) 2018-2020, krishpranav <krisna.pranav@gmail.com> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <AK/GenericLexer.h> #include <AK/JsonValue.h> namespace AK { class JsonParser : private GenericLexer { public: explicit JsonParser(const StringView& input) : GenericLexer(input) { } Optional<JsonValue> parse(); private: Optional<JsonValue> parse_helper(); String consume_and_unescape_string(); Optional<JsonValue> parse_array(); Optional<JsonValue> parse_object(); Optional<JsonValue> parse_number(); Optional<JsonValue> parse_string(); Optional<JsonValue> parse_false(); Optional<JsonValue> parse_true(); Optional<JsonValue> parse_null(); String m_last_string_starting_with_character[256]; }; } using AK::JsonParser;
[ "krisna.pranav@gmail.com" ]
krisna.pranav@gmail.com
094c1117798df575b47b8296e2927b70e17a1ca2
686a7ce0b37872bacaa4ebf6c394774e29d3a058
/src/main/native/include/boost-ext/test/teamcity_boost.hpp
cdc159bb890db3ca7652bd8216dd3bd7b1157ca0
[ "MIT", "Apache-2.0" ]
permissive
darcyg/boost-ext
042e7cd6662ed5d7d3c8b37194675fd225cae125
443e3584778960a33422a61f398a6af2fa065beb
refs/heads/master
2021-01-16T17:46:43.829411
2014-05-20T19:41:14
2014-05-20T19:41:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,114
hpp
/* Copyright 2011 JetBrains s.r.o. * * 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. * * $Revision: 88625 $ */ #ifndef H_TEAMCITY_BOOST #define H_TEAMCITY_BOOST #include <boost/test/results_collector.hpp> #include <boost/test/unit_test.hpp> #include <boost/test/unit_test_log_formatter.hpp> #include "boost-ext/test/teamcity_messages.hpp" using namespace boost::unit_test; namespace JetBrains { // Custom formatter for TeamCity messages class TeamcityBoostLogFormatter: public boost::unit_test::unit_test_log_formatter { TeamcityMessages messages; std::string currentDetails; std::string flowId; std::string toString(const_string bstr) { std::stringstream ss; ss << bstr; return ss.str(); } public: TeamcityBoostLogFormatter(const std::string &_flowId) : flowId(_flowId) {} TeamcityBoostLogFormatter() : flowId(getFlowIdFromEnvironment()) {} void log_start(std::ostream&, boost::unit_test::counter_t test_cases_amount) {} void log_finish(std::ostream&) {} void log_build_info(std::ostream&) {} void test_unit_start(std::ostream &out, boost::unit_test::test_unit const& tu) { messages.setOutput(out); if (tu.p_type == tut_case) { messages.testStarted(tu.p_name, flowId); } else { messages.suiteStarted(tu.p_name, flowId); } currentDetails.clear(); } void test_unit_finish(std::ostream &out, boost::unit_test::test_unit const& tu, unsigned long elapsed) { messages.setOutput(out); test_results const& tr = results_collector.results(tu.p_id); if (tu.p_type == tut_case) { if(!tr.passed()) { if(tr.p_skipped) { messages.testIgnored(tu.p_name, "ignored", flowId); } else if (tr.p_aborted) { messages.testFailed(tu.p_name, "aborted", currentDetails, flowId); } else { messages.testFailed(tu.p_name, "failed", currentDetails, flowId); } } messages.testFinished(tu.p_name, elapsed / 1000, flowId); } else { messages.suiteFinished(tu.p_name, flowId); } } void test_unit_skipped(std::ostream&, boost::unit_test::test_unit const& tu) {} void log_exception(std::ostream &out, boost::unit_test::log_checkpoint_data const&, boost::unit_test::const_string explanation) { std::string what = toString(explanation); out << what << std::endl; currentDetails += what + "\n"; } void log_entry_start(std::ostream&, boost::unit_test::log_entry_data const&, log_entry_types let) {} void log_entry_value(std::ostream &out, boost::unit_test::const_string value) { out << value; currentDetails += toString(value); } void log_entry_finish(std::ostream &out) { out << std::endl; currentDetails += "\n"; } }; // Fake fixture to register formatter struct TeamcityFormatterRegistrar { TeamcityFormatterRegistrar() { if (JetBrains::underTeamcity()) { boost::unit_test::unit_test_log.set_formatter(new JetBrains::TeamcityBoostLogFormatter()); boost::unit_test::unit_test_log.set_threshold_level(boost::unit_test::log_successful_tests); } } }; #ifdef BOOST_TEST_MODULE BOOST_GLOBAL_FIXTURE(TeamcityFormatterRegistrar); #endif } #endif /* H_TEAMCITY_BOOST */
[ "nathan@toonetown.com" ]
nathan@toonetown.com
0954cfa1980e360b2d290e5a4bf46a98ae90ca56
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/content/browser/ssl/ssl_manager.cc
d4f90426f971e3c8c5c313573c162e8d7c37ec98
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
17,099
cc
// Copyright (c) 2012 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 "content/browser/ssl/ssl_manager.h" #include <set> #include <utility> #include "base/bind.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/supports_user_data.h" #include "content/browser/devtools/devtools_agent_host_impl.h" #include "content/browser/devtools/protocol/security_handler.h" #include "content/browser/frame_host/navigation_entry_impl.h" #include "content/browser/loader/resource_dispatcher_host_impl.h" #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/ssl/ssl_error_handler.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/certificate_request_result_type.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/ssl_host_state_delegate.h" #include "content/public/common/console_message_level.h" #include "net/url_request/url_request.h" namespace content { namespace { const char kSSLManagerKeyName[] = "content_ssl_manager"; // Events for UMA. Do not reorder or change! enum SSLGoodCertSeenEvent { NO_PREVIOUS_EXCEPTION = 0, HAD_PREVIOUS_EXCEPTION = 1, SSL_GOOD_CERT_SEEN_EVENT_MAX = 2 }; void OnAllowCertificateWithRecordDecision( bool record_decision, const base::Callback<void(bool, content::CertificateRequestResultType)>& callback, CertificateRequestResultType decision) { callback.Run(record_decision, decision); } void OnAllowCertificate(SSLErrorHandler* handler, SSLHostStateDelegate* state_delegate, bool record_decision, CertificateRequestResultType decision) { DCHECK(handler->ssl_info().is_valid()); switch (decision) { case CERTIFICATE_REQUEST_RESULT_TYPE_CONTINUE: // Note that we should not call SetMaxSecurityStyle here, because // the active NavigationEntry has just been deleted (in // HideInterstitialPage) and the new NavigationEntry will not be // set until DidNavigate. This is ok, because the new // NavigationEntry will have its max security style set within // DidNavigate. // // While AllowCert() executes synchronously on this thread, // ContinueRequest() gets posted to a different thread. Calling // AllowCert() first ensures deterministic ordering. if (record_decision && state_delegate) { state_delegate->AllowCert(handler->request_url().host(), *handler->ssl_info().cert.get(), handler->cert_error()); } handler->ContinueRequest(); return; case CERTIFICATE_REQUEST_RESULT_TYPE_DENY: handler->DenyRequest(); return; case CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL: handler->CancelRequest(); return; } } class SSLManagerSet : public base::SupportsUserData::Data { public: SSLManagerSet() { } std::set<SSLManager*>& get() { return set_; } private: std::set<SSLManager*> set_; DISALLOW_COPY_AND_ASSIGN(SSLManagerSet); }; void HandleSSLErrorOnUI( const base::Callback<WebContents*(void)>& web_contents_getter, const base::WeakPtr<SSLErrorHandler::Delegate>& delegate, const ResourceType resource_type, const GURL& url, const net::SSLInfo& ssl_info, bool fatal) { content::WebContents* web_contents = web_contents_getter.Run(); std::unique_ptr<SSLErrorHandler> handler(new SSLErrorHandler( web_contents, delegate, resource_type, url, ssl_info, fatal)); if (!web_contents) { // Requests can fail to dispatch because they don't have a WebContents. See // https://crbug.com/86537. In this case we have to make a decision in this // function, so we ignore revocation check failures. if (net::IsCertStatusMinorError(ssl_info.cert_status)) { handler->ContinueRequest(); } else { handler->CancelRequest(); } return; } NavigationControllerImpl* controller = static_cast<NavigationControllerImpl*>(&web_contents->GetController()); controller->SetPendingNavigationSSLError(true); SSLManager* manager = controller->ssl_manager(); manager->OnCertError(std::move(handler)); } } // namespace // static void SSLManager::OnSSLCertificateError( const base::WeakPtr<SSLErrorHandler::Delegate>& delegate, const ResourceType resource_type, const GURL& url, const base::Callback<WebContents*(void)>& web_contents_getter, const net::SSLInfo& ssl_info, bool fatal) { DCHECK(delegate.get()); DVLOG(1) << "OnSSLCertificateError() cert_error: " << net::MapCertStatusToNetError(ssl_info.cert_status) << " resource_type: " << resource_type << " url: " << url.spec() << " cert_status: " << std::hex << ssl_info.cert_status; // A certificate error occurred. Construct a SSLErrorHandler object // on the UI thread for processing. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::BindOnce(&HandleSSLErrorOnUI, web_contents_getter, delegate, resource_type, url, ssl_info, fatal)); } // static void SSLManager::OnSSLCertificateSubresourceError( const base::WeakPtr<SSLErrorHandler::Delegate>& delegate, const GURL& url, int render_process_id, int render_frame_id, const net::SSLInfo& ssl_info, bool fatal) { OnSSLCertificateError(delegate, RESOURCE_TYPE_SUB_RESOURCE, url, base::Bind(&WebContentsImpl::FromRenderFrameHostID, render_process_id, render_frame_id), ssl_info, fatal); } SSLManager::SSLManager(NavigationControllerImpl* controller) : controller_(controller), ssl_host_state_delegate_( controller->GetBrowserContext()->GetSSLHostStateDelegate()) { DCHECK(controller_); SSLManagerSet* managers = static_cast<SSLManagerSet*>( controller_->GetBrowserContext()->GetUserData(kSSLManagerKeyName)); if (!managers) { auto managers_owned = base::MakeUnique<SSLManagerSet>(); managers = managers_owned.get(); controller_->GetBrowserContext()->SetUserData(kSSLManagerKeyName, std::move(managers_owned)); } managers->get().insert(this); } SSLManager::~SSLManager() { SSLManagerSet* managers = static_cast<SSLManagerSet*>( controller_->GetBrowserContext()->GetUserData(kSSLManagerKeyName)); managers->get().erase(this); } void SSLManager::DidCommitProvisionalLoad(const LoadCommittedDetails& details) { NavigationEntryImpl* entry = controller_->GetLastCommittedEntry(); int add_content_status_flags = 0; int remove_content_status_flags = 0; if (!details.is_main_frame) { // If it wasn't a main-frame navigation, then carry over content // status flags. (For example, the mixed content flag shouldn't // clear because of a frame navigation.) NavigationEntryImpl* previous_entry = controller_->GetEntryAtIndex(details.previous_entry_index); if (previous_entry) { add_content_status_flags = previous_entry->GetSSL().content_status; } } else if (!details.is_same_document) { // For main-frame non-same-page navigations, clear content status // flags. These flags are set based on the content on the page, and thus // should reflect the current content, even if the navigation was to an // existing entry that already had content status flags set. remove_content_status_flags = ~0; // Also clear any UserData from the SSLStatus. if (entry) entry->GetSSL().user_data = nullptr; } if (!UpdateEntry(entry, add_content_status_flags, remove_content_status_flags)) { // Ensure the WebContents is notified that the SSL state changed when a // load is committed, in case the active navigation entry has changed. NotifyDidChangeVisibleSSLState(); } } void SSLManager::DidDisplayMixedContent() { UpdateLastCommittedEntry(SSLStatus::DISPLAYED_INSECURE_CONTENT, 0); } void SSLManager::DidContainInsecureFormAction() { UpdateLastCommittedEntry(SSLStatus::DISPLAYED_FORM_WITH_INSECURE_ACTION, 0); } void SSLManager::DidDisplayContentWithCertErrors() { NavigationEntryImpl* entry = controller_->GetLastCommittedEntry(); if (!entry) return; // Only record information about subresources with cert errors if the // main page is HTTPS with a certificate. if (entry->GetURL().SchemeIsCryptographic() && entry->GetSSL().certificate) { UpdateLastCommittedEntry(SSLStatus::DISPLAYED_CONTENT_WITH_CERT_ERRORS, 0); } } void SSLManager::DidShowPasswordInputOnHttp() { UpdateLastCommittedEntry(SSLStatus::DISPLAYED_PASSWORD_FIELD_ON_HTTP, 0); } void SSLManager::DidHideAllPasswordInputsOnHttp() { UpdateLastCommittedEntry(0, SSLStatus::DISPLAYED_PASSWORD_FIELD_ON_HTTP); } void SSLManager::DidShowCreditCardInputOnHttp() { UpdateLastCommittedEntry(SSLStatus::DISPLAYED_CREDIT_CARD_FIELD_ON_HTTP, 0); } void SSLManager::DidRunMixedContent(const GURL& security_origin) { NavigationEntryImpl* entry = controller_->GetLastCommittedEntry(); if (!entry) return; SiteInstance* site_instance = entry->site_instance(); if (!site_instance) return; if (ssl_host_state_delegate_) { ssl_host_state_delegate_->HostRanInsecureContent( security_origin.host(), site_instance->GetProcess()->GetID(), SSLHostStateDelegate::MIXED_CONTENT); } UpdateEntry(entry, 0, 0); NotifySSLInternalStateChanged(controller_->GetBrowserContext()); } void SSLManager::DidRunContentWithCertErrors(const GURL& security_origin) { NavigationEntryImpl* entry = controller_->GetLastCommittedEntry(); if (!entry) return; SiteInstance* site_instance = entry->site_instance(); if (!site_instance) return; if (ssl_host_state_delegate_) { ssl_host_state_delegate_->HostRanInsecureContent( security_origin.host(), site_instance->GetProcess()->GetID(), SSLHostStateDelegate::CERT_ERRORS_CONTENT); } UpdateEntry(entry, 0, 0); NotifySSLInternalStateChanged(controller_->GetBrowserContext()); } void SSLManager::OnCertError(std::unique_ptr<SSLErrorHandler> handler) { bool expired_previous_decision = false; // First we check if we know the policy for this error. DCHECK(handler->ssl_info().is_valid()); SSLHostStateDelegate::CertJudgment judgment = ssl_host_state_delegate_ ? ssl_host_state_delegate_->QueryPolicy( handler->request_url().host(), *handler->ssl_info().cert.get(), handler->cert_error(), &expired_previous_decision) : SSLHostStateDelegate::DENIED; if (judgment == SSLHostStateDelegate::ALLOWED) { handler->ContinueRequest(); return; } DCHECK(net::IsCertificateError(handler->cert_error())); if (handler->cert_error() == net::ERR_CERT_NO_REVOCATION_MECHANISM || handler->cert_error() == net::ERR_CERT_UNABLE_TO_CHECK_REVOCATION) { handler->ContinueRequest(); return; } OnCertErrorInternal(std::move(handler), expired_previous_decision); } void SSLManager::DidStartResourceResponse(const GURL& url, bool has_certificate, net::CertStatus ssl_cert_status) { if (has_certificate && url.SchemeIsCryptographic() && !net::IsCertStatusError(ssl_cert_status)) { // If the scheme is https: or wss: *and* the security info for the // cert has been set (i.e. the cert id is not 0) and the cert did // not have any errors, revoke any previous decisions that // have occurred. If the cert info has not been set, do nothing since it // isn't known if the connection was actually a valid connection or if it // had a cert error. SSLGoodCertSeenEvent event = NO_PREVIOUS_EXCEPTION; if (ssl_host_state_delegate_ && ssl_host_state_delegate_->HasAllowException(url.host())) { // If there's no certificate error, a good certificate has been seen, so // clear out any exceptions that were made by the user for bad // certificates. This intentionally does not apply to cached resources // (see https://crbug.com/634553 for an explanation). ssl_host_state_delegate_->RevokeUserAllowExceptions(url.host()); event = HAD_PREVIOUS_EXCEPTION; } UMA_HISTOGRAM_ENUMERATION("interstitial.ssl.good_cert_seen", event, SSL_GOOD_CERT_SEEN_EVENT_MAX); } } void SSLManager::OnCertErrorInternal(std::unique_ptr<SSLErrorHandler> handler, bool expired_previous_decision) { WebContents* web_contents = handler->web_contents(); int cert_error = handler->cert_error(); const net::SSLInfo& ssl_info = handler->ssl_info(); const GURL& request_url = handler->request_url(); ResourceType resource_type = handler->resource_type(); bool fatal = handler->fatal(); base::Callback<void(bool, content::CertificateRequestResultType)> callback = base::Bind(&OnAllowCertificate, base::Owned(handler.release()), ssl_host_state_delegate_); DevToolsAgentHostImpl* agent_host = static_cast<DevToolsAgentHostImpl*>( DevToolsAgentHost::GetOrCreateFor(web_contents).get()); if (agent_host) { for (auto* security_handler : protocol::SecurityHandler::ForAgentHost(agent_host)) { if (security_handler->NotifyCertificateError( cert_error, request_url, base::Bind(&OnAllowCertificateWithRecordDecision, false, callback))) { return; } } } GetContentClient()->browser()->AllowCertificateError( web_contents, cert_error, ssl_info, request_url, resource_type, fatal, expired_previous_decision, base::Bind(&OnAllowCertificateWithRecordDecision, true, callback)); } bool SSLManager::UpdateEntry(NavigationEntryImpl* entry, int add_content_status_flags, int remove_content_status_flags) { // We don't always have a navigation entry to update, for example in the // case of the Web Inspector. if (!entry) return false; SSLStatus original_ssl_status = entry->GetSSL(); // Copy! entry->GetSSL().initialized = true; entry->GetSSL().content_status &= ~remove_content_status_flags; entry->GetSSL().content_status |= add_content_status_flags; SiteInstance* site_instance = entry->site_instance(); // Note that |site_instance| can be NULL here because NavigationEntries don't // necessarily have site instances. Without a process, the entry can't // possibly have insecure content. See bug https://crbug.com/12423. if (site_instance && ssl_host_state_delegate_) { std::string host = entry->GetURL().host(); int process_id = site_instance->GetProcess()->GetID(); if (ssl_host_state_delegate_->DidHostRunInsecureContent( host, process_id, SSLHostStateDelegate::MIXED_CONTENT)) { entry->GetSSL().content_status |= SSLStatus::RAN_INSECURE_CONTENT; } // Only record information about subresources with cert errors if the // main page is HTTPS with a certificate. if (entry->GetURL().SchemeIsCryptographic() && entry->GetSSL().certificate && ssl_host_state_delegate_->DidHostRunInsecureContent( host, process_id, SSLHostStateDelegate::CERT_ERRORS_CONTENT)) { entry->GetSSL().content_status |= SSLStatus::RAN_CONTENT_WITH_CERT_ERRORS; } } if (entry->GetSSL().initialized != original_ssl_status.initialized || entry->GetSSL().content_status != original_ssl_status.content_status) { NotifyDidChangeVisibleSSLState(); return true; } return false; } void SSLManager::UpdateLastCommittedEntry(int add_content_status_flags, int remove_content_status_flags) { NavigationEntryImpl* entry = controller_->GetLastCommittedEntry(); if (!entry) return; UpdateEntry(entry, add_content_status_flags, remove_content_status_flags); } void SSLManager::NotifyDidChangeVisibleSSLState() { WebContentsImpl* contents = static_cast<WebContentsImpl*>(controller_->delegate()->GetWebContents()); contents->DidChangeVisibleSecurityState(); } // static void SSLManager::NotifySSLInternalStateChanged(BrowserContext* context) { SSLManagerSet* managers = static_cast<SSLManagerSet*>(context->GetUserData(kSSLManagerKeyName)); for (std::set<SSLManager*>::iterator i = managers->get().begin(); i != managers->get().end(); ++i) { (*i)->UpdateEntry((*i)->controller()->GetLastCommittedEntry(), 0, 0); } } } // namespace content
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
57966081549b9aea3853eca62953d50c2871f58b
76fccfc285e60e37ba315e5b283e220f7538102d
/Xtra/XDK/Include/driservc.h
2deb6db0b7c5b7546fc1d7f9fbd69bfef3a3c310
[]
no_license
lb90/walnut-xtra
fad41ecac313200a5fd48be3327398838282dbd6
f68673c8399077e8ac31723f4c44bc2287ceab2c
refs/heads/master
2022-02-18T21:47:09.347873
2019-08-03T16:38:12
2019-08-03T16:38:12
197,606,335
1
0
null
null
null
null
UTF-8
C++
false
false
171,564
h
/* ADOBE SYSTEMS INCORPORATED Copyright 1994 - 2008 Adobe Macromedia Software LLC All Rights Reserved NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms of the Adobe license agreement accompanying it. If you have received this file from a source other than Adobe, then your use, modification, or distribution of it requires the prior written permission of Adobe. */ #ifndef NO_PRAGMA_ONCE #pragma once #endif /**************************************************************************** / / Purpose / Director services callback interface definitions. / Director-specific common interface defintions. / ****************************************************************************/ #ifndef DRISERVC_H #define DRISERVC_H #ifdef PRECOMPILED_HEADER #error "moaxtra.h should not be precompiled" #endif #include "drtypes.h" #include "mmiservc.h" #include "MIXSND.H" #ifdef __cplusplus extern "C" { #endif struct IMoaDrScoreAccess; struct IMoaDrMovie; /* ---------------------------------------------------------------------------- / / Director specific notification types / / -------------------------------------------------------------------------- */ DEFINE_GUID(NID_DrNCastMemberModified, 0x010840D0L, 0x3E12, 0x11D0, 0x99, 0xA6, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNCastSelectionChanged, 0x03F13356L, 0x3E12, 0x11D0, 0x99, 0xA6, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNScoreModified, 0x065EBFA0L, 0x3E12, 0x11D0, 0x99, 0xA6, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNScoreSelectionChanged, 0x092315BAL, 0x3E12, 0x11D0, 0x99, 0xA6, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNCuePointPassed, 0x66C0FB00L, 0x46C9, 0x11D0, 0xBD, 0xEB, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNPaletteChanged, 0x0FF83488L, 0x3E12, 0x11D0, 0x99, 0xA6, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNStep, 0x12ABC686L, 0x3E12, 0x11D0, 0x99, 0xA6, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNIdle, 0x3B881B5EL, 0x3E12, 0x11D0, 0x99, 0xA6, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNDocumentOpened, 0x90366D2CL, 0x5CB2, 0x11D0, 0xA1, 0xBD, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNDocumentClosed, 0xA7B849FCL, 0x5CB2, 0x11D0, 0xA1, 0xBD, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); DEFINE_GUID(NID_DrNAnimationState, 0x8338a8ea, 0x7ae8, 0x11d3, 0xb3, 0xdd, 0x40, 0x2, 0xcf, 0x0, 0x0, 0x0); DEFINE_GUID(NID_DrNRewind, 0x1c155800, 0xab70, 0x11d4, 0xa6, 0x15, 0x0, 0x1, 0x2, 0x67, 0x22, 0x1a); DEFINE_GUID(NID_DrNEnteringDebugger, 0x403a1c31, 0x2a8, 0x11d5, 0xa6, 0x5, 0x0, 0x1, 0x2, 0x75, 0xa8, 0x85); DEFINE_GUID(NID_DrNLeavingDebugger, 0x403a1c33, 0x2a8, 0x11d5, 0xa6, 0x5, 0x0, 0x1, 0x2, 0x75, 0xa8, 0x85); //{95A08D02-4F2A-11B2-A62D-003065838ECE} DEFINE_GUID(NID_DrNStageWindowOpen, 0x95A08D02, 0x4F2A, 0x11B2, 0xa6, 0x2D, 0x00, 0x30, 0x65, 0x83, 0x8E, 0xCE); //{1B8E63BD-501E-11B2-9434-003065838ECE} DEFINE_GUID(NID_DrNStageWindowClose, 0x1B8E63BD, 0x501E, 0x11B2, 0x94, 0x34, 0x00, 0x30, 0x65, 0x83, 0x8E, 0xCE); /* ---------------------------------------------------------------------------- / / IMoaDrMediaOwner / / -------------------------------------------------------------------------- */ /* IID_IMoaDrMediaOwner: AC542D520003AEED00000800072C6326 */ DEFINE_GUID(IID_IMoaDrMediaOwner, 0xAC542D52L, 0x0003, 0xAEED, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrMediaOwner DECLARE_INTERFACE_(IMoaDrMediaOwner, IMoaMmPropOwner) /* Description The IMoaDrMediaOwner interface adds three methods to the IMoaMmPropOwner interface, AttachMedia(), GetMedia(), and SetMedia(). These methods enable an Xtra to retrieve media information from objects such as cast members and movies. Methods of this interface include pointers to a MoaDrMediaInfo structure as parameters. Before a GetMedia(), SetMedia(), or AttachMedia() call, use IMoaDrUtils::NewMediaInfo() to fill out the structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. Using this call forces you to fill out all the needed parameters. The aux information currently applies only when setting image media. The formatSymbol and labelSymbol members of this structure are MoaMmSymbols. These symbols are obtained from strings using the host application symbol dictionary, accessed through the StringToSymbol() method of the IMoaMmUtils interface The labelSymbol refers to the specific chunk of media data you want from the media owner. These labels are generic descriptors for the content media. In the IMoaDrCastMem interface, which inherits from IMoaDrMediaOwner, the labels used are different than the cast member types. For example, a film loop cast member has score media label, a bitmap cast member has an image media label, and so on. These generic labels are used to allow multiple representations for specific media data types. For example, a bitmap is really just one type of image. The formatSymbol refers to the specific media data type you want to get or set. In Director, the media types represented by these sy mbols are largely platform-specific, except for opaque handles and strings. For example, a bitmap cast member provides image media. On the Macintosh, the format for getting and setting this data is a Macintosh PICT. You use the formatSymbol "macPICT" to access this data. On Windows, packed DIBs are supported; you use the formatSymbol "winDIB" to access this data. This mechanism uses symbols rather than hardwired constants for future expansion of media access support. The goal is to allow Xtra media assets to export arbitrary labels and formats of their media to other Xtras. (Currently, Xtras can only access media data of other Xtras through the opaque handle provided by composite media. label. So, for example, in the future, someone may make a 3D plug-in, and other Xtras could use GetMedia() to get the "geometry" (label) media in "DXF" (format)). */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* MoaMmSymbol representing the property to get */ PMoaMmValue pPropValue) /* Pointer to a MoaMmValue to receive the property's value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal err </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other value data </TD></TR> </TABLE> */ /* Description Retrieves the value of a specified property. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* MoaMmSymbol representing the property to set */ ConstPMoaMmValue pPropValue) /* Pointer to a ConstPMoaMmValue containing the property value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists, value ok, couldn't - - internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Couldn't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Couldn't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: MoaRect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef expected </TD></TR> </TABLE> */ /* Description Sets the value of a specified property. */ STDMETHOD(GetMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) PURE; /* Category Media owner methods */ /* Description Gets media data. This method obtains a copy of the media associated with an object. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the media information structure, specifying NULL for the auxfield and kMoaDrMediaOpts_None for the options field. The caller partially populates a MoaDrMediaInfo struct with symbols indicating the requested chunk of media (labelSymbol) and the requested format (formatSymbol). After the call, the mediaDatafield is populated with the requested data; the type of this field depends on the format requested. The caller then owns the data and is responsible for disposing it, if applicable. Typically this data is either a MoaHandle, a Macintosh Handle or Pointer, or a Windows global handle. */ STDMETHOD(SetMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) PURE; /* Category Media owner methods */ /* Description Sets media data. This method copies caller-supplied media data and associates it with an object. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the media information structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the optionsfield. The caller populates a MoaDrMediaInfo structure with symbols indicating the supplied chunk of media (labelSymbol), the supplied format (formatSymbol), and the media data itself (mediaData). If the label and format are supported by the object, a call to this method copies the caller's data and replaces any existing media data for the supplied label for the cast member. Since the data is copied, the caller retains ownership of the media data passed in. Typically, this data is either a MoaHandle, a Macintosh Handle or pointer, or a Windows global handle. */ STDMETHOD(AttachMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) PURE; /* Category Media owner methods */ /* Description Attaches media to an object, releasing it from the caller. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the media information structure, specifying NULL for the auxfield and kMoaDrMediaOpts_Nonefor the options field. On enter, the labelSymbol and formatSymbol fields should be populated with symbols indicating which chunk of media is to be attach (labelSymbol), and what format the media is supplied in (formatSymbol). The mediaData field should hold the data itself (typically a MoaHandle , Macintosh Handle, or Windows global handle) Upon return, if there is no error, the media has changed ownership and belongs to the host application, and should no longer be referenced by the caller. */ }; typedef IMoaDrMediaOwner * PIMoaDrMediaOwner; /* Old synonyms for IMoaDrMediaOwner */ #define IMoaDrPropAndMediaOwner IMoaDrMediaOwner #define PIMoaDrPropAndMediaOwner PIMoaDrMediaOwner #define IID_IMoaDrPropAndMediaOwner IID_IMoaDrMediaOwner /* ---------------------------------------------------------------------------- / / IMoaDrNotificationClient - interface for receiving / notification from the host application. The type / of notification to be received is specified by the / clientType. See DRTYPES.H for the notification / type constants available. / / --------------------------------------------------------------------------- */ /* IID_IMoaDrNotificationClient: ACE09C3101BEE5D2000008000757DC04 */ DEFINE_GUID(IID_IMoaDrNotificationClient, 0xACE09C31L, 0x01BE, 0xE5D2, 0x00, 0x00, 0x08, 0x00, 0x07, 0x57, 0xDC, 0x04); #undef INTERFACE #define INTERFACE IMoaDrNotificationClient DECLARE_INTERFACE_(IMoaDrNotificationClient, IMoaUnknown) /* Description Interface for receiving notification from the host application. The type of notification to be received is specified by the notifyType. See "Types" for the notification type constants available. See IMoaDrUtils::RegisterNotificationClient() and IMoaDrUtils::UnregisterNotificationClient() for information on enabling and disabling callback notification for internal events. The IMoaDrNotificationClient interface consists of the Notify() method. */ { STD_IUNKNOWN_METHODS STDMETHOD(Notify)(THIS_ MoaLong msgCode, /* The MoaLong specifying the type of event that occurred */ PMoaVoid data) PURE; /* Description Handles notification from host application. msgCode specifies the type of event that occurred; a given notificationType can support one or more message codes. refCon is used to pass additional message-specific data from the host application to the notification client. Valid message codes are: kMoaDrMsgCode_DocFileIO <b>Windows(TM) version only</b> Used by notification type kMoaDrNotifyType_DocFileIO. This notification message is sent just before a chunk read or write occurs from or to a host application document (a movie or cast file, specifically). For this message, refCon contains a PMoaChar pointing to a C string containing the pathname of the filename being read to or written from. */ }; typedef IMoaDrNotificationClient * PIMoaDrNotificationClient; /* ---------------------------------------------------------------------------- / / IMoaDrMediaAccess - Generic media interface / / This interface contains the core methods supported by all / MediaAccess classes. MediaAccess objects, such as ScoreAccess, handle / communication with the media owner object to provide a task-specific / interface for accessing its media. / / -------------------------------------------------------------------------- */ /* IID_IMoaDrMediaAccess: AC401A980000C62600000800072C6326 */ DEFINE_GUID(IID_IMoaDrMediaAccess, 0xAC401A98L, 0x0000, 0xC626, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrMediaAccess DECLARE_INTERFACE_(IMoaDrMediaAccess, IMoaUnknown) /* Description This interface contains the core methods supported by all MediaAccess classes. MediaAccess objects, such as ScoreAccess, handle communication with the media owner object to provide a task-specific interface for accessing its media. MediaAccess is typically buffered; the MediaAccess interface operates on a copy of media data owned by an associated IMoaDrMediaOwner object. Changes are only reflected in the associated owner object when Commit() is called. Using SetAccessInfo(), the owner object can be changed on-the-fly, allowing you to obtain media data from one object, modify it, and commit it back to a different object. In Director 5.0, the only type of MediaAccess interface supported is IMoaDrScoreAccess, used for editing score data associated with a filmloop cast member or Director movie. Director API provides three ways to obtain a MediaAccess interface. <ul><ul> IMoaDrMovie::GetScoreAccess() - This method returns a score access interface for the Director movie.</ul></ul> <ul><ul> IMoaDrCastMem::GetScoreAccess() - This method returns a score access interface for a filmloop cast member</ul></ul> <ul><ul> IMoaDrPlayer::NewScoreAccess() - This method creates a new score access interface without an owner. To save the resulting score to a filmloop cast member or movie, use IMoaDrScoreAccess::SetOwner() or MoaDrMediaAccess::SetAccessInfo() to set the owner before committing.</ul></ul> */ { STD_IUNKNOWN_METHODS STDMETHOD(New)(THIS) PURE; /* Category Creating */ /* Description Obtains the current accessInfo for the media accessor. pAccessInfo is a pointer to a MoaDrAccessInfo structure to receive the information. This call populates the structure with the PIMoaDrMediaOwner for the media owner, the label symbol for the media being accessed, and the format symbol for the media being accessed. Since an interface is being supplied in this structure (pOwner), the caller is responsible for releasing it. */ STDMETHOD(Refresh)(THIS) PURE; /* Category Editing */ /* Description Disposes of the current working media and obtains a fresh copy of the media data from the associated media owner object. If there is no media owner, the call fails and kMoaDrErr_OwnerNotSet is returned. This call causes you to lose any edits made to your media data since the last Refresh() or Commit() calls. */ STDMETHOD(Commit)(THIS) PURE; /* Category Editing */ /* Description Commits changes made to the media being accessed back to the object owning the media data. Changes are not reflected in the media-owning object unless this method is called. For example, after creating a sequence of score frames using IMoaDrScoreAccess, calling Commit()updates the corresponding movie or film loop cast member. If no media owner has been set, this call fails and returns kMoaDrErr_OwnerNotSet. The media owner is set automatically if the IMoaDrScoreAccess interface was obtained directly from the owner using a GetScoreAccess() call. If you have created a new ScoreAccess object from scratch (using IMoaDrPlayer::NewScoreAccess()), it is up to you to associate the media owner object using SetAccessInfo() (or SetOwner() in IMoaDrScoreAccess). The owner is the object that gets updates when Commit() is called */ STDMETHOD(GetAccessInfo)(THIS_ PMoaDrAccessInfo pAccessInfo) /* Pointer to MoaDrAccessInfo structure to receive information */ PURE; /* Category Access Information */ /* Description Obtains the current accessInfo for the media accessor. pAccessInfo is a pointer to a MoaDrAccessInfo structure to receive the information. This call populates the structure with the PIMoaDrMediaOwner for the media owner, the label symbol for the media being accessed, and the format symbol for the media being accessed. Since an interface is being supplied in this structure (pOwner), the caller is responsible for releasing it. */ STDMETHOD(SetAccessInfo)(THIS_ ConstPMoaDrAccessInfo pAccessInfo) /* Pointer to a MoaDrAccessInfo structure to receive the information */ PURE; /* Category Access Information */ /* Description Sets the current accessInfo for the media accessor. pAccessInfo is a pointer to a MoaDrAccessInfo structure containing the new access information to be used. This call sets a new media owner, media label, and media format for the media being accessed. If a mediaOwner is already set, the media accessor's hold on the previous owner interface is released. The caller owns the owner interface (pOwner) provided in the structure. You may change the accessInfo during an editing session. For example, you could obtain an IMoaDrScoreAccess interface for a film loop cast member, edit the score, set the access information to different film loop cast member (or movie), and call Commit(). This leaves the original film loop untouched, and updates the new filmloop or movie with the edited version of the source film loop score. */ }; typedef IMoaDrMediaAccess * PIMoaDrMediaAccess; /* ---------------------------------------------------------------------------- / / IMoaDrCastMem / / -------------------------------------------------------------------------- */ /* IID_IMoaDrCastMem: AC401AB50000CD0300000800072C6326 */ DEFINE_GUID(IID_IMoaDrCastMem, 0xAC401AB5L, 0x0000, 0xCD03, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrCastMem DECLARE_INTERFACE_(IMoaDrCastMem, IMoaDrMediaOwner) /* Description The IMoaDrCastMem interface provides access to specific cast members within a cast. Cast member properties IMoaDrCastMem inherits from the IMoaMmPropOwner interface, providing for access to data through the properties mechanism described in the &quot;Multimedia Services&quot; chapter in the Development Guide document. See the &quot;Properties&quot; section for information on the properties defined for objects providing the IMoaDrCastMem interface. Cast member media types Because this interface inherits from IMoaDrMediaOwner, you can use it to access the properties and media data associated with a cast member. Methods of the IMoaDrMediaOwner interface include pointers to a MoaPrMediaInfo structure as parameters. Before a GetMedia(), SetMedia(), or AttachMedia() call, use IMoaDrUtils::NewMediaInfo() to fill out the structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. Using this call forces you to fill out all the needed parameters. The aux information currently applies only when setting image media. The formatSymbol and labelSymbol members of this structure are MoaMmSymbols. These symbols are obtained from strings using the host app symbol dictionary, accessed through the StringToSymbol() method of the IMoaMmUtils interface For more on how this mechanism is implemented, see the IMoaDrMediaOwner. Here's a brief summary of the media labels supported for Director cast members: <table border="2"> <tr><th align="left" valign="middle" width="105"><b>Media</b></th> <th align="left" valign="middle"><b>Label Description</b></th></tr> <tr><td align="left" valign="top">Composite</td> <td align="left" valign="top">Cast member media data in a portable (byte-swapped) opaque handle.</td></tr> <tr><td align="left" valign="top">Image</td> <td align="left" valign="top">Primary image data (for a bitmap, PICT, and so on). </td></tr> <tr><td align="left" valign="top">Text</td> <td align="left" valign="top">Text character string</td></tr> <tr><td align="left" valign="top">TextStyles</td> <td align="left" valign="top">Text style run data</td></tr> <tr><td align="left" valign="top">Sound</td> <td align="left" valign="top">Sound samples</td></tr> <tr><td align="left" valign="top">Palette</td> <td align="left" valign="top">Palette entries</td></tr> <tr><td align="left" valign="top">Score</td> <td align="left" valign="top">Score data for a movie or film loop</td></tr> </table> The following table provides a brief summary of the media formats supported for Director cast members. <table border="2"> <tr><th align="left" valign="middle" width="125"><b>Media Format</b></th> <th align="left" valign="middle"> <b>Description</b></th></tr> <tr><td align="left" valign="top">moaHandle</td> <td align="left" valign="top">Generic MoaHandle of data</td></tr> <tr><td align="left" valign="top">moaTEStyles</td> <td align="left" valign="top">textStyles stored in a MoaHandle</td></tr> <tr><td align="left" valign="top">macTEStyles</td> <td align="left" valign="top">textStyles in TextEdit StScrpHandle format stored in a Macintosh handle</td></tr> <tr><td align="left" valign="top">macPICT</td> <td align="left" valign="top">Macintosh PicHandle</td></tr> <tr><td align="left" valign="top">macSnd</td> <td align="left" valign="top">Macintosh sndHdl. Handle in Macintosh sound resource format. </td></tr> <tr><td align="left" valign="top">macColorTable</td> <td align="left" valign="top">Macintosh CTabHandle . Handle to a ColorTable record</td></tr> <tr><td align="left" valign="top">winDIB</td> <td align="left" valign="top">Windows packed DIB GlobalHandle with bitmap information, color table, and bits</td></tr> <tr><td align="left" valign="top">winWAVE</td> <td align="left" valign="top">Windows RIFF WAVE GlobalHandle . RIFF sound format. </td></tr> <tr><td align="left" valign="top">winPALETTE</td> <td align="left" valign="top">Windows HPALETTE GlobalHandle. RIFF palette format </td></tr> </table> Composite media label All media types support the composite label; that is, you can get the media data for any cast member as a single, opaque portable MoaHandle. Because Director handles the byteswapping of these, they're safe to write out to disk and read back in on another platform. The format for composite media is always MoaHandle. Other media labels In addition to composite, each built-in cast member type supports one or more other labels or formats. For example, bitmaps, PICTs, Rich Text, and OLE support the image label (RichText and OLE are Get-only for this); the bitmap format supported depends on the platform (macPICT on mac, winDIB on Windows). In the future, we may add additional formats, such as a portable pixel map format which is identical on both platforms. Text supports multiple labels: text to get or set the ASCII text, textStyles (Macintosh-only) to get or set the style data independently from the ASCII. Both movies and cast members support the score media label, with the format MoaHandle. This lets you get and set the score data itself. You can attach a ScoreAccess interface to one of these data handles using IMoaDrUtils::NewScoreAccess(). However, if you want to edit the score of an existing movie or cast member, it's easier just to obtain the ScoreAccess interface directly from the object itself using IMoaDrCastMem::GetScoreAccess(), Here's a complete list of the media labels and formats supported by the Director cast member types: <TABLE BORDER="2"> <TR><TH ALIGN="LEFT" WIDTH=151><B>Cast member type</B></TH> <TH ALIGN="LEFT" WIDTH=220><B>Media label</B></TH><TH ALIGN="LEFT" WIDTH=220><B>Media format</B></TH></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>BITMAP</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Image</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle mac: macPICT win: winDIB</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>FILMLOOP</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Score</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle moaHandle</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>TEXTFIELD</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Text TextStyles</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle moaHandle (null-terminated string) mac: macTEStyles mac &amp; win: moaTEStyles</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>PALETTE</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Palette Palette</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle mac: macColorTable win: winPALETTE</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>PICT</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Image Image</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle mac: macPICT win: winDIB</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>SOUND</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Sound Sound</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle mac: macSnd win: winWAVE</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>BUTTON</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Text TextStyles</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle moaHandle (null-terminated string handle) mac: macTEStyles mac &amp; win: moaTEStyles</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>SHAPE</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>MOVIE</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>DIGITAL VIDEO</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>SCRIPT</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle NOTE: Script text can be accessed using GetProp() and SetProp()</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>RICH TEXT</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Text Image (Get Only)</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle moaHandle (null-terminated string handle). Set allowed only in authoring applications mac: macPICT win: winDIB</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>OLE</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite Image (Get Only)</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle mac: macPICT win: winDIB</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>XTRA</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=151>TRANS</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>Composite</TD> <TD ALIGN="LEFT" VALIGN="TOP" WIDTH=220>moaHandle</TD></TR> </TABLE> Media access in sprite Xtras Sprite Xtras, which provide cast members through extensions to Director, only support the composite media label, which is a combination of the Xtra's media, properties, and built-in properties combined in an opaque format. You can get or set the media data of any Xtra-based cast member type as a composite MoaHandle. */ { STD_IUNKNOWN_METHODS /* IMoaDrMediaOwner methods */ STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ PMoaMmValue pPropValue) /* Pointer to a caller-owned MoaMmValue structure to receive the value of the property */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal err </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other value data </TD></TR> </TABLE> */ /* Description Obtains the value of the specified cast member property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol(). The caller is responsible for releasing the value withIMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest.*/ ConstPMoaMmValue pPropValue) /* Pointer to a caller-owned MoaMmValue structure to copy the new value for the property from.*/ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Property exists, value ok, couldn't set--internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Couldn't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Couldn't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Type mismatch: rect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=343>Type mismatch: CMRef value expected </TD></TR> </TABLE> */ /* Description Sets a cast member property to a new value. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol()., The caller continues to maintain ownership of the value passed in at pPropValue, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(GetMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller-owned media information structure */ PURE; /* Category Media owner methods */ /* Description Gets cast member media data. This method obtains a copy of the media associated with a cast member. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the media information structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. The caller partially populates a MoaDrMediaInfo struct with symbols indicating the requested chunk of media (labelSymbol) and the requested format (formatSymbol). After the call, the mediaData field is populated with the requested data; the type of this field depends on the format requested. The caller then owns the data and is responsible for disposing it, if applicable. Typically this data is either a MoaHandle, a Macintosh Handle or Pointer, or a Windows global handle. */ STDMETHOD(SetMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller-owned media information structure */ PURE; /* Category Media owner methods */ /* Description Sets cast member media data. This method copies caller-supplied media data and associates it with a cast member. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the media information structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. The caller populates a MoaDrMediaInfo structure with symbols indicating the supplied chunk of media (labelSymbol), the supplied format (formatSymbol), and the media data itself (mediaData). If the label and format are supported by the cast member, a call to this method copies the caller's data and replaces any existing media data for the supplied label for the cast member. Since the data is copied, the caller retains ownership of the media data passed in. Typically, this data is either a MoaHandle, a Macintosh Handle or pointer, or a Windows global handle. */ STDMETHOD(AttachMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller- owned media information structure */ PURE; /* Category Media owner methods */ /* Description Attaches media to a cast member, releasing it from the caller. This is the same as the SetMedia() method except instead of copying the data, it is moved to the cast member. (In effect this method is a SetMedia() call followed by a ReleaseMedia() call.) Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the media information structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. On enter, the labelSymbol and formatSymbol fields should be populated with symbols indicating which chunk of media is to be attach (labelSymbol), and what format the media is supplied in (formatSymbol). The mediaData field should hold the data itself (typically a MoaHandle, Macintosh Handle, or Windows global handle) Upon return, if there is no error, the media has changed ownership and belongs to the host application, and should no longer be referenced by the caller. This method is provided to allow the host application to optimize media-transfer if possible; it may prevent an extra copy of the media data, which may occur with separate SetMedia() and ReleaseMedia() calls). */ STDMETHOD(CallFunction)(THIS_ MoaMmSymbol methodName, /* Symbol of the method (function) to call */ MoaLong nArgs, /* Number of arguments, excluding the Xtra instance in pArgs[0] */ ConstPMoaMmValue pArgs, /* Array of arguments, with the first valid argument at pArgs[1] */ PMoaMmValue pResult) /* Pointer to a MoaMmValue to receive a result value, if any. */ PURE; /* Category Scripting Support */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=295>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=295>Successful</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=295>kMoaMmErr_FunctionNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=295>Function not supported </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=295>kMoaMmErr_WrongNumberOfArgs </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=295>Argument count wrong, </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=295>Other Property/CallHandler errors </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=295>Also acceptable here </TD></TR> </TABLE> */ /* Description Calls a cast member Lingo function. Pass the symbol of the function to call in the methodName parameter, along with the argument count (nArgs), the argument array (pArgs), and optionally, a pointer to a MoaMmValue to receive any result value. The argument array, pArgs, contains an array of MoaMmValues corresponding to the function arguments. pArgs[0] is a reserved value and should not be referenced. The function parameters are supplied in pArgs[1] through pArgs[nArgs]. If the method has a return value, it should populate pResult with a new MoaMmValue containing the result. If the cast member does not support the function specified by methodName, it returns the error code kMoaMmErr_FunctionNotFound. If the number or types of arguments are incorrect, the function returns one of the appropriate MoaMmErrors (see mmtypes.h). */ STDMETHOD(GetMemberIndex) (THIS_ MoaDrMemberIndex * pMemberIndex) /* Pointer to position of cast member in cast */ PURE; /* Category Member information */ /* Description Returns the position of the cast member This in its cast. */ STDMETHOD(GetScoreAccess) (THIS_ struct IMoaDrScoreAccess ** ppScore) PURE; /* Category Acquiring IMoaMmScoreAccess */ /* Description Obtains a IMoaDrScoreAccess interface for accessing or editing the score associated with a film loop cast member. This method is only valid for film loop cast members */ STDMETHOD(CallHandler)(THIS_ MoaMmSymbol handlerName, /* Symbol for handler (message) name */ MoaLong nArgs, /* Number of arguments you're passing */ PMoaMmValue pArgs, /* Pointer to an array of MoaMmValues containing arguments */ PMoaMmValue pResult, /* Pointer to an array of MoaMmValues containing arguments */ MoaBool * pHandled) /* Pointer to a MoaBool to receive TRUE if the handler exists in the script (message handled), or FALSE if it does not.*/ PURE; /* Category Scripting support */ /* Description Calls a handler handlerName defined in the script associated with this cast member. The nArgs argument is the number of arguments to the handler, the pArgs argument is a MoaMmList of arguments as MoaMmValues. You must pass in NULL to pResult if you do not expect a result. You must pass in a valid pointer if you do expect a result. The handler call will be passed up the standard Lingo messaging hierarchy. The argument pHandled reports whether the handler was handled by any object in the hierarchy. */ }; typedef IMoaDrCastMem * PIMoaDrCastMem; /* ---------------------------------------------------------------------------- / / IMoaDrCast / / -------------------------------------------------------------------------- */ /* IID_IMoaDrCast: AC401AEC0000D9F800000800072C6326 */ DEFINE_GUID(IID_IMoaDrCast, 0xAC401AECL, 0x0000, 0xD9F8, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrCast DECLARE_INTERFACE_(IMoaDrCast, IMoaMmPropOwner) /* Description The IMoaDrCast interface represents a cast in a movie. This interface can be acquired by calling the IMoaDrMovie methods NewCast(), GetCastFromName() and GetNthCast(). Cast properties IMoaDrCast inherits from the IMoaMmPropOwner interface, providing for access to data through the properties mechanism described in the chapter "Properties" earlier in this document. The following table lists properties defined for objects providing the IMoaDrCast interface. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ PMoaMmValue pPropValue) /* Pointer to a MoaMmValue structure to receive the value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue</FONT> passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal err </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other value data </TD></TR> </TABLE> */ /* Description Obtains the value of the specified cast property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol().The caller is responsible for releasing the value referenced by pPropValue with IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ ConstPMoaMmValue pPropValue) /* Pointer to a caller-owned ConstPMoaMmValue structure containing the new value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists, value ok, couldn't set--internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Couldn't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Couldn't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: rect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef value expected </TD></TR> </TABLE> */ /* Description Sets a cast property to a new value. The caller continues to maintain ownership of the value passed in, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(GetIndexInMovie)(THIS_ struct IMoaDrMovie * pIMoaDirMovie, /* Pointer to a caller-owned interface for the movie of interest. */ MoaDrCastIndex * pCastIndex) /* Pointer to a MoaDrCastIndex to receive the index of the cast in the specified movie */ PURE; /* Category Movie Interaction */ /* Description Obtains the index of the cast in the specified movie's cast list. Casts can be shared among several simultaneously-playing movies; each cast can have a different position within each movie's cast list. The caller must supply an interface to the movie of interest, which continues to be owned by the caller. */ STDMETHOD(GetFirstUsedMemberIndex)(THIS_ MoaDrMemberIndex * pMemberIndex) /* Pointer to a MoaDrMemberIndex to receive the memberIndex. */ PURE; /* Category Cast member access */ /* Description Obtains the index of the first occupied (non-empty) cast member slot in the cast. Returns a NULL member index if there are no cast members in the cast. */ STDMETHOD(GetNextUsedMemberIndex)(THIS_ MoaDrMemberIndex afterMemberIndex, /* Index of cast member slot after which to begin search for a non-empty cast member */ MoaDrMemberIndex * pMemberIndex) /* Pointer to a MoaDrMemberIndex to receive the member index */ PURE; /* Category Cast member access */ /* Description Obtains the index of the next occupied (non-empty) cast member slot in the cast after the specified cast member slot. Returns a NULL member index if there are no cast members in the cast after afterMemberIndex. */ STDMETHOD(GetLastUsedMemberIndex)(THIS_ MoaDrMemberIndex * pMemberIndex) /* Pointer to a MoaDrMemberIndex to receive the memberIndex.*/ PURE; /* Category Cast member access */ /* Description Obtains the index of the last occupied (non-empty) cast member slot in the cast. Returns a NULL member index if there are no cast members in the cast. */ STDMETHOD(GetFirstFreeMemberIndex)(THIS_ MoaDrMemberIndex * pMemberIndex) /* Pointer to a MoaDrMemberIndex to receive the memberIndex.*/ PURE; /* Category Cast member access */ /* Description Obtains the index of the first empty cast member slot in the cast. Returns a NULL member index if there are no empty cast member slots remaining in the cast. */ STDMETHOD(GetNextFreeMemberIndex)(THIS_ MoaDrMemberIndex afterMemberIndex, /* Index of cast member slot after which to begin searching for an empty cast member slot. */ MoaDrMemberIndex * pMemberIndex) /* Pointer to a MoaDrMemberIndex to receive the member index */ PURE; /* Category Cast member access */ /* Description Obtains the index of the next empty cast member slot in the cast after the specified cast member slot. Returns a NULL member index if there are no empty cast member slots in the cast after afterMemberIndex. */ STDMETHOD(GetLastFreeMemberIndex)(THIS_ MoaDrMemberIndex * pMemberIndex) /* Pointer to a MoaDrMemberIndex to receive the memberIndex */ PURE; /* Category Cast member access */ /* Description Obtains the index of the last empty cast member slot in the cast. Returns a NULL member index if there are no empty cast member slots remaining in the cast. */ STDMETHOD(GetMemberIndexFromName)(THIS_ PMoaChar pCastMemName, /* Pointer to a C string buffer containing the name of the cast member of interest */ MoaDrMemberIndex * pMemberIndex) /* Pointer to a MoaDrMemberIndex to receive the index of the cast member */ PURE; /* Category Cast member access */ /* Description Obtains the index of a cast member in the cast given the cast member name. Returns 0 if the cast member cannot be found in the cast. Name comparisons are case-insensitive. */ STDMETHOD(GetCastMem)(THIS_ MoaDrMemberIndex memberIndex, /* Index of the cast member of interest. This must be an occupied cast member slot. */ PIMoaDrCastMem * ppIMoaDrCastMem) /* Pointer to a PIMoaDrCastMem to receive a pointer to the cast member's interface. Interface is then owned by caller which must dispose when no longer needed.*/ PURE; /* Category Cast member access */ /* Description Obtains a cast member interface for the specified cast member. The caller subsequently owns the interface and is responsible for releasing it when it is no longer needed. A cast member interface may no longer be valid if the associated cast member is moved or deleted from the cast. You should always release the cast member interface before returning from the method implementation that calls this method. */ STDMETHOD(CreateCastMem)(THIS_ MoaDrMemberIndex memberIndex, /* Index of the cast member slot into which the newly created cast member will be placed */ MoaMmSymbol typeSymbol) /* The MoaMmSymbol of the type of cast member to create */ PURE; /* Category Cast member management */ /* Description Creates a new cast member of the specified type in the specified cast member slot. The caller must provide the symbol of the type to create. Symbols of all registered types can be obtained from the Player cast member type methods (GetNthCastMemTypeSymbol). If you know that the type is registered and the text string for the type, you can get the symbol directly using IMoaMmUtils::StringToSymbol(). If the specified cast member slot is occupied, the existing cast member is deleted. At the time of creation, the cast member probably will not have any media associated with it; use the IMoaDrCastMem::SetMedia() (or its media accessor interface) to supply it. */ STDMETHOD(DeleteCastMem)(THIS_ MoaDrMemberIndex memberIndex) /* Index of the cast member to delete */ PURE; /* Category Cast member management */ /* Description Deletes the cast member in the specified slot. The cast member is removed immediately. Any references to the cast member in the score will be dangling. */ STDMETHOD(DuplicateCastMem)(THIS_ MoaDrMemberIndex sourceMemberIndex, /* Index of the cast member in this cast to duplicate */ struct IMoaDrCast * pDestCast, /* Pointer to a caller-owned IMoaDrCast interface for the destination cast */ MoaDrMemberIndex destMemberIndex) /* Index in pDestCast of the cast member slot in which to place the copied cast member */ PURE; /* Category Cast member management */ /* Description Duplicates a cast member, placing the copy in the specified slot within the specified cast. The caller must pass in an interface to the destination cast; this interface continues to be owned by the caller. This method duplicates the cast member entirely, including its properties (name, and so on) and media data. If the destination cast member slot is occupied, the existing cast member is deleted. */ STDMETHOD(Save)(THIS_ PMoaChar pNewPathName) /* Pointer to a specified path */ PURE; /* Category Cast management */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=157>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=433>Successful</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=157>kMoaDrErr_DiskIO </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=433>IO error encountered during file access. </TD></TR> </TABLE> */ /* Description Saves the cast to the specified path, which should include the filename. This method applies only to external cast members. */ }; typedef IMoaDrCast * PIMoaDrCast; /* ---------------------------------------------------------------------------- / / IMoaDrScoreFrame / / -------------------------------------------------------------------------- */ /* IID_IMoaDrScoreFrame: AC5E874200FE19A700000800072C6326 */ DEFINE_GUID(IID_IMoaDrScoreFrame, 0xAC5E8742L, 0x00FE, 0x19A7, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrScoreFrame DECLARE_INTERFACE_(IMoaDrScoreFrame, IMoaMmPropOwner) /* Description The IMoaDrScoreFrame interface represents a particular frame in a score. You acquire this interface through the IMoaDrScoreAccess::GetFrame() method. Score frame properties IMoaDrScoreFrame inherits from the IMoaMmPropOwner interface, providing for access to data through the properties mechanism described in the "Multimedia Services" chapter in the Development Guide document. See the "Properties" section for information on the properties defined for objects providing the IMoaDrScoreFrame interface. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ PMoaMmValue pPropValue) /* Pointer to a caller-owned MoaMmValue structure to receive the value of the property */ PURE; /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue</FONT> passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other value data </TD></TR> </TABLE> */ /* Description Obtains the value of the specified score frame property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol().The caller is responsible for releasing the value with IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ ConstPMoaMmValue pPropValue) /* Pointer to a caller-owned ConstPMoaMmValue structure from which to copy the value of the property */ PURE; /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists, value ok, but can't set--internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Can't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Can't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: rect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef value expected </TD></TR> </TABLE> */ /* Description Sets a score frame property to a new value. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol().The caller continues to maintain ownership of the value passed in, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ }; typedef IMoaDrScoreFrame * PIMoaDrScoreFrame; /* ---------------------------------------------------------------------------- / / IMoaDrScoreSound / / -------------------------------------------------------------------------- */ /* IID_IMoaDrScoreSound: AC5E876500FE21EC00000800072C6326 */ DEFINE_GUID(IID_IMoaDrScoreSound, 0xAC5E8765L, 0x00FE, 0x21EC, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrScoreSound DECLARE_INTERFACE_(IMoaDrScoreSound, IMoaMmPropOwner) /* Description The IMoaDrScoreSound interface represents the sound in a particular channel in a particular frame in a score. You acquire this interface through the IMoaDrScoreAccess::GetSound() method. Score sound properties IMoaDrScoreSound inherits from the IMoaMmPropOwner interface, providing for access to data through the properties mechanism described in the "Multimedia Services" chapter in the Development Guide document. See the "Properties" section for information on the properties defined for objects providing the IMoaDrScoreSound interface. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ PMoaMmValue pPropValue) /* Pointer to a caller-owned MoaMmValue structure to receive the value of the property */ PURE; /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue</FONT> passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other value data </TD></TR> </TABLE> */ /* Description Obtains the value of the specified score sound property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol(). The caller is responsible for releasing the value with IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ ConstPMoaMmValue pPropValue) /* Pointer to a caller-owned ConstPMoaMmValue structure from which to copy the value of the property */ PURE; /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists, value ok, but can't set--internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Can't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Can't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: rect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef value expected </TD></TR> </TABLE> */ /* Description Sets a score sound property to a new value. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol().The caller continues to maintain ownership of the value passed in, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ }; typedef IMoaDrScoreSound * PIMoaDrScoreSound; /* ---------------------------------------------------------------------------- / / IMoaDrScoreSprite / / -------------------------------------------------------------------------- */ /* IID_IMoaDrScoreSprite: AC5E878200FE28B400000800072C6326 */ DEFINE_GUID(IID_IMoaDrScoreSprite, 0xAC5E8782L, 0x00FE, 0x28B4, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrScoreSprite DECLARE_INTERFACE_(IMoaDrScoreSprite, IMoaMmPropOwner) /* Description The IMoaDrScoreSprite interface represents the sprite in a particular channel in a particular frame in a score. You acquire this interface through the IMoaDrScoreAccess::GetSprite() method. Score sprite properties IMoaDrScoreSprite inherits from the IMoaMmPropOwner interface, providing for access to data through the properties mechanism described in the "Multimedia Services" chapter in the Development Guide document. See the "Properties" section for information on the properties defined for objects providing the IMoaDrScoreSprite interface. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp) (THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ PMoaMmValue pPropValue) /* Pointer to a caller-owned MoaMmValue structure to receive the value of the property */ PURE; /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue</FONT> passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other alue data </TD></TR> </TABLE> */ /* Description Obtains the value of the specified score sprite property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol(). The caller is responsible for releasing the value with IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetProp) (THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ ConstPMoaMmValue pPropValue) /* Pointer to a caller-owned ConstPMoaMmValue structure from which to copy the value of the property */ PURE; /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists, value ok, but can't set--internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Can't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Can't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: rect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef value expected </TD></TR> </TABLE> */ /* Description Sets a score sprite property to a new value To get the symbol from a string, use the IMoaMmUtils::StringToSymbol(). The caller continues to maintain ownership of the value passed in, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ }; typedef IMoaDrScoreSprite * PIMoaDrScoreSprite; /* ---------------------------------------------------------------------------- / / IMoaDrScoreAccess / / -------------------------------------------------------------------------- */ /* INTERFACEID */ /* IID_IMoaDrScoreAccess: AC401B2A0000E88800000800072C6326 */ DEFINE_GUID(IID_IMoaDrScoreAccess, 0xAC401B2AL, 0x0000, 0xE888, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrScoreAccess DECLARE_INTERFACE_(IMoaDrScoreAccess, IMoaDrMediaAccess) /* Description IMoaDrScoreAccess inherits from IMoaDrMediaAccess. This interface provides specific methods for accessing and editing the contents of a Director movie's score. You can acquire a score interface by calling the IMoaDrMovie::GetScoreAccess() method. Film loop cast members also have scores, which can be acquired by IMoaDrCastMem::GetScoreAccess(). See the section entitled IMoaDrMediaAccess for information regarding the inherited IMoaDrMediaAccess-specific methods of this interface. */ { STD_IUNKNOWN_METHODS STDMETHOD(New)(THIS) PURE; /* Category Editing support */ /* Description See IMoaDrMediaAccess */ STDMETHOD(Refresh)(THIS) PURE; /* Category Editing support */ /* Description See IMoaDrMediaAccess */ STDMETHOD(Commit)(THIS) PURE; /* Category Editing support */ /* Description Commits changes made to media back since the last BeginUpdate(), Commit(), or Refresh(). Call this method to apply changes to media back to the owner. */ STDMETHOD(GetAccessInfo)(THIS_ PMoaDrAccessInfo pAccessInfo) /* Pointer to MoaDrAccessInfo structure to receive information */ PURE; /* Category Media access */ /* Description Obtains the current accessInfo for the score accessor. pAccessInfo is a pointer to a MoaDrAccessInfo structure to receive the information. This call populates the structure with the PIMoaDrMediaOwner for the media owner, the label symbol for the media being accessed, and the format symbol for the media being accessed. Since an interface is being supplied in this structure (pOwner), the caller is responsible for releasing it. */ STDMETHOD(SetAccessInfo)(THIS_ ConstPMoaDrAccessInfo pAccessInfo) /* Pointer to MoaDrAccessInfo structure to receive information */ PURE; /* Category Media access */ /* Description Sets the current accessInfo for the score accessor. pAccessInfo is a pointer to a MoaDrAccessInfo structure providing the information. This call populates the structure with the PIMoaDrMediaOwner for the media owner, the label symbol for the media being accessed, and the format symbol for the media being accessed. Since the caller supplies an interface in this structure (pOwner), the caller is responsible for releasing it. */ /* ScoreAccess methods */ STDMETHOD(SetOwner)(THIS_ PIMoaDrMediaOwner pOwner) PURE; /* Category Media access */ /* Description Convenience method to set the access information for the ScoreAccess object. Calling this method results in the same behavior as calling SetAccessInfo() with score and MoaHandle as the label and format symbols, respectively. */ STDMETHOD(BeginUpdate)(THIS) PURE; /* Category Editing support */ /* Description Begins a score editing session. Before inserting or deleting frames, or modifying score frames, sounds, or sprites, you must call BeginUpdate(). When done with your changes, call EndUpdate(). */ STDMETHOD(EndUpdate)(THIS) PURE; /* Category Editing support */ /* Description Finishes an update session initiated by a call to BeginUpdate(). If you wish to keep score changes, call Commit() before calling this method; to revert to previous score, simply call this method without committing the media. */ STDMETHOD(SetCurFrameIndex)(THIS_ MoaDrFrameIndex frameIndex) /* Frame number of the new current frame */ PURE; /* Category Frame access */ /* Description Sets the current frame being accessed. frameIndex is the frame number of the new current frame. */ STDMETHOD(GetCurFrameIndex)(THIS_ PMoaDrFrameIndex pFrameIndex) PURE; /* Category Frame access */ /* Description Obtains the frame number of the current frame being accessed. */ STDMETHOD(GetLastFrameIndex)(THIS_ PMoaDrFrameIndex pFrameIndex) PURE; /* Category Frame access */ /* Description Obtains the frame number of the last occupied frame in the score. */ STDMETHOD(UpdateFrame)(THIS) PURE; /* Category Frame editing */ /* Description Updates the current frame. This method has two effects, it <ul><ul> saves any changes made to frame, sound, and sprite channels to the working score data</ul></ul> <ul><ul> increments the current frame by 1. </ul></ul> */ STDMETHOD(InsertFrame)(THIS) PURE; /* Category Frame Editing */ /* Description Inserts a frame at the current frame position. This has the same effect as DuplicateFrame(). */ STDMETHOD(DuplicateFrame)(THIS) PURE; /* Category Frame Editing */ /* Description Duplicates the current frame. The new frame is inserted at position &lt;currentFrame + 1&gt;. The current frame is incremented to the new frame (&lt;currentFrame + 1&gt;). */ STDMETHOD(ClearFrame)(THIS) PURE; /* Category Frame Editing */ /* Description Clears all of the cells in the current frame to their default (empty) values. */ STDMETHOD(DeleteFrame)(THIS) PURE; /* Category Frame Editing */ /* Description Deletes the current frame from the score. */ STDMETHOD(GetFrame)(THIS_ PIMoaDrScoreFrame * ppFrame) PURE; /* Category Frame access */ /* Description Obtains the IMoaDrScoreFrame interface for the score data being accessed. This interface is used to get and set frame-level properties of the score data. */ STDMETHOD(GetSound)(THIS_ MoaDrSoundChanIndex chanIndex, /* Specifies the sound channel to access */ PIMoaDrScoreSound * ppSound) PURE; /* Category Channel access */ /* Description Obtains the IMoaDrScoreSound interface for a certain sound channel of the score data being accessed. chanIndex specifies the sound channel to access; in Director 5.0, this must be either 1 or 2. This interface is used to get and set sound channel-level properties of the score data. */ STDMETHOD(GetSprite)(THIS_ MoaDrSpriteChanIndex chanIndex, /* Specifies the sprite channel to access */ PIMoaDrScoreSprite * ppSprite) PURE; /* Category Channel access */ /* Description Obtains the IMoaDrScoreSprite interface for a certain sprite channel of the score data being accessed. chanIndex specifies the sprite channel to access; in Director 5.0, this must be in the range 1 to 48. This interface is used to get and set sprite channel-level properties of the score data. */ }; typedef IMoaDrScoreAccess * PIMoaDrScoreAccess; /* ---------------------------------------------------------------------------- / / IMoaDrMovie / / -------------------------------------------------------------------------- */ /* IID_IMoaDrMovie: AC401B610000F57600000800072C6326 */ DEFINE_GUID(IID_IMoaDrMovie, 0xAC401B61L, 0x0000, 0xF576, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrMovie DECLARE_INTERFACE_(IMoaDrMovie, IMoaDrMediaOwner) /* Description The IMoaDrMovie interface represents open movies in Director. You acquire a movie interface by calling the IMoaDrPlayer methods GetActiveMovie() or GetNthMovie(). Movie properties IMoaDrMovie inherits from the IMoaMmPropOwner interface, providing for access to data through the properties mechanism described in the "Multimedia Services" chapter in the Development Guide document. See the "Properties" section for information on the properties defined for objects providing the IMoaDrMovie interface. Movie media IMoaDrMovie inherits from the IMoaDrMediaOwner interface, providing for access to media through the media owner mechanism described in the "Director Services" chapter in the Development Guide document. Movies have one kind of media: scores. Scores are editable through the IMoaDrScoreAccess interface. You acquire a movie's score data by calling either IMoaDrMovie::GetMedia(), which returns a handle to the score data, or GetScoreAccess(), which returns an IMoaDrScoreAccess interface to the score data. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest.*/ PMoaMmValue pPropValue) /* Pointer to a MoaMmValue to receive the value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other value data </TD></TR> </TABLE> */ /* Description Obtains the value of the specified movie property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol(). The caller is responsible for releasing the value at pPropValue with IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ ConstPMoaMmValue pPropValue) /* Pointer to a caller-owned ConstPMoaMmValue structure from which to copy the new value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists, value ok, couldn't set--internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Couldn't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Couldn't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: rect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef value expected </TD></TR> </TABLE> */ /* Description Sets the value of the specified property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol() method. The caller continues to maintain ownership of the value passed in, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(GetMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller-owned media information structure */ PURE; /* Category Media owner methods */ /* Description Gets movie media data by obtaining a copy of the media associated with a movie. This is how one obtains the score data associated with a movie. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. The caller partially populates a MoaDrMediaInfo structure with symbols indicating the requested chunk of media (labelSymbol) and the requested format (formatSymbol). After the call, the mediaData field is populated with the requested data. The type of this field depends on the format requested. The caller owns the data and is responsible for disposing it, if applicable. Typically, this data is either a MoaHandle, a Macintosh handle or pointer, or a Windows global handle. See Director property.rtf for a table of mediaLabels and mediaFormats supported for movies. */ STDMETHOD(SetMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller-owned media information structure */ PURE; /* Category Media owner methods */ /* Description Sets movie media data. This is how one replaces the score data associated with a movie. This method copies caller-supplied media data and associates it with the movie. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. The caller populates a MoaDrMediaInfo structure with symbols indicating the supplied chunk of media (labelSymbol) and the supplied format (formatSymbol), and the media data itself (mediaData). If the label and format are supported by the movie, a call to this method copies the caller's data and replaces any existing media data for the supplied label for the movie. Since the data is copied, the caller retains ownership of the media data passed in. Typically this data is either a MoaHandle, a Macintosh handle or pointer, or a Windows global handle. See Director property.rtf for a table of mediaLabels and mediaFormats supported for movies. */ STDMETHOD(AttachMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller-owned media information structure */ PURE; /* Category Media owner methods */ /* Description Attaches media to a movie, releasing it from the caller. This is the same as SetMedia() except instead of copying the data, it is moved to the movie. (In effect, a SetMedia() call followed by ReleaseMedia().) Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. On enter, the labelSymbol and formatSymbol fields should be populated with symbols indicating which chunk of media is to be attach (labelSymbol), and what format the media is supplied in (formatSymbol). The mediaData field should hold the data itself (typically a MoaHandle, Macintosh Handle, or Windows global handle) Upon return, if there is no error, the media has changed ownership and belongs to the host application, and should no longer be referenced by the caller. This method is provided to allow the host application to optimize media-transfer if possible, preventing an extra copy of the media data, which may occur with separate SetMedia() and ReleaseMedia() calls). */ STDMETHOD(CallHandler)(THIS_ MoaMmSymbol name, /* Symbol of the handler name to call MoaMmSymbol */ MoaLong nArgs, /* Number of arguments to pass */ PMoaMmValue pArgs, /* Array of MoaDrValues containing the arguments to the call */ PMoaMmValue pResult) /* Pointer to a caller-owned MoaMmValue to receive the return value */ PURE; /* Category Scripting support */ /* Description Calls the Lingo handler name in the movie. The nArgs argument is the number of arguments to the handler, the pArgs argument is a MoaMmList of arguments as MoaMmValues. You must pass in NULL to pResult if you do not expect a result. You must pass in a valid pointer if you do expect a result. */ STDMETHOD(GetCastCount)(THIS_ MoaLong * pCastCount) /* Pointer to a MoaLong to receive the number of casts */ PURE; /* Category Managing casts */ /* Description Obtains the number of casts in the movie. */ STDMETHOD(GetNthCast)(THIS_ MoaDrCastIndex movieCastIndex, /* Index of the cast (from 1 to GetCastCount()) of interest */ PIMoaDrCast * ppIMoaDrCast) /* Pointer to a PIMoaDrCast to receive a pointer to the cast interface */ PURE; /* Category Managing casts */ /* Description Obtains an interface to one of the movie's casts by index. The interface is then owned by the caller, and the caller is responsible for releasing it when it is no longer needed. */ STDMETHOD(GetCastFromName)(THIS_ PMoaChar pCastName, /* Pointer to a null-terminated C string containing the cast name of interest */ PIMoaDrCast * ppIMoaDrCast) /* Pointer to a PIMoaDrCast to receive a pointer to the cast interface */ PURE; /* Category Managing casts */ /* Description Obtains an interface to one of the movie's casts by name, as it appears in the Cast Properties dialog. The interface is then owned by the caller, and the caller is responsible for releasing it when it is no longer needed. */ STDMETHOD(GetCastIndexFromName)(THIS_ PMoaChar pCastName, /* Pointer to a null-terminated C string containing the cast name of interest */ MoaDrCastIndex * pCastIndex) /* Pointer to a MoaDrCastIndex to receive the index */ PURE; /* Category Managing casts */ /* Description Obtains the movie cast index associated with a named cast. This is a value from 1 to GetCastCount(). */ STDMETHOD(NewCast) (THIS_ PMoaChar pCastName, MoaBoolParam bExternal, PMoaDrCastIndex pNewCastIndex) PURE; /* Category Managing casts */ /* Description Creates a new cast and add it to the movie's cast list. Returns the position of the new cast in the pNewCastIndex argument. */ STDMETHOD(AddExternalCast) (THIS_ PMoaChar pCastName, /* The user reference name for the cast */ PMoaChar pPathName, /* The full path name for an external cast */ PMoaDrCastIndex pNewCastIndex) /* PMoaDrCastIndex for the position in the cast list */ PURE; /* Category Managing casts */ /* Description Adds an existing external cast to the movie's cast list. Returns in pNewCastIndex the position of the cast in the movie's cast list. */ STDMETHOD(RemoveCast)(THIS_ MoaDrCastIndex castIndexToRemove) /* MoaDrCastIndex for the cast to remove */ PURE; /* Category Managing casts */ /* Description Removes the cast specified by castToRemove from the movie's cast list. */ STDMETHOD(GetCMRefFromMemberName)(THIS_ PMoaChar pMemberName, /* Pointer to a null-terminated C string containing the cast member name of interest */ PMoaDrCMRef pCastMemRef) /* Pointer to a MoaDrCMRef to receive cast member reference */ PURE; /* Category Managing casts */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=229>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=361>Successful</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=229>kMoaDrErr_CastMemNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=361>Cast member not found </TD></TR> </TABLE> */ /* Description Obtains the cast member reference (MoaDrCMRef) for a cast member from its name. This method scans all of the casts for the movie, and returns the MoaDrCMRef for the first cast member whose name matches the one supplied. If no cast member is found with the specified name, kMoaDrErr_CastMemNotFound is returned and pCastMemRef is set to a null reference . Use CMRef_IsNull() to test the result. */ STDMETHOD(GetCastMemFromCMRef)(THIS_ PMoaDrCMRef pCastMemRef, /* Pointer to a MoaDrCMRef which specifies the cast member of interest */ PIMoaDrCastMem * ppIMoaDrCastMem) /* Pointer to a PIMoaDrCastMem to receive the interface for the cast member */ PURE; /* Category Acquiring ImoaDrCastMem */ /* Description Obtains the IMoaDrCastMem interface for the cast member with the supplied cast member reference. The cast member reference specifies the movieCastIndex (index to cast in the movie) and memberIndex (index to cast member slot position within the cast); use the CMRef_ macros in drtypes.h to create and access a 0. The caller owns the returned interface and is responsible for releasing it when it is no longer needed. */ STDMETHOD(UpdateStageRect) (THIS_ MoaRect * pWindowRect, /* Pointer to a MoaRect describing the area of the stage window to update */ MoaRect * pBufferRect) /* Pointer to a MoaRect describing the area of the offscreen buffer from where to update */ PURE; /* Category Imaging support */ /* Description Updates a rectangular area of the stage window from a rectangular area of the stage's offscreen buffer. Stretching or shrinking of parts of the image can be achieved by using a windowRect which differs in size from the bufferRect. Note that this call does not cause all sprites on the stage to be reimaged; it simply refreshes the stage window from Director's offscreen compositing buffer. */ STDMETHOD(GetStageWindowGC)(THIS_ PIMoaMmGC * ppWindowGC) /* Pointer to a IMoaMmGC interface for the stage window */ PURE; /* Category Imaging support */ /* Description Obtains the graphics context for the stage window. This includes the bounds rectangle, pixel depth, as well as platform-specific information (such as the WindowPtr of the window on the Macintosh, or the HWND on Windows). This information is valid only for the duration of the current call into your Xtra method, because the stage window can change in depth or size at any time (and may be disposed of and reallocated in the process). You must release the graphics context when done by calling its Release() method. Important note about graphic contexts This method should only be called by Lingo and Tool Xtras to do temporary drawing into the stage window. It should be called just before doing your drawing, and the acquired interface should be released before returning control to the calling application. This is because nativeGCInfo for the stage buffer can become invalid at any time. For example, the buffer may be dumped and recreated if window size, monitor depth, or other display characteristics change. It's not always possible to obtain the a graphics context for the stage window. During registration, startup, and shut-down, internal movie data structures may not be initialized, thus trying to get the GC for it will return the err kMoaDrErr_MovieNotOpen. Xtra developers should never attempt to acquire a graphics context and hold onto it; instead, you should acquire the interface each time you need to draw and release it before your method returns. Also, GetStageWindowGC() should not be used to get a parent window for Windows(TM) dialogs. The correct procedure is to use the IMoaMmUtils Windows API cover methods such as WinDialogBox() and WinDialogBoxParam(). If you're putting up a system dialog on Windows, use WinGetParent() to get the parent HWND to use, and bracket your dialog call with WinPrepareDialogBox() and WinUnprepareDialogBox(). Finally, these calls should not be used for sprite or transition drawing. Instead, use the graphic context passed to you explicitly in IMoaMmSpriteActor::Image() or IMoaDrTransitionActor::Continue(). If you do attempt to use this context, your Xtra will not work correctly in MIAWs, export, or other applications such as Authorware. */ STDMETHOD(GetStageBufferGC)(THIS_ PIMoaMmGC * ppBufferGC) /* Pointer to a IMoaMmGC interface for the stage offscreen buffer */ PURE; /* Category Imaging support */ /* Description Obtains the graphics context for the stage offscreen buffer. This includes the bounds rectangle, pixel depth, as well as platform-specific information (such as the WindowPtr of the window on the Macintosh or the HWND on Windows). This information is valid only for the duration of the current call into your Xtra method, because the stage window can change in depth or size at any time (and may be disposed of and reallocated in the process). You must release the graphics context when done by calling its Release() method. Important note about graphic contexts This method should only be called by Lingo and Tool Xtras to do temporary drawing into the stage window. It should be called just before doing your drawing, and the acquired interface should be released before returning control to the calling application. This is because nativeGCInfo for the stage buffer can become invalid at any time. For example, the buffer may be dumped and recreated if window size, monitor depth, or other display characteristics change. It's not always possible to obtain the a graphics context for the stage buffer. During registration, startup, and shut-down, internal movie data structures may not be initialized, thus trying to get the GC for it will return the err kMoaDrErr_MovieNotOpen. Xtra developers should never attempt to acquire a graphics context and hold onto it; instead, you should acquire the interface each time you need to draw and release it before your method returns. Finally, this method should not be called to get a context for sprite or transition drawing. Instead, use the graphic context passed to you explicitly in IMoaMmSpriteActor::Image() or IMoaDrTransitionActor::Continue(). If you attempt to use this context, your Xtra will not work correctly in MIAWs, export, or other applications such as Authorware. */ STDMETHOD(GetFrameIndexFromLabel)(THIS_ PMoaChar pLabelName, /* Pointer to a null-terminated C-string containing the name of the marker associated with the score frame (case-insensitive) */ PMoaDrFrameIndex pFrameIndex) /* Pointer to a MoaDrFrameIndex to receive the frame number of the label (marker) */ PURE; /* Category Accessing frame labels */ /* Returns <TABLE BORDER="2"> <TR><TD WIDTH=133>kMoaErr_NoErr</TD><TD WIDTH=457>if successful, kMoaDrErr_LabelNotFound if marker doesn't exist. </TD></TR> </TABLE> */ /* Description Obtains the frame number from a label (marker) name. */ STDMETHOD(GetFrameLabelFromIndex)(THIS_ MoaDrFrameIndex frameIndex, /* A MoaDrFrameIndex holding the frame number of interest */ PMoaChar pLabelName, /* Pointer to a string buffer to receive the name of the marker associated with the given score frame */ MoaLong maxLen) /* The length in bytes of the caller's C string buffer */ PURE; /* Category Accessing frame labels */ /* Description Obtains the name of the label (marker) at a given score frame number. Returns an empty string if no marker exists for the frame. */ STDMETHOD(SetFrameLabel)(THIS_ MoaDrFrameIndex frameIndex, /* A MoaDrFrameIndex holding the number of the frame */ PMoaChar pLabelName) /* Pointer to a MoaChar to receive the name of the marker associated with the given score frame */ PURE; /* Category Accessing frame labels */ /* Description Adds, modifies, or deletes a score label (marker) or a frame. You pass in the frame number and a C string for the new label. If a label doesn't exist for that frame, one will be added. If one does exist, it'll be replaced with the new one you specify. If you pass in NULL for pLabelName, any current label for that frame is deleted. */ STDMETHOD(GetScoreAccess)(THIS_ PIMoaDrScoreAccess * ppScore) PURE; /* Category Acquiring IMoaDrScoreAccess */ /* Description Gets a ScoreAccess interface provider for the movie's score. */ STDMETHOD(Save)(THIS_ PMoaChar pNewPathName, /* Null-terminated C string for the path */ MoaBoolParam bSaveExtCasts) PURE; /* Category Managing movies */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=157>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=433>Successful</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=157>kMoaDrErr_DiskIO </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=433>IO error during file access </TD></TR> </TABLE> */ /* Description Saves the movie to the path. Specify the complete path, including file name, to save the cast to a new file. Pass NULL as pNewPathName to save the cast in its previous file. */ STDMETHOD(SendSpriteMessage)(THIS_ MoaDrSpriteChanIndex chanIndex, /* Channel number of sprite to which to send the message. Valid values are from 1 to 48. */ MoaMmSymbol handlerName, /* Symbol for the handler (message) name */ MoaLong nArgs, /* Number of arguments you're passing */ PMoaMmValue pArgs, /* Pointer to an array of MoaMmValues containing arguments */ PMoaMmValue pResult, /* Pointer to a MoaMmValue to receive a result */ MoaBool * pHandled) /* arguments to a MoaBool to receive TRUE if the message was handled somewhere down the chain or FALSE if it was not. */ PURE; /* Category Scripting support */ /* Description Sends a sprite message to be passed through the standard Director sprite message hierarchy beginning with the sprite script of the sprite in the specified channel. This method is similar to IMoaDrSpriteCallback::SendSpriteMessage().You must pass in NULL to pResult if you do not expect a result; you must pass in a valid pointer if you do expect a result. */ }; typedef IMoaDrMovie * PIMoaDrMovie; /* ---------------------------------------------------------------------------- / / IMoaDrMovie2 / / -------------------------------------------------------------------------- */ /* IID_IMoaDrMovie2: 5B0D82A7-3257-11d0-A222-00A02453444C */ DEFINE_GUID(IID_IMoaDrMovie2, 0x5b0d82a7, 0x3257, 0x11d0, 0xa2, 0x22, 0x0, 0xa0, 0x24, 0x53, 0x44, 0x4c); #undef INTERFACE #define INTERFACE IMoaDrMovie2 DECLARE_INTERFACE_(IMoaDrMovie2, IMoaUnknown) /* Description The IMoaDrMovie2 interface represents open movies in Director. You acquire a movie interface by calling the IMoaDrPlayer methods GetActiveMovie() or GetNthMovie(). This returns to you an IMoaDrMovie interface. You can calling the QueryInterface method off this interface to retrieve an IMoaDrMovie2 interface Movie properties IMoaDrMovie2 inherits from the IMoaMmPropOwner interface, providing for access to data through the properties mechanism described in the "Multimedia Services" chapter in the Development Guide document. See the "Properties" section for information on the properties defined for objects providing the IMoaDrMovie interface. Movie media IMoaDrMovie inherits from the IMoaDrMediaOwner interface, providing for access to media through the media owner mechanism described in the "Director Services" chapter in the Development Guide document. Movies have one kind of media: scores. Scores are editable through the IMoaDrScoreAccess interface. You acquire a movie's score data by calling either IMoaDrMovie::GetMedia(), which returns a handle to the score data, or GetScoreAccess(), which returns an IMoaDrScoreAccess interface to the score data. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest.*/ PMoaMmValue pPropValue) /* Pointer to a MoaMmValue to receive the value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other value data </TD></TR> </TABLE> */ /* Description Obtains the value of the specified movie property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol(). The caller is responsible for releasing the value at pPropValue with IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ ConstPMoaMmValue pPropValue) /* Pointer to a caller-owned ConstPMoaMmValue structure from which to copy the new value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists, value ok, couldn't set--internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Couldn't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Couldn't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: rect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef value expected </TD></TR> </TABLE> */ /* Description Sets the value of the specified property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol() method. The caller continues to maintain ownership of the value passed in, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(GetMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller-owned media information structure */ PURE; /* Category Media owner methods */ /* Description Gets movie media data by obtaining a copy of the media associated with a movie. This is how one obtains the score data associated with a movie. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. The caller partially populates a MoaDrMediaInfo structure with symbols indicating the requested chunk of media (labelSymbol) and the requested format (formatSymbol). After the call, the mediaData field is populated with the requested data. The type of this field depends on the format requested. The caller owns the data and is responsible for disposing it, if applicable. Typically, this data is either a MoaHandle, a Macintosh handle or pointer, or a Windows global handle. See Director property.rtf for a table of mediaLabels and mediaFormats supported for movies. */ STDMETHOD(SetMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller-owned media information structure */ PURE; /* Category Media owner methods */ /* Description Sets movie media data. This is how one replaces the score data associated with a movie. This method copies caller-supplied media data and associates it with the movie. Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. The caller populates a MoaDrMediaInfo structure with symbols indicating the supplied chunk of media (labelSymbol) and the supplied format (formatSymbol), and the media data itself (mediaData). If the label and format are supported by the movie, a call to this method copies the caller's data and replaces any existing media data for the supplied label for the movie. Since the data is copied, the caller retains ownership of the media data passed in. Typically this data is either a MoaHandle, a Macintosh handle or pointer, or a Windows global handle. See Director property.rtf for a table of mediaLabels and mediaFormats supported for movies. */ STDMETHOD(AttachMedia)(THIS_ PMoaDrMediaInfo pMediaInfo) /* Pointer to a caller-owned media information structure */ PURE; /* Category Media owner methods */ /* Description Attaches media to a movie, releasing it from the caller. This is the same as SetMedia() except instead of copying the data, it is moved to the movie. (In effect, a SetMedia() call followed by ReleaseMedia().) Before making this call, use IMoaDrUtils::NewMediaInfo() to fill out the structure, specifying NULL for the aux field and kMoaDrMediaOpts_None for the options field. On enter, the labelSymbol and formatSymbol fields should be populated with symbols indicating which chunk of media is to be attach (labelSymbol), and what format the media is supplied in (formatSymbol). The mediaData field should hold the data itself (typically a MoaHandle, Macintosh Handle, or Windows global handle) Upon return, if there is no error, the media has changed ownership and belongs to the host application, and should no longer be referenced by the caller. This method is provided to allow the host application to optimize media-transfer if possible, preventing an extra copy of the media data, which may occur with separate SetMedia() and ReleaseMedia() calls). */ STDMETHOD(CallHandler)(THIS_ MoaMmSymbol name, /* Symbol of the handler name to call MoaMmSymbol */ MoaLong nArgs, /* Number of arguments to pass */ PMoaMmValue pArgs, /* Array of MoaDrValues containing the arguments to the call */ PMoaMmValue pResult) /* Pointer to a caller-owned MoaMmValue to receive the return value */ PURE; /* Category Scripting support */ /* Description Calls the Lingo handler name in the movie. The nArgs argument is the number of arguments to the handler, the pArgs argument is a MoaMmList of arguments as MoaMmValues. You must pass in NULL to pResult if you do not expect a result. You must pass in a valid pointer if you do expect a result. */ STDMETHOD(GetCastCount)(THIS_ MoaLong * pCastCount) /* Pointer to a MoaLong to receive the number of casts */ PURE; /* Category Managing casts */ /* Description Obtains the number of casts in the movie. */ STDMETHOD(GetNthCast)(THIS_ MoaDrCastIndex movieCastIndex, /* Index of the cast (from 1 to GetCastCount()) of interest */ PIMoaDrCast * ppIMoaDrCast) /* Pointer to a PIMoaDrCast to receive a pointer to the cast interface */ PURE; /* Category Managing casts */ /* Description Obtains an interface to one of the movie's casts by index. The interface is then owned by the caller, and the caller is responsible for releasing it when it is no longer needed. */ STDMETHOD(GetCastFromName)(THIS_ PMoaChar pCastName, /* Pointer to a null-terminated C string containing the cast name of interest */ PIMoaDrCast * ppIMoaDrCast) /* Pointer to a PIMoaDrCast to receive a pointer to the cast interface */ PURE; /* Category Managing casts */ /* Description Obtains an interface to one of the movie's casts by name, as it appears in the Cast Properties dialog. The interface is then owned by the caller, and the caller is responsible for releasing it when it is no longer needed. */ STDMETHOD(GetCastIndexFromName)(THIS_ PMoaChar pCastName, /* Pointer to a null-terminated C string containing the cast name of interest */ MoaDrCastIndex * pCastIndex) /* Pointer to a MoaDrCastIndex to receive the index */ PURE; /* Category Managing casts */ /* Description Obtains the movie cast index associated with a named cast. This is a value from 1 to GetCastCount(). */ STDMETHOD(NewCast) (THIS_ PMoaChar pCastName, MoaBoolParam bExternal, PMoaDrCastIndex pNewCastIndex) PURE; /* Category Managing casts */ /* Description Creates a new cast and add it to the movie's cast list. Returns the position of the new cast in the pNewCastIndex argument. */ STDMETHOD(AddExternalCast) (THIS_ PMoaChar pCastName, /* The user reference name for the cast */ PMoaChar pPathName, /* The full path name for an external cast */ PMoaDrCastIndex pNewCastIndex) /* PMoaDrCastIndex for the position in the cast list */ PURE; /* Category Managing casts */ /* Description Adds an existing external cast to the movie's cast list. Returns in pNewCastIndex the position of the cast in the movie's cast list. */ STDMETHOD(RemoveCast)(THIS_ MoaDrCastIndex castIndexToRemove) /* MoaDrCastIndex for the cast to remove */ PURE; /* Category Managing casts */ /* Description Removes the cast specified by castToRemove from the movie's cast list. */ STDMETHOD(GetCMRefFromMemberName)(THIS_ PMoaChar pMemberName, /* Pointer to a null-terminated C string containing the cast member name of interest */ PMoaDrCMRef pCastMemRef) /* Pointer to a MoaDrCMRef to receive cast member reference */ PURE; /* Category Managing casts */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=229>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=361>Successful</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=229>kMoaDrErr_CastMemNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=361>Cast member not found </TD></TR> </TABLE> */ /* Description Obtains the cast member reference (MoaDrCMRef) for a cast member from its name. This method scans all of the casts for the movie, and returns the MoaDrCMRef for the first cast member whose name matches the one supplied. If no cast member is found with the specified name, kMoaDrErr_CastMemNotFound is returned and pCastMemRef is set to a null reference . Use CMRef_IsNull() to test the result. */ STDMETHOD(GetCastMemFromCMRef)(THIS_ PMoaDrCMRef pCastMemRef, /* Pointer to a MoaDrCMRef which specifies the cast member of interest */ PIMoaDrCastMem * ppIMoaDrCastMem) /* Pointer to a PIMoaDrCastMem to receive the interface for the cast member */ PURE; /* Category Acquiring ImoaDrCastMem */ /* Description Obtains the IMoaDrCastMem interface for the cast member with the supplied cast member reference. The cast member reference specifies the movieCastIndex (index to cast in the movie) and memberIndex (index to cast member slot position within the cast); use the CMRef_ macros in drtypes.h to create and access a 0. The caller owns the returned interface and is responsible for releasing it when it is no longer needed. */ STDMETHOD(GetCMRefFromCMId)(THIS_ PMoaDrCMId pCastMemId,/* Pointer to a MoaDrCMId identifying the cast member to search for*/ PMoaDrCMRef pCastMemRef)/* Pointer to a MoaDrCMRef to receive cast member reference */ PURE; /* Category Managing casts */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=229>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=361>Successful</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=229>kMoaDrErr_CastMemNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=361>Cast member not found </TD></TR> </TABLE> */ /* Description Obtains the cast member reference (MoaDrCMRef) for a cast member from its unique identifier. This method scans all of the casts for the movie, and returns the MoaDrCMRef for the cast member whose id matches the one supplied. If no cast member is found with the specified id, kMoaDrErr_CastMemNotFound is returned and pCastMemRef is set to a null reference . Use CMRef_IsNull() to test the result. */ STDMETHOD(GetCMIdFromCMRef)(THIS_ PMoaDrCMRef pCastMemRef,/* Pointer to a MoaDrCMRef identifying the cast member we want a unique ID from*/ PMoaDrCMId pCastMemId) /* Pointer to a MoaDrCMId to recieve the unique cast member identifier */ PURE; /* Category managing casts */ /* Description Obtains a unique identifier ( MoaDrCMId) for the cast member referred to by pCastMemRef. This identifer can be used to retrieve the MoaDrCMRef for this cast member at a later time, even if the cast member has been moved across cast boundaries. */ STDMETHOD(UpdateStageRect) (THIS_ MoaRect * pWindowRect, /* Pointer to a MoaRect describing the area of the stage window to update */ MoaRect * pBufferRect) /* Pointer to a MoaRect describing the area of the offscreen buffer from where to update */ PURE; /* Category Imaging support */ /* Description Updates a rectangular area of the stage window from a rectangular area of the stage's offscreen buffer. Stretching or shrinking of parts of the image can be achieved by using a windowRect which differs in size from the bufferRect. Note that this call does not cause all sprites on the stage to be reimaged; it simply refreshes the stage window from Director's offscreen compositing buffer. */ STDMETHOD(GetStageWindowGC)(THIS_ PIMoaMmGC * ppWindowGC) /* Pointer to a IMoaMmGC interface for the stage window */ PURE; /* Category Imaging support */ /* Description Obtains the graphics context for the stage window. This includes the bounds rectangle, pixel depth, as well as platform-specific information (such as the WindowPtr of the window on the Macintosh, or the HWND on Windows). This information is valid only for the duration of the current call into your Xtra method, because the stage window can change in depth or size at any time (and may be disposed of and reallocated in the process). You must release the graphics context when done by calling its Release() method. Important note about graphic contexts This method should only be called by Lingo and Tool Xtras to do temporary drawing into the stage window. It should be called just before doing your drawing, and the acquired interface should be released before returning control to the calling application. This is because nativeGCInfo for the stage buffer can become invalid at any time. For example, the buffer may be dumped and recreated if window size, monitor depth, or other display characteristics change. It's not always possible to obtain the a graphics context for the stage window. During registration, startup, and shut-down, internal movie data structures may not be initialized, thus trying to get the GC for it will return the err kMoaDrErr_MovieNotOpen. Xtra developers should never attempt to acquire a graphics context and hold onto it; instead, you should acquire the interface each time you need to draw and release it before your method returns. Also, GetStageWindowGC() should not be used to get a parent window for Windows(TM) dialogs. The correct procedure is to use the IMoaMmUtils Windows API cover methods such as WinDialogBox() and WinDialogBoxParam(). If you're putting up a system dialog on Windows, use WinGetParent() to get the parent HWND to use, and bracket your dialog call with WinPrepareDialogBox() and WinUnprepareDialogBox(). Finally, these calls should not be used for sprite or transition drawing. Instead, use the graphic context passed to you explicitly in IMoaMmSpriteActor::Image() or IMoaDrTransitionActor::Continue(). If you do attempt to use this context, your Xtra will not work correctly in MIAWs, export, or other applications such as Authorware. */ STDMETHOD(GetStageBufferGC)(THIS_ PIMoaMmGC * ppBufferGC) /* Pointer to a IMoaMmGC interface for the stage offscreen buffer */ PURE; /* Category Imaging support */ /* Description Obtains the graphics context for the stage offscreen buffer. This includes the bounds rectangle, pixel depth, as well as platform-specific information (such as the WindowPtr of the window on the Macintosh or the HWND on Windows). This information is valid only for the duration of the current call into your Xtra method, because the stage window can change in depth or size at any time (and may be disposed of and reallocated in the process). You must release the graphics context when done by calling its Release() method. Important note about graphic contexts This method should only be called by Lingo and Tool Xtras to do temporary drawing into the stage window. It should be called just before doing your drawing, and the acquired interface should be released before returning control to the calling application. This is because nativeGCInfo for the stage buffer can become invalid at any time. For example, the buffer may be dumped and recreated if window size, monitor depth, or other display characteristics change. It's not always possible to obtain the a graphics context for the stage buffer. During registration, startup, and shut-down, internal movie data structures may not be initialized, thus trying to get the GC for it will return the err kMoaDrErr_MovieNotOpen. Xtra developers should never attempt to acquire a graphics context and hold onto it; instead, you should acquire the interface each time you need to draw and release it before your method returns. Finally, this method should not be called to get a context for sprite or transition drawing. Instead, use the graphic context passed to you explicitly in IMoaMmSpriteActor::Image() or IMoaDrTransitionActor::Continue(). If you attempt to use this context, your Xtra will not work correctly in MIAWs, export, or other applications such as Authorware. */ STDMETHOD(GetFrameIndexFromLabel)(THIS_ PMoaChar pLabelName, /* Pointer to a null-terminated C-string containing the name of the marker associated with the score frame (case-insensitive) */ PMoaDrFrameIndex pFrameIndex) /* Pointer to a MoaDrFrameIndex to receive the frame number of the label (marker) */ PURE; /* Category Accessing frame labels */ /* Returns <TABLE BORDER="2"> <TR><TD WIDTH=133>kMoaErr_NoErr</TD><TD WIDTH=457>if successful, kMoaDrErr_LabelNotFound if marker doesn't exist. </TD></TR> </TABLE> */ /* Description Obtains the frame number from a label (marker) name. */ STDMETHOD(GetFrameLabelFromIndex)(THIS_ MoaDrFrameIndex frameIndex, /* A MoaDrFrameIndex holding the frame number of interest */ PMoaChar pLabelName, /* Pointer to a string buffer to receive the name of the marker associated with the given score frame */ MoaLong maxLen) /* The length in bytes of the caller's C string buffer */ PURE; /* Category Accessing frame labels */ /* Description Obtains the name of the label (marker) at a given score frame number. Returns an empty string if no marker exists for the frame. */ STDMETHOD(SetFrameLabel)(THIS_ MoaDrFrameIndex frameIndex, /* A MoaDrFrameIndex holding the number of the frame */ PMoaChar pLabelName) /* Pointer to a MoaChar to receive the name of the marker associated with the given score frame */ PURE; /* Category Accessing frame labels */ /* Description Adds, modifies, or deletes a score label (marker) or a frame. You pass in the frame number and a C string for the new label. If a label doesn't exist for that frame, one will be added. If one does exist, it'll be replaced with the new one you specify. If you pass in NULL for pLabelName, any current label for that frame is deleted. */ STDMETHOD(GetScoreAccess)(THIS_ PIMoaDrScoreAccess * ppScore) PURE; /* Category Acquiring IMoaDrScoreAccess */ /* Description Gets a ScoreAccess interface provider for the movie's score. */ STDMETHOD(Save)(THIS_ PMoaChar pNewPathName, /* Null-terminated C string for the path */ MoaBoolParam bSaveExtCasts) PURE; /* Category Managing movies */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=157>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=433>Successful</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=157>kMoaDrErr_DiskIO </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=433>IO error during file access </TD></TR> </TABLE> */ /* Description Saves the movie to the path. Specify the complete path, including file name, to save the cast to a new file. Pass NULL as pNewPathName to save the cast in its previous file. */ STDMETHOD(SendSpriteMessage)(THIS_ MoaDrSpriteChanIndex chanIndex, /* Channel number of sprite to which to send the message. Valid values are from 1 to 48. */ MoaMmSymbol handlerName, /* Symbol for the handler (message) name */ MoaLong nArgs, /* Number of arguments you're passing */ PMoaMmValue pArgs, /* Pointer to an array of MoaMmValues containing arguments */ PMoaMmValue pResult, /* Pointer to a MoaMmValue to receive a result */ MoaBool * pHandled) /* arguments to a MoaBool to receive TRUE if the message was handled somewhere down the chain or FALSE if it was not. */ PURE; /* Category Scripting support */ /* Description Sends a sprite message to be passed through the standard Director sprite message hierarchy beginning with the sprite script of the sprite in the specified channel. This method is similar to IMoaDrSpriteCallback::SendSpriteMessage().You must pass in NULL to pResult if you do not expect a result; you must pass in a valid pointer if you do expect a result. */ STDMETHOD(MoveCastMember)(THIS_ PMoaDrCMRef pSrcMemRef,/* Pointer to a MoaDrCMRef containing the cast member you want to move */ PMoaDrCMRef pDestMemRef)/* Pointer to the MoaDrCMRef containing the location you want to move it to */ PURE; /* Category Managing Casts */ /* Description Moves the cast member in the location referred to by pSrcMemRef to the location referred to by pDestMemRef. If there is an existing cast member in the destination slot, it will be removed. */ }; typedef IMoaDrMovie2 * PIMoaDrMovie2; /* ---------------------------------------------------------------------------- / / IMoaDrMovieStage / / -------------------------------------------------------------------------- */ /* IID_IMoaDrMovieStage */ DEFINE_GUID(IID_IMoaDrMovieStage, 0x4418DAB2L, 0xFEF7, 0x11D2, 0x8C, 0xDC, 0x00, 0x05, 0x02, 0x0E, 0x2E, 0x6D); #undef INTERFACE #define INTERFACE IMoaDrMovieStage DECLARE_INTERFACE_(IMoaDrMovieStage, IMoaUnknown) /* Description The IMoaDrMovieStage interface provides access to new stage-related functions associated with a movie. IMoaDrMovieStage is an additional interface on the same movie class that supports IMoaDrMovie and IMoaDrMovie2. You acquire a movie interface by calling the IMoaDrPlayer methods GetActiveMovie() or GetNthMovie(). This returns to you an IMoaDrMovie interface. You can calling the QueryInterface method off this interface to retrieve an IMoaDrMovieStage interface Movie properties */ { STD_IUNKNOWN_METHODS STDMETHOD(TransformStagePointUnscaledToScaled)(THIS_ PMoaPoint pStagePoint) /* IN: The unscaled point, OUT: The scaled point */ PURE; /* Category Movie stage utility functions */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Point valid and transformed point was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pStagePoint </FONT>passed in </TD></TR> </TABLE> */ /* Description Transforms a given point from unscaled to scaled stage coordinates. Unscaled is the coordinate space of the original, un-zoomed movie. Scaled is the coordinate space of the movie scaled to its current drawRect. */ STDMETHOD(TransformStagePointScaledToUnscaled)(THIS_ PMoaPoint pStagePoint) /* IN: The scaled point, OUT: The unscaled point */ PURE; /* Category Movie stage utility functions */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Point valid and transformed point was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pStagePoint </FONT>passed in </TD></TR> </TABLE> */ /* Description Transforms a given point from scaled to unscaled stage coordinates. Scaled is the coordinate space of the movie scaled to its current drawRect. Unscaled is the coordinate space of the original, un-zoomed movie. */ }; typedef IMoaDrMovieStage * PIMoaDrMovieStage; /* ---------------------------------------------------------------------------- / / IMoaDrPlayer / / -------------------------------------------------------------------------- */ /* IID_IMoaDrPlayer: AC401B780000FA7D00000800072C6326 */ DEFINE_GUID(IID_IMoaDrPlayer, 0xAC401B78L, 0x0000, 0xFA7D, 0x00, 0x00, 0x08, 0x00, 0x07, 0x2C, 0x63, 0x26); #undef INTERFACE #define INTERFACE IMoaDrPlayer DECLARE_INTERFACE_(IMoaDrPlayer, IMoaMmPropOwner) /* Descripiton The IMoaDrPlayer interface provides top-level access to the interfaces representing the Director object model. IMoaDrPlayer is provided by the Director callback object, and is acquired by calling QueryInterface() on the IMoaCallback interface, provided through the pCallback instance variable of all MOA objects. From an instance of the IMoaDrPlayer interface, you can access the movies, casts, cast members, and scores that make up all open movies. Player properties IMoaDrPlayer inherits from the IMoaMmPropOwner interface, providing for access to data through the properties mechanism described in the chapter "Properties" earlier in this document. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ PMoaMmValue pPropValue) /* Pointer to a caller-owned MoaMmValue structure to receive the value of the property */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists and value was returned </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue</FONT> passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Property exists but couldn't get due to internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=235>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=355>Couldn't allocate memory for other value data </TD></TR> </TABLE> */ /* Description Obtains the value of the specified player property. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol().The caller is responsible for releasing the value with IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* The MoaMmSymbol for the property of interest */ ConstPMoaMmValue pPropValue) /* Pointer to a caller-owned MoaMmValue structure from which to copy the value */ PURE; /* Category Property owner methods */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists and value was set </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_BadParam </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Invalid <FONT SIZE=2 FACE="Courier New">pPropValue </FONT>passed in </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PropertyNotFound </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property isn't supported by this class </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_InternalError </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Property exists, value ok, can't set--internal error </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_NoMemForString </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Can't allocate memory for setting string value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_OutOfMem </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Can't allocate memory for setting other value data </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_IntegerExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: integer value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_SymbolExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: symbol value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_FloatExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: float value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_StringExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: string value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_PointExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: point value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_RectExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: rect value expected </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaMmErr_ValueTypeMismatch </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: other value expected (non-specific) </TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef value expected </TD></TR> </TABLE> */ /* Description Sets a player property to a new value. To get the symbol from a string, use the IMoaMmUtils::StringToSymbol(). The caller continues to maintain ownership of the value passed in, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(CallHandler) (THIS_ MoaMmSymbol name, /* The MoaMmSymbol for the name of the method to call */ MoaLong nArgs, /* The number of arguments you are passing to the handler */ PMoaMmValue pArgs, /* The array of MoaMmValue arguments */ PMoaMmValue pResult) /* Pointer to a caller-owned MoaMmValue to receive a result value from the handler */ PURE; /* Category Scripting support */ /* Description Calls the Lingo handler name in the currently active movie. The nArgs argument is the number of arguments to the handler, the pArgs argument is a MoaMmList of arguments as MoaMmValues. You must pass in NULL to pResult if you do not expect a result. You must pass in a valid pointer if you do expect a result. This method has the same behavior as obtaining the active movie interface by calling GetActiveMovie(), and then calling IMoaDrMovie::CallHandler(). This method is supplied as a convenience, as it eliminates the extra call needed to GetActiveMovie() for this common operation. */ STDMETHOD(GetActiveMovie)(THIS_ PIMoaDrMovie * ppIMoaDrMovie) /* Pointer to a PIMoaDrMovie to receive new interface */ PURE; /* Category Movie access */ /* Description Gets an interface to the currently active movie. The active movie may vary depending upon the context in which this method is called. If there are no MIAWs executing, the active movie is the single main movie currently being played. If MIAWs are present, the active movie can be a MIAW. This is the case if a Lingo Xtra is being called by a MIAW Lingo script; if an asset Xtra is being used by a MIAW; or if a Transition Xtra is being called on behalf of a MIAW. The caller is responsible for releasing the movie interface when it is no longer needed. */ STDMETHOD(GetMovieCount)(THIS_ MoaLong * pMovieCount) /* Pointer to a MoaLong to receive count of open movies */ PURE; /* Category Movie access */ /* Description Obtains the current number of movies open in the player. In Director 5.0, there is always at least one open movie, the main stage movie. Each open movie in a window also contributes to the movie count. Using GetNthMovie(), you can access any open movie directly. */ STDMETHOD(GetNthMovie)(THIS_ MoaLong movieIndex, /* Index of movie to obtain interface for; ranges from 1 to the number of open movies */ PIMoaDrMovie * ppIMoaDrMovie) /* Pointer to a PIMoaDrMovie to receive new interface */ PURE; /* Category Movie access */ /* Description Gets an interface to the nth movie in the player's movie list. There's always at least one open movie in Director 5.0, the main stage movie. Use GetMovieCount() to determine the number of open movies. Using this method, you could, for example, access data in a Movie In A Window even though you're currently being called in the context of the main stage movie. The caller is responsible for releasing the movie interface when it is no longer needed.Gets an interface to the nth movie in the player's movie list. There's */ STDMETHOD(ResolveFileName)(THIS_ ConstPMoaChar pFileName, /* Pointer to C string of filename in native platform format to resolve */ PMoaChar pPathName, /* Pointer to C string to receive resolved full pathname */ MoaLong maxLen) /* Size of the caller's pPathName buffer */ PURE; /* Category Accessing files */ /* Description Resolves a file name to a full path name using Director's standard filename resolution algorithm. This can include scanning the searchPaths, and so on, for the appropriate file. Director's "@:" filename notation is also supported here. */ STDMETHOD(GetCastMemTypeCount)(THIS_ MoaLong * pTypeCount) /* Pointer to a MoaLong to receive the count */ PURE; /* Category Cast member access */ /* Description Obtains the number of currently registered cast member types. This value is the sum of Director's built-in types and any types registered by external asset Xtras. */ STDMETHOD(GetNthCastMemTypeSymbol)(THIS_ MoaLong typeIndex, /* Index (from 1 to GetCastMemTypeCount()) of the cast member type of interest */ PMoaMmSymbol pSymbol) /* Pointer to a MoaMmSymbol to receive the type's symbol */ PURE; /* Category Cast member access */ /* Description Obtains the unique run-time symbol for the specified cast member type by index. This symbol is then passed as a parameter to callback methods operating on cast member types, such as GetCastMemTypeDisplayName(). */ STDMETHOD(GetCastMemTypeDisplayName)(THIS_ MoaMmSymbol typeSymbol, /* The symbol of the type of interest */ PMoaChar pName, /* Pointer to buffer to receive null-terminated C string text of the display name */ MoaLong maxLen) /* Size of the caller's name buffer */ PURE; /* Category Cast member access */ /* Description Obtains the user-readable text string associated with a cast member type. This is the same string that appears in the Insert submenu in Director. You can obtain typeSymbol using StringToSymbol() or GetNthCastMemTypeSymbol(). */ STDMETHOD(GetGlobalVarValue)(THIS_ MoaMmSymbol globalVarName, /* The symbol of the global variable of interest */ PMoaMmValue pValue) /* Pointer to a MoaMmValue to receive the value */ PURE; /* Category Scripting support */ /* Description Obtains the value of a Lingo global variable. Use IMoaMmUtils::StringToSymbol() to get a symbol from a string for globalVarName. The caller is responsible for releasing the value with IMoaMmUtils::ValueRelease() when it is no longer needed. */ STDMETHOD(SetGlobalVarValue)(THIS_ MoaMmSymbol globalVarName, /* The symbol of the global variable of interest */ PMoaMmValue pValue) /* Pointer to a MoaMmValue to copy the new value from */ PURE; /* Category Scripting support */ /* Description Sets the value of a Lingo global variable. Use IMoaDrUtils-&gt;StringToSymbol() to get a symbol from a string for globalVarName. The caller maintains ownership of the value passed in, and should release it using IMoaMmUtils::ValueRelease() when it is no longer needed. */ }; typedef IMoaDrPlayer * PIMoaDrPlayer; /* Synonyms for old method names */ #define CallHandlerInActiveMovie(me, name, nargs, pargs, presult) \ CallHandler(me, name, nargs, pargs, presult) /* ---------------------------------------------------------------------------- / / IMoaDrUtils - Director-specific utility functions / / -------------------------------------------------------------------------- */ /* IID_IMoaDrUtils: AC96CFC00045659700000040105023FB */ DEFINE_GUID(IID_IMoaDrUtils, 0xAC96CFC0L, 0x0045, 0x6597, 0x00, 0x00, 0x00, 0x40, 0x10, 0x50, 0x23, 0xFB); #undef INTERFACE #define INTERFACE IMoaDrUtils DECLARE_INTERFACE_(IMoaDrUtils, IMoaUnknown) /* Description This interface provides Director-specific utilities. It complements the features of the IMoaMmUtils interface, providing application-specific services to Xtras. */ { STD_IUNKNOWN_METHODS STDMETHOD(ValueToCMRef)(THIS_ ConstPMoaMmValue pValue, /* Pointer to a cast member reference type */ PMoaDrCMRef pCMRef) /* Pointer to a MoaDrCMRef to receive the result */ PURE; /* Category Data conversion */ /* Returns <TABLE BORDER="2"> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaErr_NoErr </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>successful</TD></TR> <TR><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=253>kMoaDrErr_CastMemberExpected </TD><TD ALIGN="LEFT" VALIGN="TOP" WIDTH=337>Type mismatch: CMRef expected </TD></TR> </TABLE> */ /* Description Obtains the MoaDrCMRef for a cast member reference-type MoaMmValue. pCMRef is a pointer to a MoaDrCMRef to receive the result. Returns kMoaDrErr_CastMemberExpected if pValue is not an cast member reference-type value. */ STDMETHOD(CMRefToValue)(THIS_ ConstPMoaDrCMRef pCMRef, /* Pointer to a ConstPMoaDrCMRef to be used as the basis for the new value */ PMoaMmValue pValue) /* Pointer to MoaMmValue to receive the result */ PURE; /* Category Data conversion */ /* Description Creates a new cast member reference-type MoaMmValue from a MoaDrCMRef. pCMRef is a pointer to a MoaDrCMRef to be used as the basis for the new value. pValue contains a pointer to a MoaMmValue to receive the result. This call populates the MoaMmValue at pValue with a new MoaMmValue, overwriting any current value. Make sure to release any preexisting value before making this call. The caller is responsible for releasing the returned value using IMoaMmUtils::ValueRelease(). */ STDMETHOD(NewMediaInfo)(THIS_ MoaMmSymbol labelSymbol, MoaMmSymbol formatSymbol, PMoaVoid mediaData, MoaLong options, /* Used when setting image media. Use a kMoaDrImgMediaOpts_ constant */ PMoaVoid aux, /* Pointer to a MoaDrImageAuxInfo structure if you use the "AuxInfo" option */ PMoaDrMediaInfo pMediaInfo) PURE; /* Category Media management */ /* Description Populates a MoaDrMediaInfo structure. This call does not allocate any media data, it simply populates the supplied structure. If populating the structure for a call to SetMedia(), you must populate the labelSymbol, formatSymbol, mediaData , options , and aux fields accordingly. options tells Director how the palette and color depth of the image should be set; it currently varies only for "image" label media. aux is used only when specifying AuxInfo options; it is ignored for other options. If populating the structure for a call to GetMedia(), only the labelSymbol and formatSymbol fields are required. Before a GetMedia(), SetMedia(), or AttachMedia() call, use this method to fill out the supplied structure, specifying NULL for the aux field. Using this call forces you to fill out all the needed parameters. When setting or getting any media label other than "image", use the value kMoaDrMediaOpts_None for the options argument. When setting or attaching an "image" media label type, there are a number of image media constants to use as the options argument. These are described in the "Constants" section later in this document. */ STDMETHOD(MediaRelease)(THIS_ PMoaDrMediaInfo pMediaInfo) PURE; /* Category Media management */ /* Description Releases the bulk media data referenced by the MoaDrMediaInfo structure in pMediaInfo. The formatSymbol and mediaData fields of pMediaInfo must be valid on entry. If the format of the media data is unknown to the host application, kMoaDrErr_MediaFormatNotSupported is returned and the media data is not be released. You can also release the data yourself using the appropriate native memory manager call (if the media data is a native data type), such as KillPicture() for "macPICT". The host application does not guarantee that it can dispose media data of all formats; only those that are built-in data types of the host application are supported by this call. */ STDMETHOD(NewScoreAccess)(THIS_ PIMoaDrScoreAccess * ppScore) PURE; /* Category Acquiring IMoaDrScoreAccess */ /* Description Creates a new instance of an object supporting IMoaDrScoreAccess. The IMoaDrScoreAccess interface is used to access and edit score data for movies and film loops. Normally, if you want to access an existing movie or film loop, you would call IMoaDrMovie::GetScoreAccess() or IMoaDrCastMem::GetScoreAccess(). However, if you do not want to create new score from scratch which is not yet associated with a movie or film loop, this method can be used. To save the resulting score, you must call the IMoaDrScoreAccess::SetOwner() method to associate an owner object with the score, and then call Commit() to save the score to the object */ STDMETHOD(RegisterNotificationClient)(THIS_ PIMoaDrNotificationClient pNotificationClient, /* Pointer to a pre-existing IMoaDrNotificationClient interface */ MoaDrNotifyType notifyType, /* Value indicating the type of notification requested */ PMoaVoid refCon) PURE; /* Category Managing notification clients */ /* Description Registers a notification client object with the host application. Notification clients are used to receive notification from the host application when certain events occur. pClient is a pointer to a pre-existing IMoaDrNotificationClient interface. notifyType is a value indicating the type of notification requested. When the internal event occurs, the host application calls the Notify() method of the specified IMoaDrNotificationClient interface. Additional notification-specific information can be supplied by the host application in the Notify() method's refCon parameter. To cease notification for a given PIMoaDrNotifyClient and notifyType, call UnregisterNotifyClient(). The same IMoaDrNotificationClient interface can be used to service multiple notifyTypes. When calling UnregisterNotificationClient(), only the notification for the supplied notifyType is disabled. Acceptable values for notifyType are: kMoaDrNotifyType_DocFileIO Windows(TM) versiononly Notification occurs whenever a chunk is read from or written to any a movie or cast file document in use by the host application. This is most interesting for Windows 3.1, where the operating system fails to read from a CD-ROM if Redbook audio is playing off of the same device. Use this hook to cease Redbook audio playing, so that subsequent document chunk file reads and writes will be successful. In the refCon argument of the Notify() method, the host application passes a PMoaChar, a pointer to a character array specifying the pathname of the file being read to or written from (a null-terminated C string). */ STDMETHOD(UnregisterNotificationClient)(THIS_ PIMoaDrNotificationClient pNotificationClient, /* Pointer to a pre-existing IMoaDrNotificationClient interface */ MoaDrNotifyType notifyType, /* Value indicating the type of notification requested */ PMoaVoid refCon) PURE; /* Category Managing notification clients */ /* Description Unregisters a notification client previously registered by a call to RegisterNotificationClient(). The same IMoaDrNotificationClient interface can be used to service multiple notifyTypes. When calling UnregisterNotificationClient(), only the notification for the supplied notifyType is disabled. */ }; typedef IMoaDrUtils * PIMoaDrUtils; /* ---------------------------------------------------------------------------- / / IMoaDrStyleAccess2 / / Text style-related utility functions / / / These are equivalent to the Macintosh GetFNum() and / GetFontName() calls. / / -------------------------------------------------------------------------- */ /* IID_IMoaDrStyleAccess2 */ DEFINE_GUID(IID_IMoaDrStyleAccess2, 0xD974E0C4L, 0x5D88, 0x11CF, 0xBA, 0x41, 0x08, 0x00, 0x07, 0x9F, 0x01, 0x6C); #undef INTERFACE #define INTERFACE IMoaDrStyleAccess2 DECLARE_INTERFACE_(IMoaDrStyleAccess2, IMoaUnknown) /* Descripiton Provides helpers for accessing text edit style data. This interface is available on Macintosh and Windows. On the Macintosh, the functionality is also available directly through the Macintosh toolbox. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetFontNumber)(THIS_ PMoaChar pFontName, /* Pointer to a C null-terminated C string containing the name of the font of interest. Case is not significant.*/ MoaLong * pFontNumber, /* Pointer to a MoaLong to receive the font number corresponding with pFontName */ PIMoaDrCast pCast) /* pointer to the director cast storing the font information we are accessing */ ; /* Description Gets the font identification number associated with a font name string. This identification number corresponds to values in the "scrpFont" field of the ScrpSTElement sub-structure in moaTEStyles. This method is equivalent to the Macintosh GetFNum() toolbox call. Currently this method always returns kMoaErr_NoErr. */ STDMETHOD(GetFontName)(THIS_ MoaLong fontNumber, /* Number of the font of interest */ PMoaChar pFontName, /* Pointer to a buffer to receive a null-terminated C string for the name of the font */ MoaLong maxLen, /* Size of the string buffer at pFontName */ PIMoaDrCast pCast) /* pointer to the director cast storing the font information we are accessing */ ; /* Description Gets the font name associated with a font identification number. This identification number corresponds to values in the "scrpFont" field of the ScrpSTElement sub-structure in moaTEStyles. This method is equivalent to Macintosh GetFontName() toolbox call. */ }; typedef IMoaDrStyleAccess2 * PIMoaDrStyleAccess2; /* ---------------------------------------------------------------------------- / / IMoaDrStyleAccess / / WARNING: This interface is obsolete! Using this interface in Director 6.0 and on / may have unpredictable results. Use the IMoaDrStyleAccess2 interface instead. / / -------------------------------------------------------------------------- */ /* IID_IMoaDrStyleAccess */ DEFINE_GUID(IID_IMoaDrStyleAccess, 0xD974E0C4L, 0x5D88, 0x11CF, 0xBA, 0x41, 0x08, 0x00, 0x07, 0x9F, 0x01, 0x6C); #undef INTERFACE #define INTERFACE IMoaDrStyleAccess DECLARE_INTERFACE_(IMoaDrStyleAccess, IMoaUnknown) /* Descripiton Provides helpers for accessing text edit style data. This interface is available on Macintosh and Windows. On the Macintosh, the functionality is also available directly through the Macintosh toolbox. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetFontNumber)(THIS_ PMoaChar pFontName, /* Pointer to a C null-terminated C string containing the name of the font of interest. Case is not significant.*/ MoaLong * pFontNumber) /* Pointer to a MoaLong to receive the font number corresponding with pFontName */ ; /* Description Gets the font identification number associated with a font name string. This identification number corresponds to values in the "scrpFont" field of the ScrpSTElement sub-structure in moaTEStyles. This method is equivalent to the Macintosh GetFNum() toolbox call. Currently this method always returns kMoaErr_NoErr. */ STDMETHOD(GetFontName)(THIS_ MoaLong fontNumber, /* Number of the font of interest */ PMoaChar pFontName, /* Pointer to a buffer to receive a null-terminated C string for the name of the font */ MoaLong maxLen) /* Size of the string buffer at pFontName */ ; /* Description Gets the font name associated with a font identification number. This identification number corresponds to values in the "scrpFont" field of the ScrpSTElement sub-structure in moaTEStyles. This method is equivalent to Macintosh GetFontName() toolbox call. */ }; typedef IMoaDrStyleAccess * PIMoaDrStyleAccess; /* ---------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- / / IMoaDrAssetCallback - Director-specific callback interface for asset xtras. / / --------------------------------------------------------------------------- */ /* IID_IMoaDrAssetCallback: ACC33F91013724E70000080007FC20C1 */ DEFINE_GUID(IID_IMoaDrAssetCallback, 0xACC33F91L, 0x0137, 0x24E7, 0x00, 0x00, 0x08, 0x00, 0x07, 0xFC, 0x20, 0xC1); #undef INTERFACE #define INTERFACE IMoaDrAssetCallback DECLARE_INTERFACE_(IMoaDrAssetCallback, IMoaMmPropOwner) /* Description The IMoaDrAssetCallback interface is provided in Director by the class that implements IMoaMmAssetCallback, which is provided by through the asset initialization method IMoaMmXAsset::SetCallback(). To acquire IMoaDrAssetCallback, the asset can call QueryInterface() on IMoaMmAssetCallback. This interface provides additional, Director-specific callback services to a media asset. In Director, an asset Xtra has both an external representation, implemented by the Xtra developer, and an internal representation, provided by Director. The Xtra developer defines custom behavior by implementing standard asset Xtra interfaces. This interface provides controlled access to the internal representation of the Xtra provided by Director. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetProp)(THIS_ MoaMmSymbol symbol, /* MoaMmSymbol representing the property to get */ PMoaMmValue pPropValue) /* Pointer to a MoaMmValue to receive the property's value */ PURE; /* Category Property owner */ /* Returns kMoaErr_NoErr Property exists and value was returned kMoaErr_BadParam Invalid pPropValue passed in kMoaMmErr_PropertyNotFound Property isn't supported by this class kMoaMmErr_InternalError Property exists but couldn't get due to internal err kMoaMmErr_NoMemForString Couldn't allocate memory for string value data kMoaErr_OutOfMem Couldn't allocate memory for other value data */ /* Description Gets any property of the cast member associated with your asset. This includes both built-in ones handled by the host application (such as name in Director for cast member name), as well as your own properties. If you retrieve your own properties, it may result in a callback to your own GetProp() method; be careful not to get stuck in a loop. */ STDMETHOD(SetProp)(THIS_ MoaMmSymbol symbol, /* MoaMmSymbol representing the property to set */ ConstPMoaMmValue pPropValue) /* Pointer to a ConstPMoaMmValue containing the property value */ PURE; /* Category Property owner */ /* Returns kMoaErr_NoErr Property exists and value was set kMoaErr_BadParam Invalid pPropValue passed in kMoaMmErr_PropertyNotFound Property isn't supported by this class kMoaMmErr_InternalError Property exists, value ok, can't set--internal error kMoaMmErr_NoMemForString Can't allocate memory for setting string value data kMoaErr_OutOfMem Can't allocate memory for setting other value data kMoaMmErr_IntegerExpected Type mismatch: integer value expected kMoaMmErr_SymbolExpected Type mismatch: symbol valueexpected kMoaMmErr_FloatExpected Type mismatch: float value expected kMoaMmErr_StringExpected Type mismatch: string value expected kMoaMmErr_PointExpected Type mismatch: point value expected kMoaMmErr_RectExpected Type mismatch: rect valueexpected kMoaMmErr_ValueTypeMismatch Type mismatch: other value expected (non-specific) kMoaDrErr_CastMemberExpected Type mismatch: CMRef value expected */ /* Description Sets any property of the cast member associated with your asset. This includes both built-in ones handled by the host application (such as name in Director for cast member name), as well as your own properties. This may result in a call back to your own SetProp() method; be careful not to get stuck in a loop. */ STDMETHOD(GetCMRef)(THIS_ PMoaDrCMRef pCMRef) /* Pointer to a MoaDrCMRef to receive the reference for the cast member associated with your asset */ PURE; /* Category Internal cast member access */ /* Description Gets the cast member reference for the cast member associated with your asset. This lets you determine the Director cast member with your asset is associated. The cast index supplied in this reference is relative to the active movie. */ STDMETHOD(CallCMHandler)(THIS_ MoaMmSymbol handlerName, /* MoaMmSymbol representing the handler to call */ MoaLong nArgs, /* Number of arguments, excluding the Xtra instance in pArgs[0] */ PMoaMmValue pArgs, /* Array of arguments, with the first valid argument at pArgs[1] */ PMoaMmValue pResult, /* Pointer to a MoaMmValue to receive the result */ MoaBool * pHandled) /* Boolean value */ PURE; /* Category Scripting support */ /* Description Calls a handler defined in the asset's cast member script. For CallCMHandler(), only the cast member script is checked; the message does not proceed up to the movie or frame level, as it does with the sprite SendMessage() call. Caller supplies a symbol for handler to call (name), the arguments (nArgs, pArgs), and a pointer to a MoaMmValue to receive a result, if any, from the handler call. Upon return, pHandled is set to TRUE if the call was handled, that is the handler existed in the cast member script. If message was not handled, it silently disappears and FALSE is returned. */ }; typedef IMoaDrAssetCallback * PIMoaDrAssetCallback; /* ---------------------------------------------------------------------------- / / IMoaDrSpriteCallback - Director-specific callback interface for / sprite asset xtras. / / --------------------------------------------------------------------------- */ /* IID_IMoaDrSpriteCallback: ACC33FCA013732510000080007FC20C1 */ DEFINE_GUID(IID_IMoaDrSpriteCallback, 0xACC33FCAL, 0x0137, 0x3251, 0x00, 0x00, 0x08, 0x00, 0x07, 0xFC, 0x20, 0xC1); #undef INTERFACE #define INTERFACE IMoaDrSpriteCallback DECLARE_INTERFACE_(IMoaDrSpriteCallback, IMoaUnknown) /* Description The IMoaDrSpriteCallback interface is provided in Director by the class that implements IMoaMmSpriteCallback, which is provided through the sprite actor initialization method IMoaMmXSpriteActor::SetCallback(). To acquire IMoaDrSpriteCallback, the asset can call QueryInterface() on IMoaMmSpriteCallback. This interface provides additional, Director-specific callback services to a media asset. */ { STD_IUNKNOWN_METHODS STDMETHOD(GetMovie)(THIS_ PIMoaDrMovie * ppIMoaDrMovie) PURE; /* Category Acquiring IMoaDrMovie */ /* Description Gets the movie interface for the movie in which the sprite is appearing. You are responsible for releasing this interface when you're done with it. */ STDMETHOD(GetSpriteChanIndex)(THIS_ PMoaDrSpriteChanIndex pChanIndex) PURE; /* Category Sprite access */ /* Description Gets the sprite channel number for the Director sprite associated with this sprite instance. Channel numbers are 1-based. */ STDMETHOD(SendSpriteMessage)(THIS_ MoaMmSymbol handlerName, MoaLong nArgs, PMoaMmValue pArgs, PMoaMmValue pResult, MoaBool * pHandled) PURE; /* Category Scripting support */ /* Description Sends a message along the standard message hierarchy starting with the sprite. The message proceeds along the path: sprite --&gt; cast member --&gt; frame --&gt; movie until it is consumed by a script at some level. (If no such handler exists at a given level, the message proceeds to the next level. Alternatively, a Lingo script can intentionally pass a message to the next level using the pass Lingo command. The caller supplies symbol for handler to call (name), the arguments (nArgs, pArgs), and a pointer to a MoaMmValue to receive a result, if any, from the handler call. Upon return, pHandled is set to TRUE if the call was handled. If the message is not handled, it silently disappears and FALSE is returned. This method is ideal for implementing widget-type sprite Xtras. For example, if you're implementing a button Xtra, you could send a buttonClicked message whenever the button was clicked. Developers could then handle this message by putting an on buttonClicked handler in the sprite script for any object in the hierarchy: sprite, cast member, frame, movie.). The Xtra could, of course, emit multiple messages, which would be needed to implement a multi-part widget such as a scrollbar. */ }; typedef IMoaDrSpriteCallback * PIMoaDrSpriteCallback; /* ---------------------------------------------------------------------------- / / IMoaDrPaletteAccess / / -------------------------------------------------------------------------- */ /* IID_IMoaDrPlayer: AC401B780000FA7D00000800072C6326 */ DEFINE_GUID(IID_IMoaDrPaletteAccess, 0x7C29A966L, 0x4150, 0x11D0, 0xAD, 0xEF, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); /* Description The IMoaDrPaletteAccess interface is provided in Director by the main callback object. Use this interface to access the media of the built in palettes supplied by director. To acquire IMoaDrPaletteAccess, call QueryInterface() on the main callback object. */ #undef INTERFACE #define INTERFACE IMoaDrPaletteAccess DECLARE_INTERFACE_(IMoaDrPaletteAccess,IMoaUnknown) { STD_IUNKNOWN_METHODS STDMETHOD(GetBuiltInPaletteCount)(THIS_ MoaUlong * pCount /* returns the number of build in palettes in Director*/ ) PURE; /* Category Media access */ /* Description Returns the number of palettes supported internally by Director. */ STDMETHOD(GetNthBuiltInPaletteSymbol)(THIS_ MoaUlong nPalette, /* the index of the palette to access. */ PMoaMmSymbol pPaletteSymbol /* returns the symbol for the palette */ ) PURE; /* Category Media access */ /* Description Returns the symbol for the nth palette. You can pass this symbol to GetBuildInPaletteMedia to get the actual palette. */ STDMETHOD(GetBuiltInPaletteMedia)(THIS_ MoaMmSymbol paletteSymbol, /* the symbol for the palette to access */ PMoaVoid * pPaletteMedia /* returns the actual palette media */ ) PURE; /* Category Media access */ /* Description returns the palette media for the built in palette referred to by paletteSymbol. You can call GetNthBuildInPaletteSymbol to get this symbol. the palette returned is either a CTabHandle on the macintosh, or an HPALETTE on windows. */ }; typedef IMoaDrPaletteAccess * PIMoaDrPaletteAccess; /* ---------------------------------------------------------------------------- */ DEFINE_GUID(IID_IMoaDrSound, 0x57A629DEL, 0x43FD, 0x11D0, 0x91, 0x7B, 0x00, 0x05, 0x9A, 0x80, 0xE8, 0x2F); #undef INTERFACE #define INTERFACE IMoaDrSound DECLARE_INTERFACE_(IMoaDrSound,IMoaUnknown) { STD_IUNKNOWN_METHODS STDMETHOD(GetSoundChannelCount)(THIS_ MoaUlong * pCount) PURE; STDMETHOD_(MoaDrSoundChannelPlayStatus,GetSoundChannelStatus)(THIS_ MoaUlong iChannel) PURE; STDMETHOD(GetFreeSoundChannel)(THIS_ MoaUlong * piChannel) PURE; STDMETHOD(PlaySoundFormat)(THIS_ MoaUlong iChannel, PIMoaStream pSoundStream, ConstPMoaChar psSoundFormat, PMoaMmValue pProxyChannel, PIMoaDrMovie pMovieContext) PURE; STDMETHOD(PlaySoundRaw)(THIS_ MoaUlong iChannel, PIMoaStream pRawSoundStream, PMoaSoundFormat pSndFormat, PMoaMmCuePoint pCuePointList, MoaUlong nCuePoints, PMoaMmValue pProxyChannel, PIMoaDrMovie pMovieContext) PURE; STDMETHOD(StopSoundChannel)(THIS_ MoaUlong iChannel, MoaUlong* pTime) PURE; STDMETHOD(SetSoundChannelVolume)(THIS_ MoaUlong iChannel, MoaUshort nVolume) PURE; STDMETHOD(GetTime)(THIS_ MoaUlong iChannel, MoaUlong* pTime) PURE; }; typedef IMoaDrSound * PIMoaDrSound; #undef INTERFACE /* ---------------------------------------------------------------------------- */ DEFINE_GUID(IID_IMoaDrSound2, 0x250cab9e, 0x9bb9, 0x11d3, 0x88, 0x8e, 0x0, 0x90, 0x27, 0x72, 0x4, 0xfa); #undef INTERFACE #define INTERFACE IMoaDrSound2 DECLARE_INTERFACE_(IMoaDrSound2,IMoaDrSound) { STD_IUNKNOWN_METHODS STDMETHOD(GetSoundChannelCount)(THIS_ MoaUlong * pCount) PURE; STDMETHOD_(MoaDrSoundChannelPlayStatus,GetSoundChannelStatus)(THIS_ MoaUlong iChannel) PURE; STDMETHOD(GetFreeSoundChannel)(THIS_ MoaUlong * piChannel) PURE; STDMETHOD(PlaySoundFormat)(THIS_ MoaUlong iChannel, PIMoaStream pSoundStream, ConstPMoaChar psSoundFormat, PMoaMmValue pProxyChannel, PIMoaDrMovie pMovieContext) PURE; STDMETHOD(PlaySoundRaw)(THIS_ MoaUlong iChannel, PIMoaStream pRawSoundStream, PMoaSoundFormat pSndFormat, PMoaMmCuePoint pCuePointList, MoaUlong nCuePoints, PMoaMmValue pProxyChannel, PIMoaDrMovie pMovieContext) PURE; STDMETHOD(StopSoundChannel)(THIS_ MoaUlong iChannel, MoaUlong* pTime) PURE; STDMETHOD(SetSoundChannelVolume)(THIS_ MoaUlong iChannel, MoaUshort nVolume) PURE; STDMETHOD(GetTime)(THIS_ MoaUlong iChannel, MoaUlong* pTime) PURE; STDMETHOD(PauseSound)(THIS_ MoaUlong iChannel, MoaBoolParam bPauseState) PURE; }; typedef IMoaDrSound2 * PIMoaDrSound2; #undef INTERFACE /* ---------------------------------------------------------------------------- */ /* IMoaDrPreferenceAccess */ DEFINE_GUID(IID_IMoaDrPreferenceAccess, 0x4BA52EC4L, 0x64B2, 0x11CF, 0x98, 0x4A, 0x08, 0x00, 0x07, 0x4F, 0x01, 0x6C); #define INTERFACE IMoaDrPreferenceAccess DECLARE_INTERFACE_(IMoaDrPreferenceAccess, IMoaUnknown) { STD_IUNKNOWN_METHODS STDMETHOD(SetDataPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, PMoaVoid pData, MoaUlong size) PURE; STDMETHOD(SetStringPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, PMoaChar pValue) PURE; STDMETHOD(SetFlagPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, MoaBool value) PURE; STDMETHOD(SetLongPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, MoaLong value) PURE; STDMETHOD(SetDoublePref) (THIS_ PMoaChar prefKey, MoaID prefGUID, MoaDouble value) PURE; STDMETHOD(SetPointPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, MoaPoint value) PURE; STDMETHOD(SetRectPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, MoaRect value) PURE; STDMETHOD(GetDataPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, PMoaVoid pValue, MoaUlong size) PURE; STDMETHOD(GetStringPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, PMoaChar* ppValue, MoaLong bufLen) PURE; STDMETHOD(GetFlagPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, MoaBool* pValue) PURE; STDMETHOD(GetLongPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, MoaLong* pValue) PURE; STDMETHOD(GetDoublePref) (THIS_ PMoaChar prefKey, MoaID prefGUID, PMoaDouble pValue) PURE; STDMETHOD(GetPointPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, PMoaPoint pValue) PURE; STDMETHOD(GetRectPref) (THIS_ PMoaChar prefKey, MoaID prefGUID, PMoaRect pValue) PURE; }; typedef IMoaDrPreferenceAccess * PIMoaDrPreferenceAccess; #undef INTERFACE /*MOA Error block for IMoaDrPreferences----------0x1490->0x149F */ #define kMoaDrPrefsErr_Base 0x1490 #define kMoaDrPrefsErr_BufferOverrun MAKE_MOAERR(kMoaMmErr_Base) #define kMoaDrPrefsErr_InvalidKey MAKE_MOAERR(kMoaMmErr_Base + 1) #define kMoaDrPrefsErr_InvalidPointer MAKE_MOAERR(kMoaMmErr_Base + 2) #define kMoaDrPrefsErr_InvalidData MAKE_MOAERR(kMoaMmErr_Base + 3) #define kMoaDrPrefsErr_ClassIDNotValid MAKE_MOAERR(kMoaMmErr_Base + 4) /* ---------------------------------------------------------------------------- */ DEFINE_GUID(IID_IMoaDrCursor, 0xb8bca0d1, 0x7388, 0x11d2, 0x91, 0x20, 0x0, 0xa0, 0xc9, 0x2e, 0x3a, 0x0f); #undef INTERFACE #define INTERFACE IMoaDrCursor DECLARE_INTERFACE_(IMoaDrCursor, IMoaUnknown) { /* IMoaUnknown methods */ STD_IUNKNOWN_METHODS /* The cursorID can be one of the built in types, above, or a resource ID. The pCursorBitmap is the CMRef of a cast member, (either a 1-bit bitmap or a Cursor Xtra Asset) to be used as the sprite cursor. pCursorMask is an optional 1-bit mask bitmap (only used with a 1-bit bitmap cursor)*/ /* a spriteNum of 0 indicates setting of the stage cursor*/ STDMETHOD(SetSpriteCursor) (THIS_ MoaDrSpriteChanIndex spriteNum, MoaDrCursorID cursorID, PMoaDrCMRef pCursorBitmap, PMoaDrCMRef pCursorMask ) PURE; }; typedef IMoaDrCursor * PIMoaDrCursor; #undef INTERFACE /* ---------------------------------------------------------------------------- */ /* IMoaDrMovieContext */ DEFINE_GUID(IID_IMoaDrMovieContext, 0x99cd6df0, 0x49e8, 0x11d2, 0xa6, 0x6d, 0x00, 0xa0, 0xc9, 0xe7, 0x37, 0x36); #define INTERFACE IMoaDrMovieContext typedef struct { MoaLong dontUseEver[4]; } DrContextState, * PDrContextState; DECLARE_INTERFACE_(IMoaDrMovieContext, IMoaUnknown) { STD_IUNKNOWN_METHODS STDMETHOD(PushXtraContext) (THIS_ PDrContextState pDrContextState) PURE; STDMETHOD(PopXtraContext) (THIS_ PDrContextState pDrContextState) PURE; STDMETHOD(ReleaseExclusiveThread) (THIS_ PDrContextState pDrContextState) PURE; STDMETHOD(ReacquireExclusiveThread) (THIS_ PDrContextState pDrContextState) PURE; }; typedef IMoaDrMovieContext * PIMoaDrMovieContext; #undef INTERFACE #ifdef __cplusplus } #endif #include "drivalue.h" #endif /* DRISERVC_H */
[ "luca.bacci982@gmail.com" ]
luca.bacci982@gmail.com
30cf60b14a16a9614db9b6abebd8c40c6e090038
6b8654648da2e786d4c0998b26fc114c9d219451
/_old_/benchmark/increase_stack_benchmark.cpp
ce7f6aaebeb54dcd1d821c306dc7b14eb855c4c1
[ "MIT" ]
permissive
gian21391/enumeration_tool
d2edcd0d59c0f7b0e96a827f3b475d201b2581f0
607ca83c5cf8a7da6ea7438afcd158607e005a11
refs/heads/master
2020-06-26T12:00:03.447115
2020-06-14T18:21:47
2020-06-14T18:21:47
199,625,104
0
0
null
null
null
null
UTF-8
C++
false
false
9,973
cpp
#define CATCH_CONFIG_ENABLE_BENCHMARKING #include <catch.hpp> #include <enumeration_tool/symbol.hpp> #include <cmath> using EnumerationType = int; class enumerator { public: explicit enumerator( const std::vector<enumeration_symbol<EnumerationType>>& s ) : symbols{s} {} void enumerate( unsigned min_cost, unsigned max_cost ) { assert(!symbols.empty()); for (auto i = 0u; i < min_cost; ++i) { stack.emplace_back( 0 ); } while (max_cost >= stack.size()) // checks if too many elements in the stack { if (formula_is_concrete() && !formula_is_duplicate()) { use_formula(); } increase_stack(); } } void enumerate( unsigned max_cost ) { assert(!symbols.empty()); stack.emplace_back( 0 ); while (max_cost >= stack.size()) // checks if too many elements in the stack { if (formula_is_concrete() && !formula_is_duplicate()) { use_formula(); } increase_stack(); } } bool formula_is_concrete() { // here check whether a formula has dangling symbols int count = 1; for (const auto& value : stack) { count--; if (count < 0) return false; count += symbols[value].num_children; } if (count == 0) return true; else return false; } bool formula_is_duplicate() { // here we can check whether a simplification gives us an already obtained formula for (auto stack_iterator = stack.begin(); stack_iterator != stack.end(); std::advance( stack_iterator, 1 )) { if (symbols[*stack_iterator].attributes.is_set( enumeration_attributes::no_double_application )) { // here check if immediately after there is the same symbol auto temp_iterator = std::next( stack_iterator ); if (*temp_iterator == *stack_iterator) { return true; } // TODO: finish this } if (symbols[*stack_iterator].attributes.is_set( enumeration_attributes::commutative )) { // here check whether the first number in the stack is bigger the second auto plus_one_iterator = std::next( stack_iterator ); auto plus_two_iterator = std::next( plus_one_iterator ); if (*plus_one_iterator > *plus_two_iterator) { return true; } } if (symbols[*stack_iterator].attributes.is_set( enumeration_attributes::idempotent )) { // here check whether the first subtree is equal to the second subtree auto left_tree_iterator = std::next( stack_iterator ); auto left_tree = get_subtree( left_tree_iterator - stack.begin()); auto right_tree_iterator = stack_iterator; std::advance( right_tree_iterator, left_tree.size()); auto right_tree = get_subtree( right_tree_iterator - stack.begin()); if (left_tree == right_tree) { return true; } } } return false; } // do something with the current item virtual void use_formula() {}; protected: void increase_stack() { bool increase_flag = false; for (auto reverse_iterator = stack.rbegin(); reverse_iterator != stack.rend(); reverse_iterator++) { if (*reverse_iterator == symbols.size() - 1) { *reverse_iterator = 0; } else { (*reverse_iterator)++; increase_flag = true; break; } } if (!increase_flag) stack.emplace_back( 0 ); } std::vector<uint32_t> get_subtree( uint32_t starting_index ) { auto temporary_stack = stack; // remove all elements up to starting index auto new_begin_iterator = temporary_stack.begin(); std::advance( new_begin_iterator, starting_index ); temporary_stack.erase( temporary_stack.begin(), new_begin_iterator ); int count = 1; auto temporary_stack_iterator = temporary_stack.begin(); for (; temporary_stack_iterator != temporary_stack.end(); std::advance( temporary_stack_iterator, 1 )) { count--; if (count < 0) break; count += symbols[*temporary_stack_iterator].num_children; } assert( count == -1 || count == 0 ); temporary_stack.erase( temporary_stack_iterator, temporary_stack.end()); return temporary_stack; } std::vector<enumeration_symbol<EnumerationType>> symbols; std::vector<unsigned> stack; }; class enumerator_base_conversion { public: explicit enumerator_base_conversion( const std::vector<enumeration_symbol<EnumerationType>>& s ) : symbols{s} {} void enumerate( unsigned min_cost, unsigned max_cost ) { assert(!symbols.empty()); for (auto i = 0u; i < min_cost; ++i) { stack.emplace_back( 0 ); } while (max_cost >= stack.size()) // checks if too many elements in the stack { if (formula_is_concrete() && !formula_is_duplicate()) { use_formula(); } increase_stack(); } } void enumerate( unsigned max_cost ) { assert(!symbols.empty()); stack.emplace_back( 0 ); while (max_cost >= stack.size()) // checks if too many elements in the stack { if (formula_is_concrete() && !formula_is_duplicate()) { use_formula(); } increase_stack(); } } bool formula_is_concrete() { // here check whether a formula has dangling symbols int count = 1; for (const auto& value : stack) { count--; if (count < 0) return false; count += symbols[value].num_children; } if (count == 0) return true; else return false; } bool formula_is_duplicate() { // here we can check whether a simplification gives us an already obtained formula for (auto stack_iterator = stack.begin(); stack_iterator != stack.end(); std::advance( stack_iterator, 1 )) { if (symbols[*stack_iterator].attributes.is_set( enumeration_attributes::no_double_application )) { // here check if immediately after there is the same symbol auto temp_iterator = std::next( stack_iterator ); if (*temp_iterator == *stack_iterator) { return true; } // TODO: finish this } if (symbols[*stack_iterator].attributes.is_set( enumeration_attributes::commutative )) { // here check whether the first number in the stack is bigger the second auto plus_one_iterator = std::next( stack_iterator ); auto plus_two_iterator = std::next( plus_one_iterator ); if (*plus_one_iterator > *plus_two_iterator) { return true; } } if (symbols[*stack_iterator].attributes.is_set( enumeration_attributes::idempotent )) { // here check whether the first subtree is equal to the second subtree auto left_tree_iterator = std::next( stack_iterator ); auto left_tree = get_subtree( left_tree_iterator - stack.begin()); auto right_tree_iterator = stack_iterator; std::advance( right_tree_iterator, left_tree.size()); auto right_tree = get_subtree( right_tree_iterator - stack.begin()); if (left_tree == right_tree) { return true; } } } return false; } // do something with the current item virtual void use_formula() {}; protected: void increase_stack() { counter++; auto temp_counter = counter; auto base = symbols.size(); int digits = (std::log2(temp_counter) / std::log2(base)) + 1; if (digits > stack.size()) { stack.emplace_back(0); for (auto& item : stack) { item = 0; } counter = 0; return; } int i = 0; while (temp_counter >= symbols.size()) { auto value = temp_counter % symbols.size(); temp_counter /= symbols.size(); stack[i++] = value; } stack[i] = temp_counter; } std::vector<uint32_t> get_subtree( uint32_t starting_index ) { auto temporary_stack = stack; // remove all elements up to starting index auto new_begin_iterator = temporary_stack.begin(); std::advance( new_begin_iterator, starting_index ); temporary_stack.erase( temporary_stack.begin(), new_begin_iterator ); int count = 1; auto temporary_stack_iterator = temporary_stack.begin(); for (; temporary_stack_iterator != temporary_stack.end(); std::advance( temporary_stack_iterator, 1 )) { count--; if (count < 0) break; count += symbols[*temporary_stack_iterator].num_children; } assert( count == -1 || count == 0 ); temporary_stack.erase( temporary_stack_iterator, temporary_stack.end()); return temporary_stack; } std::vector<enumeration_symbol<EnumerationType>> symbols; std::vector<unsigned> stack; uint64_t counter; }; TEST_CASE("increase_stack_test", "[benchmark]") { BENCHMARK_ADVANCED("current") (Catch::Benchmark::Chronometer meter) { std::vector<enumeration_symbol<EnumerationType>> symbols; enumeration_symbol<EnumerationType> s0; s0.num_children = 0; for (int i = 0; i < 10; ++i) { symbols.emplace_back(s0); } enumeration_symbol<EnumerationType> s1; s1.num_children = 1; for (int i = 0; i < 2; ++i) { symbols.emplace_back(s1); } enumeration_symbol<EnumerationType> s2; s2.num_children = 2; for (int i = 0; i < 2; ++i) { symbols.emplace_back(s2); } enumerator en(symbols); meter.measure([&] { return en.enumerate(6); }); }; BENCHMARK_ADVANCED("base conversion") (Catch::Benchmark::Chronometer meter) { std::vector<enumeration_symbol<EnumerationType>> symbols; enumeration_symbol<EnumerationType> s0; s0.num_children = 0; for (int i = 0; i < 10; ++i) { symbols.emplace_back(s0); } enumeration_symbol<EnumerationType> s1; s1.num_children = 1; for (int i = 0; i < 2; ++i) { symbols.emplace_back(s1); } enumeration_symbol<EnumerationType> s2; s2.num_children = 2; for (int i = 0; i < 2; ++i) { symbols.emplace_back(s2); } enumerator_base_conversion en(symbols); meter.measure([&] { return en.enumerate(6); }); }; }
[ "gianluca.martino@tuhh.de" ]
gianluca.martino@tuhh.de
5cc762e9adb2207a9abc1f128c8359018b8fa894
5098a5bab107adb675b394b06093ed6913921ebc
/SDK/Itm_LoadoutSelectButton_classes.h
05d35f4c41c9c62cf27949321deca9ca67b3fd2d
[]
no_license
tetosama/DRG-SDK
87af9452fa0d3aed2411a09a108f705ae427ba1e
acb72b0ee2aae332f236f99030d27f4da9113de1
refs/heads/master
2022-03-31T00:12:10.582553
2020-01-18T21:21:43
2020-01-18T21:21:43
234,783,902
0
0
null
null
null
null
UTF-8
C++
false
false
6,598
h
#pragma once // Name: , Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass Itm_LoadoutSelectButton.ITM_LoadoutSelectButton_C // 0x00C0 (0x02F0 - 0x0230) class UITM_LoadoutSelectButton_C : public UUserWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0230(0x0008) (ZeroConstructor, Transient, DuplicateTransient) class UWidgetAnimation* Hover; // 0x0238(0x0008) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Transient, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBorder* Background; // 0x0240(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UButton* Button_1; // 0x0248(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* Image_LoadoutIcon; // 0x0250(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UBorder* SelectionBorder; // 0x0258(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UTextBlock* TextBlock_ButtonText; // 0x0260(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) struct FScriptMulticastDelegate OnClicked; // 0x0268(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable) bool IsSelected; // 0x0278(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x7]; // 0x0279(0x0007) MISSED OFFSET struct FText ButtonText; // 0x0280(0x0018) (Edit, BlueprintVisible) struct FSlateColor IconSelectedColor; // 0x0298(0x0028) (Edit, BlueprintVisible, DisableEditOnInstance) struct FSlateColor IconNotSelectedColor; // 0x02C0(0x0028) (Edit, BlueprintVisible, DisableEditOnInstance) class UBasic_ToolTip_HeadlineAndText_C* HoverTooltipWidget; // 0x02E8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, InstancedReference, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass Itm_LoadoutSelectButton.ITM_LoadoutSelectButton_C"); return ptr; } class UWidget* GetToolTipWidget(); void BndEvt__Button_0_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature(); void SetSelected(bool* InSelected); void PreConstruct(bool* IsDesignTime); void SetIcon(class UTexture2D** Texture); void BndEvt__Button_0_K2Node_ComponentBoundEvent_1_OnButtonHoverEvent__DelegateSignature(); void BndEvt__Button_0_K2Node_ComponentBoundEvent_2_OnButtonHoverEvent__DelegateSignature(); void ExecuteUbergraph_ITM_LoadoutSelectButton(int* EntryPoint); void OnClicked__DelegateSignature(class UITM_LoadoutSelectButton_C** Button); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "39564369+tetosama@users.noreply.github.com" ]
39564369+tetosama@users.noreply.github.com
20f87e0e7c9ba9fbf29563b01143857cd9ae1e70
974897eae62d73db4aa1bdfda4efa41c4e9dd0ed
/Source/MV/Utility/threadPool.hpp
771dddbec69a1e3becc306e4cddc3a0434ecab94
[]
no_license
Devacor/Bindstone
71670d3d1e37d578a8616baad4a2b4dba36ff327
6b204c945d437456d79189509526962b89499839
refs/heads/master
2023-02-17T08:52:35.874390
2020-10-19T08:04:19
2020-10-19T08:04:19
40,729,765
1
0
null
null
null
null
UTF-8
C++
false
false
7,655
hpp
#ifndef _MV_THREADPOOL_H_ #define _MV_THREADPOOL_H_ #include <thread> #include <condition_variable> #include <deque> #include <vector> #include <atomic> #include <list> #include "log.h" namespace MV { class ThreadPool { class Worker; public: class Job { friend Worker; public: enum class Continue { MAIN_THREAD, POOL, IMMEDIATE }; Job(const std::function<void()> &a_action) : action(a_action) { } Job(const std::function<void()> &a_action, const std::function<void()> &a_onFinish, Continue a_continueMethod = Continue::POOL) : action(a_action), onFinish(a_onFinish), onFinishContinue(a_continueMethod){ } Job(Job&& a_rhs) = default; Job(const Job& a_rhs) = default; void group(const std::shared_ptr<std::atomic<size_t>> &a_groupCounter, const std::shared_ptr<std::function<void()>> &a_onGroupFinish, Continue a_continueMethod = Continue::POOL) { onGroupFinishContinue = a_continueMethod; groupCounter = a_groupCounter; onGroupFinish = a_onGroupFinish; } void operator()() noexcept { try { action(); } catch (std::exception &e) { parent->exception(e); } bool groupFinished = groupCounter && --(*groupCounter) == 0 && onGroupFinish && *onGroupFinish; if (onFinish && groupFinished && onFinishContinue == onGroupFinishContinue) { continueMethod([=](){ try { onFinish(); } catch (std::exception &e) { parent->exception(e); } try { (*onGroupFinish)(); } catch (std::exception &e) { parent->exception(e); } }, onFinishContinue); }else{ if (onFinish) { continueMethod(onFinish, onFinishContinue); } if (groupFinished) { continueMethod(*onGroupFinish, onGroupFinishContinue); } } } private: const void continueMethod(const std::function<void()> &a_method, Continue a_plan){ switch(a_plan){ case Continue::IMMEDIATE: try { a_method(); } catch (std::exception &e) { parent->exception(e); } break; case Continue::MAIN_THREAD: parent->schedule(a_method); break; case Continue::POOL: parent->task(a_method); break; } } ThreadPool* parent = nullptr; Continue onFinishContinue = Continue::MAIN_THREAD; Continue onGroupFinishContinue = Continue::MAIN_THREAD; std::function<void()> action; std::function<void()> onFinish; std::shared_ptr<std::atomic<size_t>> groupCounter; std::shared_ptr<std::function<void()>> onGroupFinish; }; friend Job; private: class Worker { public: Worker(ThreadPool* a_parent) : parent(a_parent) { thread = std::make_unique<std::thread>([=]() { work(); }); } ~Worker() { if (thread && thread->joinable()) { thread->join(); } } void cleanup() { const double cleanupTimeout = 5.0; auto start = std::chrono::high_resolution_clock::now(); while (!finished && std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - start).count() < cleanupTimeout) { std::this_thread::yield(); } if(!finished){ MV::error("Cleanup Timeout Exceeded in MV::ThreadPool::Worker!"); } } private: void work() { finished = false; while (!parent->stopped) { std::unique_lock<std::mutex> guard(parent->lock); parent->notify.wait(guard, [=] {return parent->jobs.size() > 0 || parent->stopped; }); if (parent->stopped) { break; } auto job = std::move(parent->jobs.front()); parent->jobs.pop_front(); guard.unlock(); job.parent = parent; job(); --parent->active; } finished = true; } ThreadPool* parent; bool finished = true; std::unique_ptr<std::thread> thread; }; friend Worker; public: ThreadPool() : ThreadPool(std::thread::hardware_concurrency() > 1 ? std::thread::hardware_concurrency() - 1 : 1) { } ThreadPool(size_t a_threads) { for (size_t i = 0; i < a_threads; ++i) { workers.push_back(std::make_unique<Worker>(this)); } } ~ThreadPool() { { std::lock_guard<std::mutex> guard(lock); jobs.clear(); stopped = true; } notify.notify_all(); for (auto&& worker : workers) { worker->cleanup(); } } void task(Job&& a_newWork) { ++active; { std::lock_guard<std::mutex> guard(lock); jobs.emplace_back(std::move(a_newWork)); } notify.notify_one(); } void task(const Job &a_newWork) { ++active; { std::lock_guard<std::mutex> guard(lock); jobs.emplace_back(a_newWork); } notify.notify_one(); } void task(const std::function<void()> &a_task) { ++active; { std::lock_guard<std::mutex> guard(lock); jobs.emplace_back(a_task); } notify.notify_one(); } void task(const std::function<void()> &a_task, const std::function<void()> &a_onComplete) { ++active; { std::lock_guard<std::mutex> guard(lock); jobs.emplace_back(a_task, a_onComplete); } notify.notify_one(); } void tasks(std::vector<Job> &&a_tasks, const std::function<void()> &a_onGroupComplete, Job::Continue a_continueCompletionCallback = Job::Continue::POOL) { active+=static_cast<int>(a_tasks.size()); std::shared_ptr<std::atomic<size_t>> counter = std::make_shared<std::atomic<size_t>>(a_tasks.size()); std::shared_ptr<std::function<void()>> sharedGroupComplete = std::make_shared<std::function<void()>>(a_onGroupComplete); { std::lock_guard<std::mutex> guard(lock); for (auto&& job : a_tasks) { job.group(counter, sharedGroupComplete, a_continueCompletionCallback); jobs.push_back(std::move(job)); } } for (size_t i = 0; i < a_tasks.size(); ++i) { notify.notify_one(); } } void tasks(const std::vector<Job> &a_tasks, const std::function<void()> &a_onGroupComplete, Job::Continue a_continueCompletionCallback = Job::Continue::POOL) { active+=static_cast<int>(a_tasks.size()); std::shared_ptr<std::atomic<size_t>> counter = std::make_shared<std::atomic<size_t>>(a_tasks.size()); std::shared_ptr<std::function<void()>> sharedGroupComplete = std::make_shared<std::function<void()>>(a_onGroupComplete); { std::lock_guard<std::mutex> guard(lock); for (auto&& job : a_tasks) { jobs.push_back(job); jobs.back().group(counter, sharedGroupComplete, a_continueCompletionCallback); } } for (size_t i = 0; i < a_tasks.size(); ++i) { notify.notify_one(); } } void schedule(const std::function<void()> &a_method) { std::lock_guard<std::mutex> guard(scheduleLock); scheduled.push_back(a_method); } bool run() { auto wasActive = active > 0; auto endNode = scheduled.end(); for (auto i = scheduled.begin(); i != endNode;) { try { (*i)(); } catch (std::exception &e) { exception(e); } std::lock_guard<std::mutex> guard(scheduleLock); scheduled.erase(i++); } return wasActive; } void exceptionHandler(std::function<void(std::exception &e)> a_onException) { std::lock_guard<std::mutex> guard(exceptionLock); onException = a_onException; } size_t threads() const { return workers.size(); } private: void exception(std::exception &e) { std::lock_guard<std::mutex> guard(exceptionLock); if (onException) { onException(e); } else { MV::error("Uncaught Exception in Thread Pool: ", e.what()); } } std::condition_variable notify; bool stopped = false; std::mutex lock; std::mutex scheduleLock; std::mutex exceptionLock; std::vector<std::unique_ptr<Worker>> workers; std::deque<Job> jobs; std::list<std::function<void()>> scheduled; std::deque<std::string> exceptionMessages; std::function<void(std::exception &e)> onException; std::atomic<int> active; }; } #endif
[ "maxmike@gmail.com" ]
maxmike@gmail.com
03e121c43d8bd546ef531ee34ca7a2ee7bcbb105
d5c5f6e754e5f3f714c71db959c54fd183bb9fcc
/Ball.cpp
cd0f227b72230dede6f03d656577855296be7a63
[]
no_license
TeMeRolEee/GameDayProject
a347c17ecacff83f242fa8917a3b78b4f9963440
7baa211319a7c5d60b24313c5095f2e2f5e761d8
refs/heads/master
2020-03-22T07:27:11.495376
2018-07-04T21:41:50
2018-07-04T21:41:50
139,701,349
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
// // Created by temerole on 2018.07.04.. // #include "Ball.h" Ball::Ball() : QGraphicsRectItem() { setRect(10, 10, 10, 10); setPos(40, 50); QBrush brush; brush.setStyle(Qt::SolidPattern); brush.setColor(Qt::red); setBrush(brush); } float Ball::getVelocity() { return velocity; } void Ball::setVelocity(float newVelocity) { this->velocity = newVelocity; } void Ball::setVector(QVector2D *newVector){ this->vector = newVector; } QVector2D* Ball::getVector() { return vector; } Ball::~Ball() { }
[ "david.rethalmi@gmail.com" ]
david.rethalmi@gmail.com
b2273afe62b223ea1d9571f62782d2c4d15a6826
5b936ba7bcac2e785b20ef28732b6299c5e27bc9
/src/perl_interpreter_sea_bridge.cpp
56682e0ae502a6f94e82909846c81b843bec464c
[ "MIT" ]
permissive
Pelleplutt/BladePSGI
8a51c6b60dbe64c57bb0092dae5782d4df55f4f8
ae15f9d107dd16ba7eca634246554c8da71adce3
refs/heads/master
2020-03-26T05:02:10.233799
2018-08-13T14:08:57
2018-08-13T14:08:57
144,535,358
0
0
MIT
2018-08-13T05:55:43
2018-08-13T05:55:43
null
UTF-8
C++
false
false
3,413
cpp
#include "bladepsgi.hpp" #include "string" extern "C" { #include "perl/bladepsgi_perl.h" #include "perl/XS.h" void bladepsgi_perl_interpreter_cb_set_worker_status(BPSGI_Context *ctx, const char *status) { Assert(ctx->mainapp != NULL && ctx->worker != NULL); auto worker = (BPSGIWorker *) ctx->worker; worker->SetWorkerStatus(status[0]); } int bladepsgi_perl_interpreter_cb_fastcgi_listen_sockfd(BPSGI_Context *ctx) { Assert(ctx->mainapp != NULL); auto mainapp = (BPSGIMainApplication *) ctx->mainapp; Assert(mainapp->fastcgi_sockfd() != -1); return mainapp->fastcgi_sockfd(); } const char * bladepsgi_perl_interpreter_cb_psgi_application_path(BPSGI_Context *ctx) { Assert(ctx->mainapp != NULL); auto mainapp = (BPSGIMainApplication *) ctx->mainapp; Assert(mainapp->psgi_application_path() != NULL); return mainapp->psgi_application_path(); } const char * bladepsgi_perl_interpreter_cb_psgi_application_loader(BPSGI_Context *ctx) { Assert(ctx->mainapp != NULL); auto mainapp = (BPSGIMainApplication *) ctx->mainapp; return mainapp->psgi_application_loader(); } extern const char * bladepsgi_perl_interpreter_cb_request_auxiliary_process(BPSGI_Context *ctx, const char *name, void *sv) { Assert(ctx->mainapp != NULL); auto callback_p = (struct bladepsgi_perl_callback_t *) malloc(sizeof(struct bladepsgi_perl_callback_t)); memset(callback_p, 0, sizeof(struct bladepsgi_perl_callback_t)); callback_p->bladepsgictx = (void *) ctx; callback_p->sv = sv; auto mainapp = (BPSGIMainApplication *) ctx->mainapp; mainapp->RequestAuxiliaryProcess(std::string(name), make_unique<BPSGIPerlCallbackFunction>(callback_p)); return NULL; } /* * Returns NULL on success, or error message on failure. */ const char * bladepsgi_perl_interpreter_cb_new_semaphore(BPSGI_Context *ctx, BPSGI_Semaphore *sem, const char *name, int value) { Assert(ctx->mainapp != NULL); auto mainapp = (BPSGIMainApplication *) ctx->mainapp; auto shmem = mainapp->shmem(); try { sem->sem = (void *) shmem->NewSemaphore(name, value); } catch (const std::string & ex) { return strdup(ex.c_str()); } return NULL; } /* * Returns NULL on success, or error message on failure. */ const char * bladepsgi_perl_interpreter_cb_new_atomic_int64(BPSGI_Context *ctx, BPSGI_AtomicInt64 **atm, const char *name, int value) { Assert(ctx->mainapp != NULL); auto mainapp = (BPSGIMainApplication *) ctx->mainapp; auto shmem = mainapp->shmem(); try { *atm = (BPSGI_AtomicInt64 *) shmem->NewAtomicInt64(name, value); } catch (const std::string & ex) { return strdup(ex.c_str()); } return NULL; } int bladepsgi_perl_interpreter_cb_sem_tryacquire(BPSGI_Semaphore *sem) { Assert(sem->sem != NULL); auto p = (BPSGISemaphore *) sem->sem; return p->TryAcquire() ? 1 : 0; } void bladepsgi_perl_interpreter_cb_sem_release(BPSGI_Semaphore *sem) { Assert(sem->sem != NULL); auto p = (BPSGISemaphore *) sem->sem; p->Release(); } int64_t bladepsgi_perl_interpreter_cb_atomic_int64_fetch_add(BPSGI_AtomicInt64 *atm, int64_t value) { return std::atomic_fetch_add((std::atomic<int64_t> *) atm, value); } int64_t bladepsgi_perl_interpreter_cb_atomic_int64_load(BPSGI_AtomicInt64 *atm) { return std::atomic_load((std::atomic<int64_t> *) atm); } void bladepsgi_perl_interpreter_cb_atomic_int64_store(BPSGI_AtomicInt64 *atm, int64_t value) { return std::atomic_store((std::atomic<int64_t> *) atm, value); } }
[ "marko@trustly.com" ]
marko@trustly.com
37ddc945938d68af787bb538394ddd08b8faca31
d5acc40e766857c2399013c5228fc4f02b2f5210
/c++/2 - fibonacci.cpp
5672def815cd5c24bc94f4bbf996c490894866f8
[]
no_license
celvro/euler
a79dec92620fedfaaa5789a29d964395488fc1d8
f76d6f00efd9db26b9caad72e94110d5ef972b37
refs/heads/master
2016-09-10T03:21:41.417156
2015-04-30T21:27:38
2015-04-30T21:27:38
20,080,352
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
#include<iostream> using namespace std; int main() { int sum=0, prev=1, next=2, temp; while(next<4000000) { if(!(next%2)) sum+=next; temp=next; next+=prev; prev=temp; } cout << sum << endl; cin.get(); return 0; }
[ "dwlfk2@mst.edu" ]
dwlfk2@mst.edu
4d3aad662ebdec186856d26f09161a74271d9b4d
a59c6d3ef3a55cf9885fdc304b9d3bda5c22a504
/arista.cpp
0be1b860833e6b8b3e1005d38ea6c4ad9ac1bc06
[]
no_license
dcaceres7/Proyecto2Parcial
7ac47f5d5b457cd0be005b8220a89eafad73c64f
8b3d99303cc1508f24039e14cccffe3bb4287ab5
refs/heads/master
2020-12-24T15:58:10.462244
2015-06-30T21:33:40
2015-06-30T21:33:40
38,334,264
0
0
null
null
null
null
UTF-8
C++
false
false
652
cpp
#include "arista.h" #include <QPainter> Arista::Arista(Vertice* origen, Vertice* destino, int v) { this->origen = origen; this->destino = destino; valor = v; } QRectF Arista::boundingRect() const { return QRectF(origen->pos(),destino->pos()); } void Arista::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->drawLine(origen->x()+(origen->size/2),origen->y()+(origen->size/2) ,destino->x()+(destino->size/2), destino->y()+(destino->size/2)); painter->drawText(((origen->x()+destino->x())/2)+(origen->size/2),((origen->y()+destino->y())/2)+(origen->size/2),QString::number(valor)); }
[ "dancacers_95@unitec.edu" ]
dancacers_95@unitec.edu
a41c3c8c4c3d0245333da7089afab0cd456fd0f3
1f3c66fccc60cf866fd83d206580989f3b7a2668
/DSRE/Source/DSRE/PlayerController/BaseController.cpp
3038b03a727adf818ee66accdf7d422f2922a787
[]
no_license
nsobczak/DSRE
86c4bc62410063738894b0acac95af93ee9a8219
6a893834cb868cdfc3b86d8dae77c4a999216f96
refs/heads/master
2022-04-21T16:30:55.534800
2020-04-20T23:12:15
2020-04-20T23:12:15
256,742,087
1
0
null
null
null
null
UTF-8
C++
false
false
626
cpp
// Copyright 2020 nsocbzak. All rights reserved. #include "BaseController.h" // Sets default values ABaseController::ABaseController() { //RootComponent = GetCapsuleComponent(); PrimaryActorTick.bCanEverTick = true; // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bTickEvenWhenPaused = true; } // Called when the game starts or when spawned void ABaseController::BeginPlay() { Super::BeginPlay(); ResetProperties(); } //void ABCController::Tick(float DeltaTime) //{ // Super::Tick(DeltaTime); // // //}
[ "nicolas.sobczak@orange.fr" ]
nicolas.sobczak@orange.fr
7fc3599faf95e20d15bb077b007f0f67b49066c4
9095705da4f7d28ab522f4c983cb73a74599a95b
/password_generator_vs/utils.h
7b9f0a29ec3740ce1b0316ebad3b34d9904f241f
[]
no_license
fanxiaohui/cpp
ca576e14d81279b7325bb44ac7293f6678e61c1f
1079895ff963dfd9933df40eee2f8077c684cf2b
refs/heads/master
2021-04-02T04:35:02.848512
2020-02-21T11:34:24
2020-02-21T11:34:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
#ifndef UTILS_H #define UTILS_H /********************************************************************* utils.h 01.10.2004 Initial coding YS **********************************************************************/ #ifdef WIN32_APP #include <Windows.h> #endif void AddTimeStamp(int *pos,char * msg); void AddStringPan(char * destStr, char * strToAdd,int len); void AddShortTimeStamp(int *pos,char * msg); int RND_Array(int); long Get1msTime(void); long Get1msTimeMS(void); char* PrintTime(void); // return string with time void PrintIntroduction(); void SendStr(char * SendString, int dest, int length); int produceRND(); class CTimer { public: CTimer(); ~CTimer(); void Start(); unsigned int GetElapsedTimeMs() const; unsigned __int64 GetElapsedTimeMks() const; private: LARGE_INTEGER m_liFreq; LARGE_INTEGER m_liStart; LARGE_INTEGER m_liEnd; }; #endif
[ "senishch@gmail.com" ]
senishch@gmail.com
5fc2d8b6048e5d5fb3d04ab289e9a915e3ba3864
206bc173b663425bea338b7eb7bc8efc094167b5
/codeforces/453/1.cpp
b4e424349b71e12466bf861fb7e4ef48c4cb703b
[]
no_license
rika77/competitive_programming
ac6e7664fe95249a3623c814e6a0c363c5af5f33
a0f860c801e9197bcdd6b029ca3e46e73dfc4253
refs/heads/master
2022-03-01T09:03:01.056933
2019-11-07T01:45:28
2019-11-07T01:45:28
122,687,377
0
0
null
null
null
null
UTF-8
C++
false
false
567
cpp
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; int main(){ int n,m; cin >> n>> m; int a[100]={}; int b[100]={}; for (int i=0;i<n;i++) { scanf("%d %d\n", &a[i], &b[i]); } if (b[n-1] != m || a[0] != 0) { printf("NO\n"); return 0; } //n=1のとき if (n==1) { if (a[0]==0 && b[0]==m) { printf("YES\n"); return 0; } else { printf("NO\n"); return 0; } } int maxi = b[0]; for (int i=0;i<n-1;i++) { maxi = max(maxi, b[i]); if (a[i+1]>maxi) { printf("NO\n"); return 0; } } printf("YES\n"); return 0; }
[ "mahimahi.kametan@gmail.com" ]
mahimahi.kametan@gmail.com
00fc85bd18c3551215b0e6596899616de1184644
5cc078770dfc5bbb8cb2d16a6f969bb0fca699cb
/VC++/ten/tenDlg.cpp
52875449e898d977d7e599b8be1ea89e713486b7
[]
no_license
sahilsoni91/visualcpp_program
53ce3c10c539dbd9ab98f550192e87f5af4d5bb1
699cbd57816e67ee88c38867e9ec2b670bf4fa70
refs/heads/master
2020-08-06T14:08:30.531679
2019-10-05T13:15:56
2019-10-05T13:15:56
213,002,018
0
0
null
null
null
null
UTF-8
C++
false
false
4,976
cpp
// tenDlg.cpp : implementation file // #include "stdafx.h" #include "ten.h" #include "tenDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTenDlg dialog CTenDlg::CTenDlg(CWnd* pParent /*=NULL*/) : CDialog(CTenDlg::IDD, pParent) { //{{AFX_DATA_INIT(CTenDlg) m_check1 = FALSE; m_check2 = FALSE; m_check3 = FALSE; m_check4 = FALSE; m_text = _T(""); //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CTenDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTenDlg) DDX_Check(pDX, IDC_CHECK1, m_check1); DDX_Check(pDX, IDC_CHECK2, m_check2); DDX_Check(pDX, IDC_CHECK3, m_check3); DDX_Check(pDX, IDC_CHECK4, m_check4); DDX_Text(pDX, IDC_RICHEDIT1, m_text); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CTenDlg, CDialog) //{{AFX_MSG_MAP(CTenDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_RADIO1, OnRadio1) ON_BN_CLICKED(IDC_RADIO2, OnRadio2) ON_BN_CLICKED(IDC_RADIO3, OnRadio3) ON_BN_CLICKED(IDC_RADIO4, OnRadio4) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTenDlg message handlers BOOL CTenDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control } void CTenDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CTenDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CTenDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CTenDlg::OnRadio1() { // TODO: Add your control notification handler code here m_check1=true; m_check2=true; m_check3=true; m_check4=true; m_text="$ 5.00"; UpdateData(false); } void CTenDlg::OnRadio2() { // TODO: Add your control notification handler code here m_check1=true; m_check2=false; m_check3=true; m_check4=false; m_text="$ 4.50"; UpdateData(false); } void CTenDlg::OnRadio3() { // TODO: Add your control notification handler code here m_check1=false; m_check2=true; m_check3=false; m_check4=true; m_text="$ 3.25"; UpdateData(false); } void CTenDlg::OnRadio4() { // TODO: Add your control notification handler code here m_check1=false; m_check2=false; m_check3=false; m_check4=false; m_text="$ 0.00"; UpdateData(false); }
[ "sahilsoni91@gmail.com" ]
sahilsoni91@gmail.com
45aca7497813acbd8959b5bc3115b843eaed82d9
2e50fd32816c9493fe81ad4834978932f32da060
/eduRend17v1/source/mesh.cpp
18689922c06a6d5eaf67ea14fbcb1de653a16356
[]
no_license
ai7900/DirectX-_11_Render_Assignments
89e38baed6d1187dcca61b03866813b2c3707755
7edd60d6f6f1d2c6fbda0df987d5c3aafb5a66eb
refs/heads/master
2021-02-15T14:43:06.193455
2020-03-04T13:34:37
2020-03-04T13:34:37
244,908,058
0
0
null
null
null
null
UTF-8
C++
false
false
13,819
cpp
// // mesh.cpp // // (c) CJG 2016, cjgribel@gmail.com // #include <algorithm> #include "mesh.h" using linalg::int3; void mesh_t::load_mtl( std::string path, std::string filename, mtl_hash_t &mtl_hash) { std::string fullpath = path+filename; std::ifstream in(fullpath.c_str()); if (!in) throw std::runtime_error(std::string("Failed to open ") + fullpath); std::cout << "Opened " << fullpath << "\n"; std::string line; material_t *current_mtl = NULL; while (getline(in, line, '\n')) { char str0[1024] = {0}, str1[1024]; float a,b,c; ltrim(line); if (sscanf(line.c_str(), "newmtl %s", str0) == 1) { // check for duplicate if (mtl_hash.find(str0) != mtl_hash.end() ) printf("Warning: duplicate material '%s'\n", str0); mtl_hash[str0] = material_t(); current_mtl = &mtl_hash[str0]; current_mtl->name = str0; current_mtl->map_bump = "../../Assets/textures/0001CD_normal.jpg"; } else if (!current_mtl) { // no parsed material so can't add any content continue; } else if (sscanf(line.c_str(), "map_Kd %[^\n]", str0) == 1) { // search for the image file and ignore the rest std::string mapfile; if (find_filename_from_suffixes(str0, ALLOWED_TEXTURE_SUFFIXES, mapfile)) current_mtl->map_Kd = path + mapfile; else throw std::runtime_error(std::string("Error: no allowed format found for 'map_Kd' in material ") + current_mtl->name); } else if (sscanf(line.c_str(), "map_Ks %[^\n]", str0) == 1) { // search for the image file and ignore the rest std::string mapfile; if (find_filename_from_suffixes(str0, ALLOWED_TEXTURE_SUFFIXES, mapfile)) current_mtl->map_Ks = path + mapfile; else throw std::runtime_error(std::string("Error: no allowed format found for 'map_Ks' in material ") + current_mtl->name); } else if (sscanf(line.c_str(), "map_Ka %[^\n]", str0) == 1) { // search for the image file and ignore the rest std::string mapfile; if (find_filename_from_suffixes(str0, ALLOWED_TEXTURE_SUFFIXES, mapfile)) current_mtl->map_Ka = path + mapfile; else throw std::runtime_error(std::string("Error: no allowed format found for 'map_Ka' in material ") + current_mtl->name); } else if (sscanf(line.c_str(), "map_d %[^\n]", str0) == 1) { // search for the image file and ignore the rest std::string mapfile; if (find_filename_from_suffixes(str0, ALLOWED_TEXTURE_SUFFIXES, mapfile)) current_mtl->map_d = path + mapfile; else throw std::runtime_error(std::string("Error: no allowed format found for 'map_d' in material ") + current_mtl->name); } else if (sscanf(line.c_str(), "map_bump %[^\n]", str0) == 1) { // search for the image file and ignore the rest std::string mapfile; if (find_filename_from_suffixes(str0, ALLOWED_TEXTURE_SUFFIXES, mapfile)) current_mtl->map_bump = path+mapfile; else throw std::runtime_error(std::string("Error: no allowed format found for 'map_bump' in material ") + current_mtl->name); } else if (sscanf(line.c_str(), "Ka %f %f %f", &a, &b, &c) == 3) { current_mtl->Ka = vec3f(a, b, c); } else if (sscanf(line.c_str(), "Kd %f %f %f", &a, &b, &c) == 3) { current_mtl->Kd = vec3f(a, b, c); } else if (sscanf(line.c_str(), "Ks %f %f %f", &a, &b, &c) == 3) { current_mtl->Ks = vec3f(a, b, c); } } in.close(); } void mesh_t::load_obj(const std::string& filename, bool auto_generate_normals, bool triangulate) { std::string parentdir = get_parentdir(filename); std::ifstream in(filename.c_str()); if (!in) throw std::runtime_error(std::string("Failed to open ") + filename); std::cout << "Opened " << filename << "\n"; // raw data from obj std::vector<vec3f> file_vertices, file_normals; std::vector<vec2f> file_texcoords; std::vector<unwelded_drawcall_t> file_drawcalls; mtl_hash_t file_materials; std::string current_group_name; unwelded_drawcall_t default_drawcall; unwelded_drawcall_t* current_drawcall = &default_drawcall; int last_ofs = 0; bool face_section = false; // info for skin weight mapping std::string line; while (getline(in, line)) { float x, y, z; int a[3], b[3], c[3], d[3]; char str[1024]; // material file // if (sscanf(line.c_str(), "mtllib %s", str) == 1) { load_mtl(parentdir, str, file_materials); } // active material // else if (sscanf(line.c_str(), "usemtl %s", str) == 1) { unwelded_drawcall_t udc; udc.mtl_name = str; udc.group_name = current_group_name; udc.v_ofs = last_ofs; face_section = true; // skinning: set current vertex offset and mark beginning of a face-section file_drawcalls.push_back(udc); current_drawcall = &file_drawcalls.back(); } else if (sscanf(line.c_str(), "g %s", str) == 1) { current_group_name = str; } // 3D vertex // else if (sscanf(line.c_str(), "v %f %f %f", &x, &y, &z) == 3) { // update vertex offset and mark end to a face section if (face_section) { last_ofs = file_vertices.size(); face_section = false; } file_vertices.push_back(vec3f(x, y, z)); } // 2D vertex // else if (sscanf(line.c_str(), "v %f %f", &x, &y) == 2) { file_vertices.push_back(vec3f(x, y, 0.0f)); } // 3D texel (not supported: ignore last component) // else if (sscanf(line.c_str(), "vt %f %f %f", &x, &y, &z) == 3) { file_texcoords.push_back(vec2f(x, y)); } // 2D texel // else if (sscanf(line.c_str(), "vt %f %f", &x, &y) == 2) { file_texcoords.push_back(vec2f(x, y)); } // normal // else if (sscanf(line.c_str(), "vn %f %f %f", &x, &y, &z) == 3) { file_normals.push_back(vec3f(x, y, z)); } // face: 4x vertex // else if (sscanf(line.c_str(), "f %d %d %d %d", &a[0], &b[0], &c[0], &d[0]) == 4) { if (triangulate) { current_drawcall->tris.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, -1, -1, -1, -1, -1, -1 }); current_drawcall->tris.push_back({ a[0] - 1, c[0] - 1, d[0] - 1, -1, -1, -1, -1, -1, -1 }); } else current_drawcall->quads.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, d[0] - 1, -1, -1, -1, -1, -1, -1, -1, -1 }); } // face: 3x vertex // else if (sscanf(line.c_str(), "f %d %d %d", &a[0], &b[0], &c[0]) == 3) { current_drawcall->tris.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, -1, -1, -1, -1, -1, -1 }); } // face: 4x vertex/texel (triangulate) // else if (sscanf(line.c_str(), "f %d/%d %d/%d %d/%d %d/%d", &a[0], &a[1], &b[0], &b[1], &c[0], &c[1], &d[0], &d[1]) == 8) { if (triangulate) { current_drawcall->tris.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, -1, -1, -1, a[1] - 1, b[1] - 1, c[1] - 1 }); current_drawcall->tris.push_back({ a[0] - 1, c[0] - 1, d[0] - 1, -1, -1, -1, a[1] - 1, c[1] - 1, d[1] - 1 }); } else current_drawcall->quads.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, d[0] - 1, -1, -1, -1, -1, a[1] - 1, b[1] - 1, c[1] - 1, d[1] - 1 }); } // face: 3x vertex/texel // else if (sscanf(line.c_str(), "f %d/%d %d/%d %d/%d", &a[0], &a[1], &b[0], &b[1], &c[0], &c[1]) == 6) { current_drawcall->tris.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, -1, -1, -1, a[1] - 1, b[1] - 1, c[1] - 1 }); } // face: 4x vertex//normal (triangulate) // else if (sscanf(line.c_str(), "f %d//%d %d//%d %d//%d %d//%d", &a[0], &a[1], &b[0], &b[1], &c[0], &c[1], &d[0], &d[1]) == 8) { if (triangulate) { current_drawcall->tris.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, a[1] - 1, b[1] - 1, c[1] - 1, -1, -1, -1 }); current_drawcall->tris.push_back({ a[0] - 1, c[0] - 1, d[0] - 1, a[1] - 1, c[1] - 1, d[1] - 1, -1, -1, -1 }); } else current_drawcall->quads.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, d[0] - 1, a[2] - 1, b[2] - 1, c[2] - 1, d[2] - 1, -1, -1, -1, -1 }); } // face: 3x vertex//normal // else if (sscanf(line.c_str(), "f %d//%d %d//%d %d//%d", &a[0], &a[1], &b[0], &b[1], &c[0], &c[1]) == 6) { current_drawcall->tris.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, a[1] - 1, b[1] - 1, c[1] - 1, -1, -1, -1 }); } // face: 4x vertex/texel/normal (triangulate) // else if (sscanf(line.c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d", &a[0], &a[1], &a[2], &b[0], &b[1], &b[2], &c[0], &c[1], &c[2], &d[0], &d[1], &d[2]) == 12) { if (triangulate) { current_drawcall->tris.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, a[2] - 1, b[2] - 1, c[2] - 1, a[1] - 1, b[1] - 1, c[1] - 1 }); current_drawcall->tris.push_back({ a[0] - 1, c[0] - 1, d[0] - 1, a[2] - 1, c[2] - 1, d[2] - 1, a[1] - 1, c[1] - 1, d[1] - 1 }); } else current_drawcall->quads.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, d[0] - 1, a[2] - 1, b[2] - 1, c[2] - 1, d[2] - 1, a[1] - 1, b[1] - 1, c[1] - 1, d[1] - 1 }); } // face: 3x vertex/texel/normal // else if (sscanf(line.c_str(), "f %d/%d/%d %d/%d/%d %d/%d/%d", &a[0], &a[1], &a[2], &b[0], &b[1], &b[2], &c[0], &c[1], &c[2]) == 9) { current_drawcall->tris.push_back({ a[0] - 1, b[0] - 1, c[0] - 1, a[2] - 1, b[2] - 1, c[2] - 1, a[1] - 1, b[1] - 1, c[1] - 1 }); } // unknown obj syntax // else { } } in.close(); // use defualt drawcall if no instance of usemtl if (!file_drawcalls.size()) file_drawcalls.push_back(default_drawcall); has_normals = (bool)file_normals.size(); has_texcoords = (bool)file_texcoords.size(); printf("Loaded:\n\t%d vertices\n\t%d texels\n\t%d normals\n\t%d drawcalls\n", (int)file_vertices.size(), (int)file_texcoords.size(), (int)file_normals.size(), (int)file_drawcalls.size()); #if 1 // auto-generate normals if (!has_normals && auto_generate_normals) { compute_normals(file_vertices, file_normals, file_drawcalls); has_normals = true; printf("Auto-generated %d normals\n", (int)file_normals.size()); } #endif #if 1 printf("Welding vertex array..."); std::unordered_map<std::string, unsigned> mtl_to_index_hash; // hash function for int3 struct int3_hashfunction { std::size_t operator () (const int3& i3) const { return i3.x; } }; for (auto &dc : file_drawcalls) { drawcall_t wdc; wdc.group_name = dc.group_name; std::unordered_map<int3, unsigned, int3_hashfunction> index3_to_index_hash; // material // if (dc.mtl_name.size()) { // // is material added to main vector? auto mtl_index = mtl_to_index_hash.find(dc.mtl_name); if (mtl_index == mtl_to_index_hash.end()) { auto mtl = file_materials.find(dc.mtl_name); if (mtl == file_materials.end()) throw std::runtime_error(std::string("Error: used material ") + dc.mtl_name + " not found\n"); wdc.mtl_index = (unsigned)materials.size(); mtl_to_index_hash[dc.mtl_name] = (unsigned)materials.size(); materials.push_back(mtl->second); } else wdc.mtl_index = mtl_index->second;; } else // mtl string is empty, use empty index wdc.mtl_index = -1; // weld vertices from triangles // for (auto &tri : dc.tris) { triangle_t wtri; for (int i = 0; i < 3; i++) { int3 i3 = { tri.vi[0 + i], tri.vi[3 + i], tri.vi[6 + i] }; auto s = index3_to_index_hash.find(i3); if (s == index3_to_index_hash.end()) { // index-combo does not exist, create it vertex_t v; v.Pos = file_vertices[i3.x]; if (i3.y > -1) v.Normal = file_normals[i3.y]; if (i3.z > -1) v.TexCoord = file_texcoords[i3.z]; wtri.vi[i] = (unsigned)vertices.size(); index3_to_index_hash[i3] = (unsigned)(vertices.size()); vertices.push_back(v); } else { // use existing index-combo wtri.vi[i] = s->second; } } wdc.tris.push_back(wtri); } #if 1 // weld vertices from quads // for (auto &quad : dc.quads) { quad_t_ wquad; for (int i = 0; i < 4; i++) { int3 i3 = { quad.vi[0 + i], quad.vi[3 + i], quad.vi[6 + i] }; auto s = index3_to_index_hash.find(i3); if (s == index3_to_index_hash.end()) { // index-combo does not exist, create it vertex_t v; v.Pos = file_vertices[i3.x]; if (i3.y > -1) v.Normal = file_normals[i3.y]; if (i3.z > -1) v.TexCoord = file_texcoords[i3.z]; wquad.vi[i] = (unsigned)vertices.size(); index3_to_index_hash[i3] = (unsigned)(vertices.size()); vertices.push_back(v); } else { // use existing index-combo wquad.vi[i] = s->second; } } wdc.quads.push_back(wquad); } #endif drawcalls.push_back(wdc); } printf("Done\n"); // Produce and print some stats // int tris = 0, quads = 0; for (auto &dc : drawcalls){ tris += dc.tris.size(); quads += dc.quads.size(); } printf("\t%d vertices\n\t%d drawcalls\n\t%d triangles\n\t%d quads\n", vertices.size(), drawcalls.size(), tris, quads); printf("Loaded materials:\n"); for (auto &mtl : materials) printf("\t%s\n", mtl.name.c_str()); #ifdef MESH_FORCE_CCW // Force ccw: flip triangle if geometric normal points away from vertex normal (at index=0) for (auto& dc : drawcalls) for (auto& tri : dc.tris) { int a = tri.vi[0], b = tri.vi[1], c = tri.vi[2]; vec3f v0 = vertices[a].Pos, v1 = vertices[b].Pos, v2 = vertices[c].Pos; vec3f geo_n = linalg::normalize((v1-v0)%(v2-v0)); vec3f vert_n = vertices[a].Normal; if (linalg::dot(geo_n, vert_n) < 0) std::swap(tri.vi[0], tri.vi[1]); } #endif #ifdef MESH_SORT_DRAWCALLS std::sort(drawcalls.begin(), drawcalls.end()); printf("Sorted drawcalls\n"); #endif #endif }
[ "46970089+ai7900@users.noreply.github.com" ]
46970089+ai7900@users.noreply.github.com
f8c13462099a09d77f750bda0eec69a28ba3a734
22d423e5f9b74dfffb3646160761aeb0e4a8a063
/Übungsaufgaben/A03/3_1_2.cpp
983211687b850f56d2e470b93ae51eb530875472
[]
no_license
elenaiwnw/Progra-Arbeitsverzeichnis
f900a243df43a7d1db7fa55c75a9965bb52cc9a6
bfce2bf0a0d57cd416fb1caf48792adc1fd54669
refs/heads/master
2022-04-06T19:37:43.314047
2020-02-09T18:32:32
2020-02-09T18:32:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,970
cpp
#include<iostream> #include<cmath> using namespace std; int n; // Zählt wie oft Funktion f() verwendet wird // Die mathematische Funktion aus der Aufgabe double f(double x) { n++; if (x<=-2) { return cos((M_PI/2)*x)+3; } else if (x<=0) { return 2*x+6; } else if (x<=2) { return 3*x*x+6; } else { return 18; } } // Funktion A() schätzt den Integralwert zur Funktion f() zwischen zwei Grenzen l und r und mit einem gegebenen Epsilon double A(double l, double r, double eps) { double fl = f(l); // Funktionswert an der linken Grenze double fr = f(r); // Funktionswert an der rechten Grenze // Vergleiche exakten und approximierten Funktionswert an der Stelle (l+r)/2 if (abs(f((l+r)/2) - (fl+fr)/2) > eps) { // Abweichung zu groß, also halbiere Intervallbreite und starte mit neuen Grenzen return A(l,(r+l)/2,eps) + A((r+l)/2,r,eps); } else { // Abweichung < eps, also errechne Fläche des Trapez return ((fl+fr)/2)*(r-l); } } int main() { // Deklarierung von Variablen double l = -4; double r = 4; double eps, a; // Legende cout << "eps: \tEpsilon" << endl; cout << "a: \tgeschätzter Integralwert" << endl; cout << "n: \tAnzahl der Funktionsauswertungen" << endl; cout << "E: \trelativer Fehler" << endl; cout << endl; // Errechne geschätzten Integralwert für verschiedene Genauigkeiten for (int i=1;i<=4;i++) { eps=pow(10,-i); // eps = aktuelles Epsilon cout << "eps=" << eps << endl; n=0; // Zähler zurücksetzen /* Ausgabe des geschätzten Integralwerts zu den gegebenen Grenzen und mit aktueller Genauigkeit. Funktion wird zweimal aufgerufen, damit die maximale Intervall-Breite eines Trapezes der halben Breite des zu berechnenden Integrals entspricht */ a = A(l,(l+r)/2,eps) + A((l+r)/2,r,eps); cout << "\ta=" << a << endl; cout << "\tn=" << n << endl; cout << "\tE=" << (a-70)/70 << endl; cout << endl; } return 0; }
[ "paul.orschau@icloud.com" ]
paul.orschau@icloud.com
813807ffa99157887687ad4364e72c008c81f192
9948e90ab62f394b1414f94458b2069311130c38
/MVD_15_Shadows-master/src/GraphicsUtilities.cpp
44b92bd395e4084fa1d790387900e0b2c3cfcdbd
[]
no_license
lauriChu/MVD_FirstCustomShader
fda96443356465427f213fb24fc0707e7383a39d
def32a44e188db7dd9762080e0376cca888d4af2
refs/heads/master
2020-04-25T05:43:31.657266
2019-03-08T18:44:54
2019-03-08T18:44:54
172,553,384
0
0
null
null
null
null
UTF-8
C++
false
false
4,721
cpp
#include "GraphicsUtilities.h" // ****** GEOMETRY ***** // //generates buffers in VRAM Geometry::Geometry(std::vector<float>& vertices, std::vector<float>& uvs, std::vector<float>& normals, std::vector<unsigned int>& indices) { createVertexArrays(vertices, uvs, normals, indices); } void Geometry::render() { glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, num_tris * 3, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } void Geometry::createVertexArrays(std::vector<float>& vertices, std::vector<float>& uvs, std::vector<float>& normals, std::vector<unsigned int>& indices) { //generate and bind vao glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vbo; //positions glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), &(vertices[0]), GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); //texture coords glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(float), &(uvs[0]), GL_STATIC_DRAW); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); //normals glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(float), &(normals[0]), GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); //indices GLuint ibo; glGenBuffers(1, &ibo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &(indices[0]), GL_STATIC_DRAW); //unbind glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); //set number of triangles num_tris = (GLuint)indices.size() / 3; //set AABB setAABB(vertices); } // Given an array of floats (in sets of three, representing vertices) calculates and // sets the AABB of a geometry void Geometry::setAABB(std::vector<GLfloat>& vertices) { //set very max and very min float big = 1000000.0f; float small = -1000000.0f; lm::vec3 min(big, big, big); lm::vec3 max(small, small, small); //for all verts, find max and min for (size_t i = 0; i < vertices.size(); i += 3) { float x = vertices[i]; float y = vertices[i + 1]; float z = vertices[i + 2]; if (x < min.x) min.x = x; if (y < min.y) min.y = y; if (z < min.z) min.z = z; if (x > max.x) max.x = x; if (y > max.y) max.y = y; if (z > max.z) max.z = z; } //set center and halfwidth based on max and min aabb.center = lm::vec3((min.x + max.x) / 2, (min.y + max.y) / 2, (min.z + max.z) / 2); aabb.half_width = lm::vec3(max.x - aabb.center.x, max.y - aabb.center.y, max.z - aabb.center.z); } //creates a standard plane geometry and return its int Geometry::createPlaneGeometry() { std::vector<GLfloat> vertices, uvs, normals; std::vector<GLuint> indices; vertices = { -1.0f, -1.0f, 0.0f, 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f }; uvs = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f }; normals = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; indices = { 0, 1, 2, 0, 2, 3 }; //generate the OpenGL buffers and create geometry createVertexArrays(vertices, uvs, normals, indices); return 1; } void Framebuffer::bindAndClear() { glViewport(0, 0, width, height); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Framebuffer::initColor(GLsizei w, GLsizei h) { width = w; height = h; glGenFramebuffers(1, &(framebuffer)); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glGenTextures(1, &(color_textures[0])); glBindTexture(GL_TEXTURE_2D, color_textures[0]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_textures[0], 0); unsigned int rbo; glGenRenderbuffers(1, &rbo); glBindRenderbuffer(GL_RENDERBUFFER, rbo); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); glBindRenderbuffer(GL_RENDERBUFFER, 0); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rbo); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "ERROR::FRAMEBUFFER:: Framebuffer is not complete!" << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); } void Framebuffer::initDepth(GLsizei w, GLsizei h) { width = w; height = h; }
[ "lau.gf92@gmail.com" ]
lau.gf92@gmail.com
6d0a3d9ffadf7d6092bc8d1ab2fa2443834453cb
b68c932209eafc7077815ed94c7dbf834287a0b4
/applications/PoromechanicsApplication/custom_elements/U_Pw_small_strain_interface_element.cpp
d8f4b4aa6e955ad31b0822fa1b2766fd75a07e51
[ "BSD-3-Clause" ]
permissive
electricintel/Kratos
f9cee22187b24a9363dae8ae8720c6441e5deace
bf76c92022d7da942f26ce9478334befd1ebe174
refs/heads/master
2023-01-20T13:04:54.439161
2020-11-29T07:22:06
2020-11-29T07:22:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
93,746
cpp
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Ignasi de Pouplana // // Application includes #include "custom_elements/U_Pw_small_strain_interface_element.hpp" namespace Kratos { template< unsigned int TDim, unsigned int TNumNodes > Element::Pointer UPwSmallStrainInterfaceElement<TDim,TNumNodes>::Create( IndexType NewId, NodesArrayType const& ThisNodes, PropertiesType::Pointer pProperties ) const { return Element::Pointer( new UPwSmallStrainInterfaceElement( NewId, this->GetGeometry().Create( ThisNodes ), pProperties ) ); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > Element::Pointer UPwSmallStrainInterfaceElement<TDim,TNumNodes>::Create(IndexType NewId, GeometryType::Pointer pGeom, PropertiesType::Pointer pProperties) const { return Element::Pointer( new UPwSmallStrainInterfaceElement( NewId, pGeom, pProperties ) ); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > int UPwSmallStrainInterfaceElement<TDim,TNumNodes>::Check( const ProcessInfo& rCurrentProcessInfo ) const { KRATOS_TRY const PropertiesType& Prop = this->GetProperties(); if (this->Id() < 1) KRATOS_THROW_ERROR(std::logic_error, "Element found with Id 0 or negative","") // Verify generic variables int ierr = UPwElement<TDim,TNumNodes>::Check(rCurrentProcessInfo); if(ierr != 0) return ierr; // Verify specific properties if ( MINIMUM_JOINT_WIDTH.Key() == 0 || Prop.Has( MINIMUM_JOINT_WIDTH ) == false || Prop[MINIMUM_JOINT_WIDTH] <= 0.0 ) KRATOS_THROW_ERROR( std::invalid_argument,"MINIMUM_JOINT_WIDTH has Key zero, is not defined or has an invalid value at element", this->Id() ) if ( TRANSVERSAL_PERMEABILITY.Key() == 0 || Prop.Has( TRANSVERSAL_PERMEABILITY ) == false || Prop[TRANSVERSAL_PERMEABILITY] < 0.0 ) KRATOS_THROW_ERROR( std::invalid_argument,"TRANSVERSAL_PERMEABILITY has Key zero, is not defined or has an invalid value at element", this->Id() ) // Verify the constitutive law if ( CONSTITUTIVE_LAW.Key() == 0 || Prop.Has( CONSTITUTIVE_LAW ) == false ) KRATOS_THROW_ERROR( std::invalid_argument, "CONSTITUTIVE_LAW has Key zero or is not defined at element ", this->Id() ) if ( Prop[CONSTITUTIVE_LAW] != NULL ) { // Verify compatibility of the element with the constitutive law ConstitutiveLaw::Features LawFeatures; Prop[CONSTITUTIVE_LAW]->GetLawFeatures(LawFeatures); bool correct_strain_measure = false; for(unsigned int i=0; i<LawFeatures.mStrainMeasures.size(); i++) { if(LawFeatures.mStrainMeasures[i] == ConstitutiveLaw::StrainMeasure_Infinitesimal) correct_strain_measure = true; } if( correct_strain_measure == false ) KRATOS_THROW_ERROR( std::logic_error, "constitutive law is not compatible with the element type", " StrainMeasure_Infinitesimal " ); // Check constitutive law ierr = Prop[CONSTITUTIVE_LAW]->Check( Prop, this->GetGeometry(), rCurrentProcessInfo ); } else KRATOS_THROW_ERROR( std::logic_error, "A constitutive law needs to be specified for the element ", this->Id() ) return ierr; KRATOS_CATCH( "" ); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::Initialize(const ProcessInfo& rCurrentProcessInfo) { KRATOS_TRY UPwElement<TDim,TNumNodes>::Initialize(rCurrentProcessInfo); //Compute initial gap of the joint this->CalculateInitialGap(this->GetGeometry()); KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateMassMatrix( MatrixType& rMassMatrix, const ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY const unsigned int element_size = TNumNodes * (TDim + 1); //Resizing mass matrix if ( rMassMatrix.size1() != element_size ) rMassMatrix.resize( element_size, element_size, false ); noalias( rMassMatrix ) = ZeroMatrix( element_size, element_size ); const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const GeometryType::IntegrationPointsArrayType& integration_points = Geom.IntegrationPoints( mThisIntegrationMethod ); const unsigned int NumGPoints = integration_points.size(); //Defining shape functions and the determinant of the jacobian at all integration points const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); Vector detJContainer(NumGPoints); Geom.DeterminantOfJacobian(detJContainer,mThisIntegrationMethod); //Defining necessary variables double IntegrationCoefficient; const double& Porosity = Prop[POROSITY]; const double Density = Porosity*Prop[DENSITY_WATER] + (1.0-Porosity)*Prop[DENSITY_SOLID]; BoundedMatrix<double,TDim+1, TNumNodes*(TDim+1)> Nut = ZeroMatrix(TDim+1, TNumNodes*(TDim+1)); array_1d<double,TNumNodes*TDim> DisplacementVector; PoroElementUtilities::GetNodalVariableVector(DisplacementVector,Geom,DISPLACEMENT); BoundedMatrix<double,TDim, TDim> RotationMatrix; this->CalculateRotationMatrix(RotationMatrix,Geom); BoundedMatrix<double,TDim, TNumNodes*TDim> Nu = ZeroMatrix(TDim, TNumNodes*TDim); array_1d<double,TDim> LocalRelDispVector; array_1d<double,TDim> RelDispVector; const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; double JointWidth; //Loop over integration points for ( unsigned int GPoint = 0; GPoint < NumGPoints; GPoint++ ) { InterfaceElementUtilities::CalculateNuMatrix(Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Nu,DisplacementVector); noalias(LocalRelDispVector) = prod(RotationMatrix,RelDispVector); this->CalculateJointWidth(JointWidth, LocalRelDispVector[TDim-1], MinimumJointWidth,GPoint); InterfaceElementUtilities::CalculateNuElementMatrix(Nut,NContainer,GPoint); //calculating weighting coefficient for integration this->CalculateIntegrationCoefficient( IntegrationCoefficient, detJContainer[GPoint], integration_points[GPoint].Weight() ); //Adding contribution to Mass matrix noalias(rMassMatrix) += Density*prod(trans(Nut),Nut)*JointWidth*IntegrationCoefficient; } KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::FinalizeSolutionStep( const ProcessInfo& rCurrentProcessInfo ) { KRATOS_TRY //Defining necessary variables const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); array_1d<double,TNumNodes*TDim> DisplacementVector; PoroElementUtilities::GetNodalVariableVector(DisplacementVector,Geom,DISPLACEMENT); BoundedMatrix<double,TDim, TDim> RotationMatrix; this->CalculateRotationMatrix(RotationMatrix,Geom); BoundedMatrix<double,TDim, TNumNodes*TDim> Nu = ZeroMatrix(TDim, TNumNodes*TDim); array_1d<double,TDim> RelDispVector; const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; double JointWidth; //Create constitutive law parameters: Vector StrainVector(TDim); Vector StressVector(TDim); Matrix ConstitutiveMatrix(TDim,TDim); Vector Np(TNumNodes); Matrix GradNpT(TNumNodes,TDim); Matrix F = identity_matrix<double>(TDim); double detF = 1.0; ConstitutiveLaw::Parameters ConstitutiveParameters(Geom,Prop,rCurrentProcessInfo); ConstitutiveParameters.SetConstitutiveMatrix(ConstitutiveMatrix); ConstitutiveParameters.SetStressVector(StressVector); ConstitutiveParameters.SetStrainVector(StrainVector); ConstitutiveParameters.SetShapeFunctionsValues(Np); ConstitutiveParameters.SetShapeFunctionsDerivatives(GradNpT); ConstitutiveParameters.SetDeterminantF(detF); ConstitutiveParameters.SetDeformationGradientF(F); ConstitutiveParameters.Set(ConstitutiveLaw::COMPUTE_STRESS); ConstitutiveParameters.Set(ConstitutiveLaw::USE_ELEMENT_PROVIDED_STRAIN); // Auxiliar output variables unsigned int NumGPoints = mConstitutiveLawVector.size(); std::vector<double> JointWidthContainer(NumGPoints); //Loop over integration points for ( unsigned int GPoint = 0; GPoint < NumGPoints; GPoint++ ) { InterfaceElementUtilities::CalculateNuMatrix(Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Nu,DisplacementVector); noalias(StrainVector) = prod(RotationMatrix,RelDispVector); JointWidthContainer[GPoint] = mInitialGap[GPoint] + StrainVector[TDim-1]; this->CheckAndCalculateJointWidth(JointWidth, ConstitutiveParameters, StrainVector[TDim-1], MinimumJointWidth, GPoint); noalias(Np) = row(NContainer,GPoint); //compute constitutive tensor and/or stresses mConstitutiveLawVector[GPoint]->FinalizeMaterialResponseCauchy(ConstitutiveParameters); } if(rCurrentProcessInfo[NODAL_SMOOTHING] == true) { this->ExtrapolateGPValues(JointWidthContainer); } KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template< > void UPwSmallStrainInterfaceElement<2,4>::ExtrapolateGPValues (const std::vector<double>& JointWidthContainer) { array_1d<double,2> DamageContainer; // 2 LobattoPoints for ( unsigned int i = 0; i < 2; i++ ) // NumLobattoPoints { DamageContainer[i] = 0.0; DamageContainer[i] = mConstitutiveLawVector[i]->GetValue( DAMAGE_VARIABLE, DamageContainer[i] ); } GeometryType& rGeom = this->GetGeometry(); const double& Area = rGeom.Area(); array_1d<double,4> NodalJointWidth; NodalJointWidth[0] = JointWidthContainer[0]*Area; NodalJointWidth[1] = JointWidthContainer[1]*Area; NodalJointWidth[2] = JointWidthContainer[1]*Area; NodalJointWidth[3] = JointWidthContainer[0]*Area; array_1d<double,4> NodalDamage; NodalDamage[0] = DamageContainer[0]*Area; NodalDamage[1] = DamageContainer[1]*Area; NodalDamage[2] = DamageContainer[1]*Area; NodalDamage[3] = DamageContainer[0]*Area; for(unsigned int i = 0; i < 4; i++) //NumNodes { rGeom[i].SetLock(); rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_WIDTH) += NodalJointWidth[i]; rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_DAMAGE) += NodalDamage[i]; rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_AREA) += Area; rGeom[i].UnSetLock(); } } //---------------------------------------------------------------------------------------- template< > void UPwSmallStrainInterfaceElement<3,6>::ExtrapolateGPValues (const std::vector<double>& JointWidthContainer) { array_1d<double,3> DamageContainer; // 3 LobattoPoints for ( unsigned int i = 0; i < 3; i++ ) // NumLobattoPoints { DamageContainer[i] = 0.0; DamageContainer[i] = mConstitutiveLawVector[i]->GetValue( DAMAGE_VARIABLE, DamageContainer[i] ); } GeometryType& rGeom = this->GetGeometry(); const double& Area = rGeom.Area(); array_1d<double,6> NodalJointWidth; NodalJointWidth[0] = JointWidthContainer[0]*Area; NodalJointWidth[1] = JointWidthContainer[1]*Area; NodalJointWidth[2] = JointWidthContainer[2]*Area; NodalJointWidth[3] = JointWidthContainer[0]*Area; NodalJointWidth[4] = JointWidthContainer[1]*Area; NodalJointWidth[5] = JointWidthContainer[2]*Area; array_1d<double,6> NodalDamage; NodalDamage[0] = DamageContainer[0]*Area; NodalDamage[1] = DamageContainer[1]*Area; NodalDamage[2] = DamageContainer[2]*Area; NodalDamage[3] = DamageContainer[0]*Area; NodalDamage[4] = DamageContainer[1]*Area; NodalDamage[5] = DamageContainer[2]*Area; for(unsigned int i = 0; i < 6; i++) //NumNodes { rGeom[i].SetLock(); rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_WIDTH) += NodalJointWidth[i]; rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_DAMAGE) += NodalDamage[i]; rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_AREA) += Area; rGeom[i].UnSetLock(); } } //---------------------------------------------------------------------------------------- template< > void UPwSmallStrainInterfaceElement<3,8>::ExtrapolateGPValues (const std::vector<double>& JointWidthContainer) { array_1d<double,4> DamageContainer; // 4 LobattoPoints for ( unsigned int i = 0; i < 4; i++ ) // NumLobattoPoints { DamageContainer[i] = 0.0; DamageContainer[i] = mConstitutiveLawVector[i]->GetValue( DAMAGE_VARIABLE, DamageContainer[i] ); } GeometryType& rGeom = this->GetGeometry(); const double& Area = rGeom.Area(); array_1d<double,8> NodalJointWidth; NodalJointWidth[0] = JointWidthContainer[0]*Area; NodalJointWidth[1] = JointWidthContainer[1]*Area; NodalJointWidth[2] = JointWidthContainer[2]*Area; NodalJointWidth[3] = JointWidthContainer[3]*Area; NodalJointWidth[4] = JointWidthContainer[0]*Area; NodalJointWidth[5] = JointWidthContainer[1]*Area; NodalJointWidth[6] = JointWidthContainer[2]*Area; NodalJointWidth[7] = JointWidthContainer[3]*Area; array_1d<double,8> NodalDamage; NodalDamage[0] = DamageContainer[0]*Area; NodalDamage[1] = DamageContainer[1]*Area; NodalDamage[2] = DamageContainer[2]*Area; NodalDamage[3] = DamageContainer[3]*Area; NodalDamage[4] = DamageContainer[0]*Area; NodalDamage[5] = DamageContainer[1]*Area; NodalDamage[6] = DamageContainer[2]*Area; NodalDamage[7] = DamageContainer[3]*Area; for(unsigned int i = 0; i < 8; i++) //NumNodes { rGeom[i].SetLock(); rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_WIDTH) += NodalJointWidth[i]; rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_DAMAGE) += NodalDamage[i]; rGeom[i].FastGetSolutionStepValue(NODAL_JOINT_AREA) += Area; rGeom[i].UnSetLock(); } } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateOnIntegrationPoints( const Variable<double>& rVariable, std::vector<double>& rValues,const ProcessInfo& rCurrentProcessInfo ) { if(rVariable == DAMAGE_VARIABLE) { //Variables computed on Lobatto points const GeometryType& Geom = this->GetGeometry(); const unsigned int NumGPoints = Geom.IntegrationPointsNumber( mThisIntegrationMethod ); std::vector<double> GPValues(NumGPoints); for ( unsigned int i = 0; i < NumGPoints; i++ ) GPValues[i] = mConstitutiveLawVector[i]->GetValue( rVariable, GPValues[i] ); //Printed on standard GiD Gauss points const unsigned int OutputGPoints = Geom.IntegrationPointsNumber( this->GetIntegrationMethod() ); if ( rValues.size() != OutputGPoints ) rValues.resize( OutputGPoints ); this->InterpolateOutputDoubles(rValues,GPValues); } else if(rVariable == STATE_VARIABLE) { if ( rValues.size() != mConstitutiveLawVector.size() ) rValues.resize(mConstitutiveLawVector.size()); for ( unsigned int i = 0; i < mConstitutiveLawVector.size(); i++ ) rValues[i] = mConstitutiveLawVector[i]->GetValue( rVariable, rValues[i] ); } else if(rVariable == JOINT_WIDTH) { //Variables computed on Lobatto points const GeometryType& Geom = this->GetGeometry(); const unsigned int NumGPoints = Geom.IntegrationPointsNumber( mThisIntegrationMethod ); std::vector<array_1d<double,3>> GPAuxValues(NumGPoints); this->CalculateOnIntegrationPoints(LOCAL_RELATIVE_DISPLACEMENT_VECTOR, GPAuxValues, rCurrentProcessInfo); std::vector<double> GPValues(NumGPoints); for(unsigned int i=0; i < NumGPoints; i++) { GPValues[i] = mInitialGap[i] + GPAuxValues[i][TDim-1]; } //Printed on standard GiD Gauss points const unsigned int OutputGPoints = Geom.IntegrationPointsNumber( this->GetIntegrationMethod() ); if ( rValues.size() != OutputGPoints ) rValues.resize( OutputGPoints ); this->InterpolateOutputDoubles(rValues,GPValues); } else { //Printed on standard GiD Gauss points const unsigned int OutputGPoints = this->GetGeometry().IntegrationPointsNumber( this->GetIntegrationMethod() ); if ( rValues.size() != OutputGPoints ) rValues.resize( OutputGPoints ); for(unsigned int i=0; i < OutputGPoints; i++) { rValues[i] = 0.0; } } } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateOnIntegrationPoints(const Variable<array_1d<double,3>>& rVariable, std::vector<array_1d<double,3>>& rValues,const ProcessInfo& rCurrentProcessInfo) { if(rVariable == FLUID_FLUX_VECTOR || rVariable == LOCAL_STRESS_VECTOR || rVariable == LOCAL_RELATIVE_DISPLACEMENT_VECTOR || rVariable == LOCAL_FLUID_FLUX_VECTOR) { //Variables computed on Lobatto points const GeometryType& Geom = this->GetGeometry(); std::vector<array_1d<double,3>> GPValues(Geom.IntegrationPointsNumber( mThisIntegrationMethod )); if(rVariable == FLUID_FLUX_VECTOR) { const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const unsigned int NumGPoints = Geom.IntegrationPointsNumber( mThisIntegrationMethod ); //Defining the shape functions, the jacobian and the shape functions local gradients Containers const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); const GeometryType::ShapeFunctionsGradientsType& DN_DeContainer = Geom.ShapeFunctionsLocalGradients( mThisIntegrationMethod ); GeometryType::JacobiansType JContainer(NumGPoints); Geom.Jacobian( JContainer, mThisIntegrationMethod ); //Defining necessary variables array_1d<double,TNumNodes> PressureVector; for(unsigned int i=0; i<TNumNodes; i++) PressureVector[i] = Geom[i].FastGetSolutionStepValue(WATER_PRESSURE); array_1d<double,TNumNodes*TDim> VolumeAcceleration; PoroElementUtilities::GetNodalVariableVector(VolumeAcceleration,Geom,VOLUME_ACCELERATION); array_1d<double,TDim> BodyAcceleration; array_1d<double,TNumNodes*TDim> DisplacementVector; PoroElementUtilities::GetNodalVariableVector(DisplacementVector,Geom,DISPLACEMENT); BoundedMatrix<double,TDim, TDim> RotationMatrix; this->CalculateRotationMatrix(RotationMatrix,Geom); BoundedMatrix<double,TDim, TNumNodes*TDim> Nu = ZeroMatrix(TDim, TNumNodes*TDim); array_1d<double,TDim> LocalRelDispVector; array_1d<double,TDim> RelDispVector; const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; double JointWidth; BoundedMatrix<double,TNumNodes, TDim> GradNpT; const double& Transversal_Permeability = Prop[TRANSVERSAL_PERMEABILITY]; BoundedMatrix<double,TDim, TDim> LocalPermeabilityMatrix = ZeroMatrix(TDim,TDim); const double& DynamicViscosityInverse = 1.0/Prop[DYNAMIC_VISCOSITY]; const double& FluidDensity = Prop[DENSITY_WATER]; array_1d<double,TDim> LocalFluidFlux; array_1d<double,TDim> GradPressureTerm; array_1d<double,TDim> FluidFlux; SFGradAuxVariables SFGradAuxVars; //Loop over integration points for ( unsigned int GPoint = 0; GPoint < NumGPoints; GPoint++ ) { InterfaceElementUtilities::CalculateNuMatrix(Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Nu,DisplacementVector); noalias(LocalRelDispVector) = prod(RotationMatrix,RelDispVector); this->CalculateJointWidth(JointWidth, LocalRelDispVector[TDim-1], MinimumJointWidth,GPoint); this->CalculateShapeFunctionsGradients< BoundedMatrix<double,TNumNodes,TDim> >(GradNpT,SFGradAuxVars,JContainer[GPoint],RotationMatrix, DN_DeContainer[GPoint],NContainer,JointWidth,GPoint); PoroElementUtilities::InterpolateVariableWithComponents(BodyAcceleration,NContainer,VolumeAcceleration,GPoint); InterfaceElementUtilities::CalculatePermeabilityMatrix(LocalPermeabilityMatrix,JointWidth,Transversal_Permeability); noalias(GradPressureTerm) = prod(trans(GradNpT),PressureVector); noalias(GradPressureTerm) += -FluidDensity*BodyAcceleration; noalias(LocalFluidFlux) = -DynamicViscosityInverse*prod(LocalPermeabilityMatrix,GradPressureTerm); noalias(FluidFlux) = prod(trans(RotationMatrix),LocalFluidFlux); PoroElementUtilities::FillArray1dOutput(GPValues[GPoint],FluidFlux); } } else if(rVariable == LOCAL_STRESS_VECTOR) { //Defining necessary variables const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); array_1d<double,TNumNodes*TDim> DisplacementVector; PoroElementUtilities::GetNodalVariableVector(DisplacementVector,Geom,DISPLACEMENT); BoundedMatrix<double,TDim, TDim> RotationMatrix; this->CalculateRotationMatrix(RotationMatrix,Geom); BoundedMatrix<double,TDim, TNumNodes*TDim> Nu = ZeroMatrix(TDim, TNumNodes*TDim); array_1d<double,TDim> RelDispVector; const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; double JointWidth; array_1d<double,TDim> LocalStressVector; //Create constitutive law parameters: Vector StrainVector(TDim); Vector StressVectorDynamic(TDim); Matrix ConstitutiveMatrix(TDim,TDim); Vector Np(TNumNodes); Matrix GradNpT(TNumNodes,TDim); Matrix F = identity_matrix<double>(TDim); double detF = 1.0; ConstitutiveLaw::Parameters ConstitutiveParameters(Geom,Prop,rCurrentProcessInfo); ConstitutiveParameters.Set(ConstitutiveLaw::COMPUTE_STRESS); ConstitutiveParameters.Set(ConstitutiveLaw::USE_ELEMENT_PROVIDED_STRAIN); ConstitutiveParameters.SetConstitutiveMatrix(ConstitutiveMatrix); ConstitutiveParameters.SetStressVector(StressVectorDynamic); ConstitutiveParameters.SetStrainVector(StrainVector); ConstitutiveParameters.SetShapeFunctionsValues(Np); ConstitutiveParameters.SetShapeFunctionsDerivatives(GradNpT); ConstitutiveParameters.SetDeterminantF(detF); ConstitutiveParameters.SetDeformationGradientF(F); //Loop over integration points for ( unsigned int GPoint = 0; GPoint < mConstitutiveLawVector.size(); GPoint++ ) { InterfaceElementUtilities::CalculateNuMatrix(Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Nu,DisplacementVector); noalias(StrainVector) = prod(RotationMatrix,RelDispVector); this->CheckAndCalculateJointWidth(JointWidth, ConstitutiveParameters, StrainVector[TDim-1], MinimumJointWidth, GPoint); noalias(Np) = row(NContainer,GPoint); //compute constitutive tensor and/or stresses mConstitutiveLawVector[GPoint]->CalculateMaterialResponseCauchy(ConstitutiveParameters); noalias(LocalStressVector) = StressVectorDynamic; PoroElementUtilities::FillArray1dOutput(GPValues[GPoint],LocalStressVector); } } else if(rVariable == LOCAL_RELATIVE_DISPLACEMENT_VECTOR) { //Defining necessary variables const GeometryType& Geom = this->GetGeometry(); const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); array_1d<double,TNumNodes*TDim> DisplacementVector; PoroElementUtilities::GetNodalVariableVector(DisplacementVector,Geom,DISPLACEMENT); BoundedMatrix<double,TDim, TDim> RotationMatrix; this->CalculateRotationMatrix(RotationMatrix,Geom); BoundedMatrix<double,TDim, TNumNodes*TDim> Nu = ZeroMatrix(TDim, TNumNodes*TDim); array_1d<double,TDim> LocalRelDispVector; array_1d<double,TDim> RelDispVector; //Loop over integration points for ( unsigned int GPoint = 0; GPoint < mConstitutiveLawVector.size(); GPoint++ ) { InterfaceElementUtilities::CalculateNuMatrix(Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Nu,DisplacementVector); noalias(LocalRelDispVector) = prod(RotationMatrix,RelDispVector); PoroElementUtilities::FillArray1dOutput(GPValues[GPoint],LocalRelDispVector); } } else if(rVariable == LOCAL_FLUID_FLUX_VECTOR) { const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const unsigned int NumGPoints = Geom.IntegrationPointsNumber( mThisIntegrationMethod ); //Defining the shape functions, the jacobian and the shape functions local gradients Containers const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); const GeometryType::ShapeFunctionsGradientsType& DN_DeContainer = Geom.ShapeFunctionsLocalGradients( mThisIntegrationMethod ); GeometryType::JacobiansType JContainer(NumGPoints); Geom.Jacobian( JContainer, mThisIntegrationMethod ); //Defining necessary variables array_1d<double,TNumNodes> PressureVector; for(unsigned int i=0; i<TNumNodes; i++) PressureVector[i] = Geom[i].FastGetSolutionStepValue(WATER_PRESSURE); array_1d<double,TNumNodes*TDim> VolumeAcceleration; PoroElementUtilities::GetNodalVariableVector(VolumeAcceleration,Geom,VOLUME_ACCELERATION); array_1d<double,TDim> BodyAcceleration; array_1d<double,TNumNodes*TDim> DisplacementVector; PoroElementUtilities::GetNodalVariableVector(DisplacementVector,Geom,DISPLACEMENT); BoundedMatrix<double,TDim, TDim> RotationMatrix; this->CalculateRotationMatrix(RotationMatrix,Geom); BoundedMatrix<double,TDim, TNumNodes*TDim> Nu = ZeroMatrix(TDim, TNumNodes*TDim); array_1d<double,TDim> LocalRelDispVector; array_1d<double,TDim> RelDispVector; const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; double JointWidth; BoundedMatrix<double,TNumNodes, TDim> GradNpT; const double& Transversal_Permeability = Prop[TRANSVERSAL_PERMEABILITY]; BoundedMatrix<double,TDim, TDim> LocalPermeabilityMatrix = ZeroMatrix(TDim,TDim); const double& DynamicViscosityInverse = 1.0/Prop[DYNAMIC_VISCOSITY]; const double& FluidDensity = Prop[DENSITY_WATER]; array_1d<double,TDim> LocalFluidFlux; array_1d<double,TDim> GradPressureTerm; SFGradAuxVariables SFGradAuxVars; //Loop over integration points for ( unsigned int GPoint = 0; GPoint < NumGPoints; GPoint++ ) { InterfaceElementUtilities::CalculateNuMatrix(Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Nu,DisplacementVector); noalias(LocalRelDispVector) = prod(RotationMatrix,RelDispVector); this->CalculateJointWidth(JointWidth, LocalRelDispVector[TDim-1], MinimumJointWidth,GPoint); this->CalculateShapeFunctionsGradients< BoundedMatrix<double,TNumNodes,TDim> >(GradNpT,SFGradAuxVars,JContainer[GPoint],RotationMatrix, DN_DeContainer[GPoint],NContainer,JointWidth,GPoint); PoroElementUtilities::InterpolateVariableWithComponents(BodyAcceleration,NContainer,VolumeAcceleration,GPoint); InterfaceElementUtilities::CalculatePermeabilityMatrix(LocalPermeabilityMatrix,JointWidth,Transversal_Permeability); noalias(GradPressureTerm) = prod(trans(GradNpT),PressureVector); noalias(GradPressureTerm) += -FluidDensity*BodyAcceleration; noalias(LocalFluidFlux) = -DynamicViscosityInverse*prod(LocalPermeabilityMatrix,GradPressureTerm); PoroElementUtilities::FillArray1dOutput(GPValues[GPoint],LocalFluidFlux); } } //Printed on standard GiD Gauss points const unsigned int OutputGPoints = Geom.IntegrationPointsNumber( this->GetIntegrationMethod() ); if ( rValues.size() != OutputGPoints ) rValues.resize( OutputGPoints ); this->InterpolateOutputValues< array_1d<double,3> >(rValues,GPValues); } else { //Printed on standard GiD Gauss points const unsigned int OutputGPoints = this->GetGeometry().IntegrationPointsNumber( this->GetIntegrationMethod() ); if ( rValues.size() != OutputGPoints ) rValues.resize( OutputGPoints ); for(unsigned int i=0; i < OutputGPoints; i++) { noalias(rValues[i]) = ZeroVector(3); } } } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateOnIntegrationPoints(const Variable<Matrix>& rVariable,std::vector<Matrix>& rValues, const ProcessInfo& rCurrentProcessInfo) { if(rVariable == PERMEABILITY_MATRIX || rVariable == LOCAL_PERMEABILITY_MATRIX) { //Variables computed on Lobatto points const GeometryType& Geom = this->GetGeometry(); std::vector<Matrix> GPValues(Geom.IntegrationPointsNumber( mThisIntegrationMethod )); if(rVariable == PERMEABILITY_MATRIX) { const GeometryType& Geom = this->GetGeometry(); const PropertiesType& Prop = this->GetProperties(); //Defining the shape functions container const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); //Defining necessary variables array_1d<double,TNumNodes*TDim> DisplacementVector; PoroElementUtilities::GetNodalVariableVector(DisplacementVector,Geom,DISPLACEMENT); BoundedMatrix<double,TDim, TDim> RotationMatrix; this->CalculateRotationMatrix(RotationMatrix,Geom); BoundedMatrix<double,TDim, TNumNodes*TDim> Nu = ZeroMatrix(TDim, TNumNodes*TDim); array_1d<double,TDim> LocalRelDispVector; array_1d<double,TDim> RelDispVector; const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; double JointWidth; const double& Transversal_Permeability = Prop[TRANSVERSAL_PERMEABILITY]; BoundedMatrix<double,TDim, TDim> LocalPermeabilityMatrix = ZeroMatrix(TDim,TDim); BoundedMatrix<double,TDim, TDim> PermeabilityMatrix; //Loop over integration points for ( unsigned int GPoint = 0; GPoint < mConstitutiveLawVector.size(); GPoint++ ) { InterfaceElementUtilities::CalculateNuMatrix(Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Nu,DisplacementVector); noalias(LocalRelDispVector) = prod(RotationMatrix,RelDispVector); this->CalculateJointWidth(JointWidth, LocalRelDispVector[TDim-1], MinimumJointWidth,GPoint); InterfaceElementUtilities::CalculatePermeabilityMatrix(LocalPermeabilityMatrix,JointWidth,Transversal_Permeability); noalias(PermeabilityMatrix) = prod(trans(RotationMatrix),BoundedMatrix<double,TDim, TDim>(prod(LocalPermeabilityMatrix,RotationMatrix))); GPValues[GPoint].resize(TDim,TDim,false); noalias(GPValues[GPoint]) = PermeabilityMatrix; } } else if(rVariable == LOCAL_PERMEABILITY_MATRIX) { const GeometryType& Geom = this->GetGeometry(); const PropertiesType& Prop = this->GetProperties(); //Defining the shape functions container const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); //Defining necessary variables array_1d<double,TNumNodes*TDim> DisplacementVector; PoroElementUtilities::GetNodalVariableVector(DisplacementVector,Geom,DISPLACEMENT); BoundedMatrix<double,TDim, TDim> RotationMatrix; this->CalculateRotationMatrix(RotationMatrix,Geom); BoundedMatrix<double,TDim, TNumNodes*TDim> Nu = ZeroMatrix(TDim, TNumNodes*TDim); array_1d<double,TDim> LocalRelDispVector; array_1d<double,TDim> RelDispVector; const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; double JointWidth; const double& Transversal_Permeability = Prop[TRANSVERSAL_PERMEABILITY]; BoundedMatrix<double,TDim, TDim> LocalPermeabilityMatrix = ZeroMatrix(TDim,TDim); //Loop over integration points for ( unsigned int GPoint = 0; GPoint < mConstitutiveLawVector.size(); GPoint++ ) { InterfaceElementUtilities::CalculateNuMatrix(Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Nu,DisplacementVector); noalias(LocalRelDispVector) = prod(RotationMatrix,RelDispVector); this->CalculateJointWidth(JointWidth, LocalRelDispVector[TDim-1], MinimumJointWidth,GPoint); InterfaceElementUtilities::CalculatePermeabilityMatrix(LocalPermeabilityMatrix,JointWidth,Transversal_Permeability); GPValues[GPoint].resize(TDim,TDim,false); noalias(GPValues[GPoint]) = LocalPermeabilityMatrix; } } //Printed on standard GiD Gauss points const unsigned int OutputGPoints = Geom.IntegrationPointsNumber( this->GetIntegrationMethod() ); if ( rValues.size() != OutputGPoints ) rValues.resize( OutputGPoints ); for(unsigned int GPoint=0; GPoint<OutputGPoints; GPoint++) rValues[GPoint].resize(TDim,TDim,false); this->InterpolateOutputValues< Matrix >(rValues,GPValues); } else { //Printed on standard GiD Gauss points const unsigned int OutputGPoints = this->GetGeometry().IntegrationPointsNumber( this->GetIntegrationMethod() ); if ( rValues.size() != OutputGPoints ) rValues.resize( OutputGPoints ); for(unsigned int i=0; i < OutputGPoints; i++) { rValues[i].resize(TDim,TDim,false); noalias(rValues[i]) = ZeroMatrix(TDim,TDim); } } } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- template< > void UPwSmallStrainInterfaceElement<2,4>::CalculateInitialGap(const GeometryType& Geom) { const double& MinimumJointWidth = this->GetProperties()[MINIMUM_JOINT_WIDTH]; mInitialGap.resize(2); mIsOpen.resize(2); array_1d<double,3> Vx; noalias(Vx) = Geom.GetPoint( 3 ) - Geom.GetPoint( 0 ); mInitialGap[0] = norm_2(Vx); if(mInitialGap[0] < MinimumJointWidth) mIsOpen[0] = false; else mIsOpen[0] = true; noalias(Vx) = Geom.GetPoint( 2 ) - Geom.GetPoint( 1 ); mInitialGap[1] = norm_2(Vx); if(mInitialGap[1] < MinimumJointWidth) mIsOpen[1] = false; else mIsOpen[1] = true; } //---------------------------------------------------------------------------------------- template< > void UPwSmallStrainInterfaceElement<3,6>::CalculateInitialGap(const GeometryType& Geom) { const double& MinimumJointWidth = this->GetProperties()[MINIMUM_JOINT_WIDTH]; mInitialGap.resize(3); mIsOpen.resize(3); array_1d<double,3> Vx; noalias(Vx) = Geom.GetPoint( 3 ) - Geom.GetPoint( 0 ); mInitialGap[0] = norm_2(Vx); if(mInitialGap[0] < MinimumJointWidth) mIsOpen[0] = false; else mIsOpen[0] = true; noalias(Vx) = Geom.GetPoint( 4 ) - Geom.GetPoint( 1 ); mInitialGap[1] = norm_2(Vx); if(mInitialGap[1] < MinimumJointWidth) mIsOpen[1] = false; else mIsOpen[1] = true; noalias(Vx) = Geom.GetPoint( 5 ) - Geom.GetPoint( 2 ); mInitialGap[2] = norm_2(Vx); if(mInitialGap[2] < MinimumJointWidth) mIsOpen[2] = false; else mIsOpen[2] = true; } //---------------------------------------------------------------------------------------- template< > void UPwSmallStrainInterfaceElement<3,8>::CalculateInitialGap(const GeometryType& Geom) { const double& MinimumJointWidth = this->GetProperties()[MINIMUM_JOINT_WIDTH]; mInitialGap.resize(4); mIsOpen.resize(4); array_1d<double,3> Vx; noalias(Vx) = Geom.GetPoint( 4 ) - Geom.GetPoint( 0 ); mInitialGap[0] = norm_2(Vx); if(mInitialGap[0] < MinimumJointWidth) mIsOpen[0] = false; else mIsOpen[0] = true; noalias(Vx) = Geom.GetPoint( 5 ) - Geom.GetPoint( 1 ); mInitialGap[1] = norm_2(Vx); if(mInitialGap[1] < MinimumJointWidth) mIsOpen[1] = false; else mIsOpen[1] = true; noalias(Vx) = Geom.GetPoint( 6 ) - Geom.GetPoint( 2 ); mInitialGap[2] = norm_2(Vx); if(mInitialGap[2] < MinimumJointWidth) mIsOpen[2] = false; else mIsOpen[2] = true; noalias(Vx) = Geom.GetPoint( 7 ) - Geom.GetPoint( 3 ); mInitialGap[3] = norm_2(Vx); if(mInitialGap[3] < MinimumJointWidth) mIsOpen[3] = false; else mIsOpen[3] = true; } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateStiffnessMatrix( MatrixType& rStiffnessMatrix, const ProcessInfo& CurrentProcessInfo ) { KRATOS_TRY const unsigned int element_size = TNumNodes * (TDim + 1); //Resizing mass matrix if ( rStiffnessMatrix.size1() != element_size ) rStiffnessMatrix.resize( element_size, element_size, false ); noalias( rStiffnessMatrix ) = ZeroMatrix( element_size, element_size ); //Previous definitions const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const GeometryType::IntegrationPointsArrayType& integration_points = Geom.IntegrationPoints( mThisIntegrationMethod ); const unsigned int NumGPoints = integration_points.size(); //Containers of variables at all integration points const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); const GeometryType::ShapeFunctionsGradientsType& DN_DeContainer = Geom.ShapeFunctionsLocalGradients( mThisIntegrationMethod ); GeometryType::JacobiansType JContainer(NumGPoints); Geom.Jacobian( JContainer, mThisIntegrationMethod ); Vector detJContainer(NumGPoints); Geom.DeterminantOfJacobian(detJContainer,mThisIntegrationMethod); //Constitutive Law parameters ConstitutiveLaw::Parameters ConstitutiveParameters(Geom,Prop,CurrentProcessInfo); ConstitutiveParameters.Set(ConstitutiveLaw::COMPUTE_CONSTITUTIVE_TENSOR); //Element variables InterfaceElementVariables Variables; this->InitializeElementVariables(Variables,ConstitutiveParameters,Geom,Prop,CurrentProcessInfo); //Auxiliary variables const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; array_1d<double,TDim> RelDispVector; SFGradAuxVariables SFGradAuxVars; //Loop over integration points for( unsigned int GPoint = 0; GPoint < NumGPoints; GPoint++) { //Compute Np, StrainVector, JointWidth, GradNpT noalias(Variables.Np) = row(NContainer,GPoint); InterfaceElementUtilities::CalculateNuMatrix(Variables.Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Variables.Nu,Variables.DisplacementVector); noalias(Variables.StrainVector) = prod(Variables.RotationMatrix,RelDispVector); this->CheckAndCalculateJointWidth(Variables.JointWidth,ConstitutiveParameters,Variables.StrainVector[TDim-1], MinimumJointWidth, GPoint); this->CalculateShapeFunctionsGradients< Matrix >(Variables.GradNpT,SFGradAuxVars,JContainer[GPoint],Variables.RotationMatrix, DN_DeContainer[GPoint],NContainer,Variables.JointWidth,GPoint); //Compute constitutive tensor mConstitutiveLawVector[GPoint]->CalculateMaterialResponseCauchy(ConstitutiveParameters); //Compute weighting coefficient for integration this->CalculateIntegrationCoefficient(Variables.IntegrationCoefficient, detJContainer[GPoint], integration_points[GPoint].Weight() ); //Compute stiffness matrix this->CalculateAndAddStiffnessMatrix(rStiffnessMatrix, Variables); } KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAll( MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, const ProcessInfo& CurrentProcessInfo ) { KRATOS_TRY //Previous definitions const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const GeometryType::IntegrationPointsArrayType& integration_points = Geom.IntegrationPoints( mThisIntegrationMethod ); const unsigned int NumGPoints = integration_points.size(); //Containers of variables at all integration points const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); const GeometryType::ShapeFunctionsGradientsType& DN_DeContainer = Geom.ShapeFunctionsLocalGradients( mThisIntegrationMethod ); GeometryType::JacobiansType JContainer(NumGPoints); Geom.Jacobian( JContainer, mThisIntegrationMethod ); Vector detJContainer(NumGPoints); Geom.DeterminantOfJacobian(detJContainer,mThisIntegrationMethod); //Constitutive Law parameters ConstitutiveLaw::Parameters ConstitutiveParameters(Geom,Prop,CurrentProcessInfo); ConstitutiveParameters.Set(ConstitutiveLaw::COMPUTE_CONSTITUTIVE_TENSOR); ConstitutiveParameters.Set(ConstitutiveLaw::COMPUTE_STRESS); ConstitutiveParameters.Set(ConstitutiveLaw::USE_ELEMENT_PROVIDED_STRAIN); //Element variables InterfaceElementVariables Variables; this->InitializeElementVariables(Variables,ConstitutiveParameters,Geom,Prop,CurrentProcessInfo); //Auxiliary variables const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; const double& Transversal_Permeability = Prop[TRANSVERSAL_PERMEABILITY]; array_1d<double,TDim> RelDispVector; SFGradAuxVariables SFGradAuxVars; //Loop over integration points for( unsigned int GPoint = 0; GPoint < NumGPoints; GPoint++) { //Compute Np, StrainVector, JointWidth, GradNpT noalias(Variables.Np) = row(NContainer,GPoint); InterfaceElementUtilities::CalculateNuMatrix(Variables.Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Variables.Nu,Variables.DisplacementVector); noalias(Variables.StrainVector) = prod(Variables.RotationMatrix,RelDispVector); this->CheckAndCalculateJointWidth(Variables.JointWidth,ConstitutiveParameters,Variables.StrainVector[TDim-1], MinimumJointWidth, GPoint); this->CalculateShapeFunctionsGradients< Matrix >(Variables.GradNpT,SFGradAuxVars,JContainer[GPoint],Variables.RotationMatrix, DN_DeContainer[GPoint],NContainer,Variables.JointWidth,GPoint); //Compute BodyAcceleration and Permeability Matrix PoroElementUtilities::InterpolateVariableWithComponents(Variables.BodyAcceleration,NContainer,Variables.VolumeAcceleration,GPoint); InterfaceElementUtilities::CalculatePermeabilityMatrix(Variables.LocalPermeabilityMatrix,Variables.JointWidth,Transversal_Permeability); //Compute constitutive tensor and stresses mConstitutiveLawVector[GPoint]->CalculateMaterialResponseCauchy(ConstitutiveParameters); //Compute weighting coefficient for integration this->CalculateIntegrationCoefficient(Variables.IntegrationCoefficient, detJContainer[GPoint], integration_points[GPoint].Weight() ); //Contributions to the left hand side this->CalculateAndAddLHS(rLeftHandSideMatrix, Variables); //Contributions to the right hand side this->CalculateAndAddRHS(rRightHandSideVector, Variables); } KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateRHS( VectorType& rRightHandSideVector, const ProcessInfo& CurrentProcessInfo ) { KRATOS_TRY //Previous definitions const PropertiesType& Prop = this->GetProperties(); const GeometryType& Geom = this->GetGeometry(); const GeometryType::IntegrationPointsArrayType& integration_points = Geom.IntegrationPoints( mThisIntegrationMethod ); const unsigned int NumGPoints = integration_points.size(); //Containers of variables at all integration points const Matrix& NContainer = Geom.ShapeFunctionsValues( mThisIntegrationMethod ); const GeometryType::ShapeFunctionsGradientsType& DN_DeContainer = Geom.ShapeFunctionsLocalGradients( mThisIntegrationMethod ); GeometryType::JacobiansType JContainer(NumGPoints); Geom.Jacobian( JContainer, mThisIntegrationMethod ); Vector detJContainer(NumGPoints); Geom.DeterminantOfJacobian(detJContainer,mThisIntegrationMethod); //Constitutive Law parameters ConstitutiveLaw::Parameters ConstitutiveParameters(Geom,Prop,CurrentProcessInfo); ConstitutiveParameters.Set(ConstitutiveLaw::COMPUTE_STRESS); ConstitutiveParameters.Set(ConstitutiveLaw::USE_ELEMENT_PROVIDED_STRAIN); //Element variables InterfaceElementVariables Variables; this->InitializeElementVariables(Variables,ConstitutiveParameters,Geom,Prop,CurrentProcessInfo); //Auxiliary variables const double& MinimumJointWidth = Prop[MINIMUM_JOINT_WIDTH]; const double& Transversal_Permeability = Prop[TRANSVERSAL_PERMEABILITY]; array_1d<double,TDim> RelDispVector; SFGradAuxVariables SFGradAuxVars; //Loop over integration points for( unsigned int GPoint = 0; GPoint < NumGPoints; GPoint++) { //Compute Np, StrainVector, JointWidth, GradNpT noalias(Variables.Np) = row(NContainer,GPoint); InterfaceElementUtilities::CalculateNuMatrix(Variables.Nu,NContainer,GPoint); noalias(RelDispVector) = prod(Variables.Nu,Variables.DisplacementVector); noalias(Variables.StrainVector) = prod(Variables.RotationMatrix,RelDispVector); this->CheckAndCalculateJointWidth(Variables.JointWidth,ConstitutiveParameters,Variables.StrainVector[TDim-1], MinimumJointWidth, GPoint); this->CalculateShapeFunctionsGradients< Matrix >(Variables.GradNpT,SFGradAuxVars,JContainer[GPoint],Variables.RotationMatrix, DN_DeContainer[GPoint],NContainer,Variables.JointWidth,GPoint); //Compute BodyAcceleration and Permeability Matrix PoroElementUtilities::InterpolateVariableWithComponents(Variables.BodyAcceleration,NContainer,Variables.VolumeAcceleration,GPoint); InterfaceElementUtilities::CalculatePermeabilityMatrix(Variables.LocalPermeabilityMatrix,Variables.JointWidth,Transversal_Permeability); //Compute stresses mConstitutiveLawVector[GPoint]->CalculateMaterialResponseCauchy(ConstitutiveParameters); //Compute weighting coefficient for integration this->CalculateIntegrationCoefficient(Variables.IntegrationCoefficient, detJContainer[GPoint], integration_points[GPoint].Weight() ); //Contributions to the right hand side this->CalculateAndAddRHS(rRightHandSideVector, Variables); } KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::InitializeElementVariables(InterfaceElementVariables& rVariables,ConstitutiveLaw::Parameters& rConstitutiveParameters, const GeometryType& Geom, const PropertiesType& Prop, const ProcessInfo& CurrentProcessInfo) { KRATOS_TRY //Properties variables const double& BulkModulusSolid = Prop[BULK_MODULUS_SOLID]; const double& Porosity = Prop[POROSITY]; const double BulkModulus = Prop[YOUNG_MODULUS]/(3.0*(1.0-2.0*Prop[POISSON_RATIO])); rVariables.DynamicViscosityInverse = 1.0/Prop[DYNAMIC_VISCOSITY]; rVariables.FluidDensity = Prop[DENSITY_WATER]; rVariables.Density = Porosity*rVariables.FluidDensity + (1.0-Porosity)*Prop[DENSITY_SOLID]; rVariables.BiotCoefficient = 1.0-BulkModulus/BulkModulusSolid; rVariables.BiotModulusInverse = (rVariables.BiotCoefficient-Porosity)/BulkModulusSolid + Porosity/Prop[BULK_MODULUS_FLUID]; //ProcessInfo variables rVariables.VelocityCoefficient = CurrentProcessInfo[VELOCITY_COEFFICIENT]; rVariables.DtPressureCoefficient = CurrentProcessInfo[DT_PRESSURE_COEFFICIENT]; //Nodal Variables for(unsigned int i=0; i<TNumNodes; i++) { rVariables.PressureVector[i] = Geom[i].FastGetSolutionStepValue(WATER_PRESSURE); rVariables.DtPressureVector[i] = Geom[i].FastGetSolutionStepValue(DT_WATER_PRESSURE); } PoroElementUtilities::GetNodalVariableVector(rVariables.DisplacementVector,Geom,DISPLACEMENT); PoroElementUtilities::GetNodalVariableVector(rVariables.VelocityVector,Geom,VELOCITY); PoroElementUtilities::GetNodalVariableVector(rVariables.VolumeAcceleration,Geom,VOLUME_ACCELERATION); //General Variables this->CalculateRotationMatrix(rVariables.RotationMatrix,Geom); InterfaceElementUtilities::CalculateVoigtVector(rVariables.VoigtVector); //Variables computed at each GP //Constitutive Law parameters rVariables.StrainVector.resize(TDim,false); rVariables.StressVector.resize(TDim,false); rVariables.ConstitutiveMatrix.resize(TDim,TDim,false); rVariables.Np.resize(TNumNodes,false); rVariables.GradNpT.resize(TNumNodes,TDim,false); rVariables.F.resize(TDim,TDim,false); rVariables.detF = 1.0; rConstitutiveParameters.SetStrainVector(rVariables.StrainVector); rConstitutiveParameters.SetStressVector(rVariables.StressVector); rConstitutiveParameters.SetConstitutiveMatrix(rVariables.ConstitutiveMatrix); rConstitutiveParameters.SetShapeFunctionsValues(rVariables.Np); rConstitutiveParameters.SetShapeFunctionsDerivatives(rVariables.GradNpT); rConstitutiveParameters.SetDeformationGradientF(rVariables.F); rConstitutiveParameters.SetDeterminantF(rVariables.detF); //Auxiliary variables noalias(rVariables.Nu) = ZeroMatrix(TDim, TNumNodes*TDim); noalias(rVariables.LocalPermeabilityMatrix) = ZeroMatrix(TDim,TDim); KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template<> void UPwSmallStrainInterfaceElement<2,4>::CalculateRotationMatrix(BoundedMatrix<double,2,2>& rRotationMatrix, const GeometryType& Geom) { KRATOS_TRY //Define mid-plane points for quadrilateral_interface_2d_4 array_1d<double, 3> pmid0; array_1d<double, 3> pmid1; noalias(pmid0) = 0.5 * (Geom.GetPoint( 0 ) + Geom.GetPoint( 3 )); noalias(pmid1) = 0.5 * (Geom.GetPoint( 1 ) + Geom.GetPoint( 2 )); //Unitary vector in local x direction array_1d<double, 3> Vx; noalias(Vx) = pmid1 - pmid0; double inv_norm_x = 1.0/norm_2(Vx); Vx[0] *= inv_norm_x; Vx[1] *= inv_norm_x; //Rotation Matrix rRotationMatrix(0,0) = Vx[0]; rRotationMatrix(0,1) = Vx[1]; // We need to determine the unitary vector in local y direction pointing towards the TOP face of the joint // Unitary vector in local x direction (3D) array_1d<double, 3> Vx3D; Vx3D[0] = Vx[0]; Vx3D[1] = Vx[1]; Vx3D[2] = 0.0; // Unitary vector in local y direction (first option) array_1d<double, 3> Vy3D; Vy3D[0] = -Vx[1]; Vy3D[1] = Vx[0]; Vy3D[2] = 0.0; // Vector in global z direction (first option) array_1d<double, 3> Vz; MathUtils<double>::CrossProduct(Vz, Vx3D, Vy3D); // Vz must have the same sign as vector (0,0,1) if(Vz[2] > 0.0) { rRotationMatrix(1,0) = -Vx[1]; rRotationMatrix(1,1) = Vx[0]; } else { rRotationMatrix(1,0) = Vx[1]; rRotationMatrix(1,1) = -Vx[0]; } KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template<> void UPwSmallStrainInterfaceElement<3,6>::CalculateRotationMatrix(BoundedMatrix<double,3,3>& rRotationMatrix, const GeometryType& Geom) { KRATOS_TRY //Define mid-plane points for prism_interface_3d_6 array_1d<double, 3> pmid0; array_1d<double, 3> pmid1; array_1d<double, 3> pmid2; noalias(pmid0) = 0.5 * (Geom.GetPoint( 0 ) + Geom.GetPoint( 3 )); noalias(pmid1) = 0.5 * (Geom.GetPoint( 1 ) + Geom.GetPoint( 4 )); noalias(pmid2) = 0.5 * (Geom.GetPoint( 2 ) + Geom.GetPoint( 5 )); //Unitary vector in local x direction array_1d<double, 3> Vx; noalias(Vx) = pmid1 - pmid0; double inv_norm = 1.0/norm_2(Vx); Vx[0] *= inv_norm; Vx[1] *= inv_norm; Vx[2] *= inv_norm; //Unitary vector in local z direction array_1d<double, 3> Vy; noalias(Vy) = pmid2 - pmid0; array_1d<double, 3> Vz; MathUtils<double>::CrossProduct(Vz, Vx, Vy); inv_norm = 1.0/norm_2(Vz); Vz[0] *= inv_norm; Vz[1] *= inv_norm; Vz[2] *= inv_norm; //Unitary vector in local y direction MathUtils<double>::CrossProduct( Vy, Vz, Vx); //Rotation Matrix rRotationMatrix(0,0) = Vx[0]; rRotationMatrix(0,1) = Vx[1]; rRotationMatrix(0,2) = Vx[2]; rRotationMatrix(1,0) = Vy[0]; rRotationMatrix(1,1) = Vy[1]; rRotationMatrix(1,2) = Vy[2]; rRotationMatrix(2,0) = Vz[0]; rRotationMatrix(2,1) = Vz[1]; rRotationMatrix(2,2) = Vz[2]; KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template<> void UPwSmallStrainInterfaceElement<3,8>::CalculateRotationMatrix(BoundedMatrix<double,3,3>& rRotationMatrix, const GeometryType& Geom) { KRATOS_TRY //Define mid-plane points for hexahedra_interface_3d_8 array_1d<double, 3> pmid0; array_1d<double, 3> pmid1; array_1d<double, 3> pmid2; noalias(pmid0) = 0.5 * (Geom.GetPoint( 0 ) + Geom.GetPoint( 4 )); noalias(pmid1) = 0.5 * (Geom.GetPoint( 1 ) + Geom.GetPoint( 5 )); noalias(pmid2) = 0.5 * (Geom.GetPoint( 2 ) + Geom.GetPoint( 6 )); //Unitary vector in local x direction array_1d<double, 3> Vx; noalias(Vx) = pmid1 - pmid0; double inv_norm = 1.0/norm_2(Vx); Vx[0] *= inv_norm; Vx[1] *= inv_norm; Vx[2] *= inv_norm; //Unitary vector in local z direction array_1d<double, 3> Vy; noalias(Vy) = pmid2 - pmid0; array_1d<double, 3> Vz; MathUtils<double>::CrossProduct(Vz, Vx, Vy); inv_norm = 1.0/norm_2(Vz); Vz[0] *= inv_norm; Vz[1] *= inv_norm; Vz[2] *= inv_norm; //Unitary vector in local y direction MathUtils<double>::CrossProduct( Vy, Vz, Vx); //Rotation Matrix rRotationMatrix(0,0) = Vx[0]; rRotationMatrix(0,1) = Vx[1]; rRotationMatrix(0,2) = Vx[2]; rRotationMatrix(1,0) = Vy[0]; rRotationMatrix(1,1) = Vy[1]; rRotationMatrix(1,2) = Vy[2]; rRotationMatrix(2,0) = Vz[0]; rRotationMatrix(2,1) = Vz[1]; rRotationMatrix(2,2) = Vz[2]; KRATOS_CATCH( "" ) } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateJointWidth(double& rJointWidth, const double& NormalRelDisp, const double& MinimumJointWidth,const unsigned int& GPoint) { rJointWidth = mInitialGap[GPoint] + NormalRelDisp; if(rJointWidth < MinimumJointWidth) { rJointWidth = MinimumJointWidth; } } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CheckAndCalculateJointWidth(double& rJointWidth, ConstitutiveLaw::Parameters& rConstitutiveParameters, double& rNormalRelDisp,const double& MinimumJointWidth,const unsigned int& GPoint) { rJointWidth = mInitialGap[GPoint] + rNormalRelDisp; rConstitutiveParameters.Set(ConstitutiveLaw::COMPUTE_STRAIN_ENERGY); // No contact between interfaces // Initally open joint if(mIsOpen[GPoint]==true) { if(rJointWidth < MinimumJointWidth) { rConstitutiveParameters.Reset(ConstitutiveLaw::COMPUTE_STRAIN_ENERGY); // Contact between interfaces rNormalRelDisp = rJointWidth - MinimumJointWidth; rJointWidth = MinimumJointWidth; } } // Initally closed joint else { if(rJointWidth < 0.0) { rConstitutiveParameters.Reset(ConstitutiveLaw::COMPUTE_STRAIN_ENERGY); // Contact between interfaces rNormalRelDisp = rJointWidth; rJointWidth = MinimumJointWidth; } else if(rJointWidth < MinimumJointWidth) { rJointWidth = MinimumJointWidth; } } } //---------------------------------------------------------------------------------------- template< > template< class TMatrixType > void UPwSmallStrainInterfaceElement<2,4>::CalculateShapeFunctionsGradients(TMatrixType& rGradNpT,SFGradAuxVariables& rAuxVariables, const Matrix& Jacobian,const BoundedMatrix<double,2,2>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint) { //Quadrilateral_interface_2d_4 rAuxVariables.GlobalCoordinatesGradients[0] = Jacobian(0,0); rAuxVariables.GlobalCoordinatesGradients[1] = Jacobian(1,0); noalias(rAuxVariables.LocalCoordinatesGradients) = prod(RotationMatrix,rAuxVariables.GlobalCoordinatesGradients); rGradNpT(0,0) = DN_De(0,0)/rAuxVariables.LocalCoordinatesGradients[0]; rGradNpT(0,1) = -Ncontainer(GPoint,0)/JointWidth; rGradNpT(1,0) = DN_De(1,0)/rAuxVariables.LocalCoordinatesGradients[0]; rGradNpT(1,1) = -Ncontainer(GPoint,1)/JointWidth; rGradNpT(2,0) = DN_De(2,0)/rAuxVariables.LocalCoordinatesGradients[0]; rGradNpT(2,1) = Ncontainer(GPoint,2)/JointWidth; rGradNpT(3,0) = DN_De(3,0)/rAuxVariables.LocalCoordinatesGradients[0]; rGradNpT(3,1) = Ncontainer(GPoint,3)/JointWidth; } //---------------------------------------------------------------------------------------- template< > template< class TMatrixType > void UPwSmallStrainInterfaceElement<3,6>::CalculateShapeFunctionsGradients(TMatrixType& rGradNpT,SFGradAuxVariables& rAuxVariables, const Matrix& Jacobian,const BoundedMatrix<double,3,3>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint) { //Prism_interface_3d_6 for(unsigned int i = 0; i < 6; i++) { rAuxVariables.ShapeFunctionsNaturalGradientsMatrix(i,0) = DN_De(i,0); rAuxVariables.ShapeFunctionsNaturalGradientsMatrix(i,1) = DN_De(i,1); } rAuxVariables.GlobalCoordinatesGradients[0] = Jacobian(0,0); rAuxVariables.GlobalCoordinatesGradients[1] = Jacobian(1,0); rAuxVariables.GlobalCoordinatesGradients[2] = Jacobian(2,0); noalias(rAuxVariables.LocalCoordinatesGradients) = prod(RotationMatrix,rAuxVariables.GlobalCoordinatesGradients); rAuxVariables.LocalCoordinatesGradientsMatrix(0,0) = rAuxVariables.LocalCoordinatesGradients[0]; rAuxVariables.LocalCoordinatesGradientsMatrix(1,0) = rAuxVariables.LocalCoordinatesGradients[1]; rAuxVariables.GlobalCoordinatesGradients[0] = Jacobian(0,1); rAuxVariables.GlobalCoordinatesGradients[1] = Jacobian(1,1); rAuxVariables.GlobalCoordinatesGradients[2] = Jacobian(2,1); noalias(rAuxVariables.LocalCoordinatesGradients) = prod(RotationMatrix,rAuxVariables.GlobalCoordinatesGradients); rAuxVariables.LocalCoordinatesGradientsMatrix(0,1) = rAuxVariables.LocalCoordinatesGradients[0]; rAuxVariables.LocalCoordinatesGradientsMatrix(1,1) = rAuxVariables.LocalCoordinatesGradients[1]; PoroElementUtilities::InvertMatrix2( rAuxVariables.LocalCoordinatesGradientsInvMatrix, rAuxVariables.LocalCoordinatesGradientsMatrix ); noalias(rAuxVariables.ShapeFunctionsGradientsMatrix) = prod(rAuxVariables.ShapeFunctionsNaturalGradientsMatrix,rAuxVariables.LocalCoordinatesGradientsInvMatrix); rGradNpT(0,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(0,0); rGradNpT(0,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(0,1); rGradNpT(0,2) = -Ncontainer(GPoint,0)/JointWidth; rGradNpT(1,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(1,0); rGradNpT(1,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(1,1); rGradNpT(1,2) = -Ncontainer(GPoint,1)/JointWidth; rGradNpT(2,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(2,0); rGradNpT(2,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(2,1); rGradNpT(2,2) = -Ncontainer(GPoint,2)/JointWidth; rGradNpT(3,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(3,0); rGradNpT(3,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(3,1); rGradNpT(3,2) = Ncontainer(GPoint,3)/JointWidth; rGradNpT(4,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(4,0); rGradNpT(4,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(4,1); rGradNpT(4,2) = Ncontainer(GPoint,4)/JointWidth; rGradNpT(5,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(5,0); rGradNpT(5,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(5,1); rGradNpT(5,2) = Ncontainer(GPoint,5)/JointWidth; } //---------------------------------------------------------------------------------------- template< > template< class TMatrixType > void UPwSmallStrainInterfaceElement<3,8>::CalculateShapeFunctionsGradients(TMatrixType& rGradNpT,SFGradAuxVariables& rAuxVariables, const Matrix& Jacobian,const BoundedMatrix<double,3,3>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint) { //Hexahedral_interface_3d_8 for(unsigned int i = 0; i < 8; i++) { rAuxVariables.ShapeFunctionsNaturalGradientsMatrix(i,0) = DN_De(i,0); rAuxVariables.ShapeFunctionsNaturalGradientsMatrix(i,1) = DN_De(i,1); } rAuxVariables.GlobalCoordinatesGradients[0] = Jacobian(0,0); rAuxVariables.GlobalCoordinatesGradients[1] = Jacobian(1,0); rAuxVariables.GlobalCoordinatesGradients[2] = Jacobian(2,0); noalias(rAuxVariables.LocalCoordinatesGradients) = prod(RotationMatrix,rAuxVariables.GlobalCoordinatesGradients); rAuxVariables.LocalCoordinatesGradientsMatrix(0,0) = rAuxVariables.LocalCoordinatesGradients[0]; rAuxVariables.LocalCoordinatesGradientsMatrix(1,0) = rAuxVariables.LocalCoordinatesGradients[1]; rAuxVariables.GlobalCoordinatesGradients[0] = Jacobian(0,1); rAuxVariables.GlobalCoordinatesGradients[1] = Jacobian(1,1); rAuxVariables.GlobalCoordinatesGradients[2] = Jacobian(2,1); noalias(rAuxVariables.LocalCoordinatesGradients) = prod(RotationMatrix,rAuxVariables.GlobalCoordinatesGradients); rAuxVariables.LocalCoordinatesGradientsMatrix(0,1) = rAuxVariables.LocalCoordinatesGradients[0]; rAuxVariables.LocalCoordinatesGradientsMatrix(1,1) = rAuxVariables.LocalCoordinatesGradients[1]; PoroElementUtilities::InvertMatrix2( rAuxVariables.LocalCoordinatesGradientsInvMatrix, rAuxVariables.LocalCoordinatesGradientsMatrix ); noalias(rAuxVariables.ShapeFunctionsGradientsMatrix) = prod(rAuxVariables.ShapeFunctionsNaturalGradientsMatrix,rAuxVariables.LocalCoordinatesGradientsInvMatrix); rGradNpT(0,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(0,0); rGradNpT(0,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(0,1); rGradNpT(0,2) = -Ncontainer(GPoint,0)/JointWidth; rGradNpT(1,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(1,0); rGradNpT(1,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(1,1); rGradNpT(1,2) = -Ncontainer(GPoint,1)/JointWidth; rGradNpT(2,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(2,0); rGradNpT(2,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(2,1); rGradNpT(2,2) = -Ncontainer(GPoint,2)/JointWidth; rGradNpT(3,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(3,0); rGradNpT(3,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(3,1); rGradNpT(3,2) = -Ncontainer(GPoint,3)/JointWidth; rGradNpT(4,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(4,0); rGradNpT(4,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(4,1); rGradNpT(4,2) = Ncontainer(GPoint,4)/JointWidth; rGradNpT(5,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(5,0); rGradNpT(5,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(5,1); rGradNpT(5,2) = Ncontainer(GPoint,5)/JointWidth; rGradNpT(6,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(6,0); rGradNpT(6,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(6,1); rGradNpT(6,2) = Ncontainer(GPoint,6)/JointWidth; rGradNpT(7,0) = rAuxVariables.ShapeFunctionsGradientsMatrix(7,0); rGradNpT(7,1) = rAuxVariables.ShapeFunctionsGradientsMatrix(7,1); rGradNpT(7,2) = Ncontainer(GPoint,7)/JointWidth; } //---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddLHS(MatrixType& rLeftHandSideMatrix, InterfaceElementVariables& rVariables) { this->CalculateAndAddStiffnessMatrix(rLeftHandSideMatrix,rVariables); this->CalculateAndAddCouplingMatrix(rLeftHandSideMatrix,rVariables); this->CalculateAndAddCompressibilityMatrix(rLeftHandSideMatrix,rVariables); this->CalculateAndAddPermeabilityMatrix(rLeftHandSideMatrix,rVariables); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddStiffnessMatrix(MatrixType& rLeftHandSideMatrix, InterfaceElementVariables& rVariables) { noalias(rVariables.DimMatrix) = prod(trans(rVariables.RotationMatrix), BoundedMatrix<double,TDim,TDim>(prod(rVariables.ConstitutiveMatrix, rVariables.RotationMatrix))); noalias(rVariables.UDimMatrix) = prod(trans(rVariables.Nu),rVariables.DimMatrix); noalias(rVariables.UMatrix) = prod(rVariables.UDimMatrix,rVariables.Nu)*rVariables.IntegrationCoefficient; //Distribute stiffness block matrix into the elemental matrix PoroElementUtilities::AssembleUBlockMatrix(rLeftHandSideMatrix,rVariables.UMatrix); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddCouplingMatrix(MatrixType& rLeftHandSideMatrix, InterfaceElementVariables& rVariables) { noalias(rVariables.UDimMatrix) = prod(trans(rVariables.Nu),trans(rVariables.RotationMatrix)); noalias(rVariables.UVector) = prod(rVariables.UDimMatrix,rVariables.VoigtVector); noalias(rVariables.UPMatrix) = -rVariables.BiotCoefficient*outer_prod(rVariables.UVector,rVariables.Np)*rVariables.IntegrationCoefficient; //Distribute coupling block matrix into the elemental matrix PoroElementUtilities::AssembleUPBlockMatrix(rLeftHandSideMatrix,rVariables.UPMatrix); noalias(rVariables.PUMatrix) = -rVariables.VelocityCoefficient*trans(rVariables.UPMatrix); //Distribute transposed coupling block matrix into the elemental matrix PoroElementUtilities::AssemblePUBlockMatrix(rLeftHandSideMatrix,rVariables.PUMatrix); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddCompressibilityMatrix(MatrixType& rLeftHandSideMatrix, InterfaceElementVariables& rVariables) { noalias(rVariables.PMatrix) = rVariables.DtPressureCoefficient*rVariables.BiotModulusInverse*outer_prod(rVariables.Np,rVariables.Np)*rVariables.JointWidth*rVariables.IntegrationCoefficient; //Distribute compressibility block matrix into the elemental matrix PoroElementUtilities::AssemblePBlockMatrix< BoundedMatrix<double,TNumNodes,TNumNodes> >(rLeftHandSideMatrix,rVariables.PMatrix,TDim,TNumNodes); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddPermeabilityMatrix(MatrixType& rLeftHandSideMatrix, InterfaceElementVariables& rVariables) { noalias(rVariables.PDimMatrix) = prod(rVariables.GradNpT,rVariables.LocalPermeabilityMatrix); noalias(rVariables.PMatrix) = rVariables.DynamicViscosityInverse*prod(rVariables.PDimMatrix,trans(rVariables.GradNpT))*rVariables.JointWidth*rVariables.IntegrationCoefficient; //Distribute permeability block matrix into the elemental matrix PoroElementUtilities::AssemblePBlockMatrix< BoundedMatrix<double,TNumNodes,TNumNodes> >(rLeftHandSideMatrix,rVariables.PMatrix,TDim,TNumNodes); } //---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddRHS(VectorType& rRightHandSideVector, InterfaceElementVariables& rVariables) { this->CalculateAndAddStiffnessForce(rRightHandSideVector, rVariables); this->CalculateAndAddMixBodyForce(rRightHandSideVector, rVariables); this->CalculateAndAddCouplingTerms(rRightHandSideVector, rVariables); this->CalculateAndAddCompressibilityFlow(rRightHandSideVector, rVariables); this->CalculateAndAddPermeabilityFlow(rRightHandSideVector, rVariables); this->CalculateAndAddFluidBodyFlow(rRightHandSideVector, rVariables); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddStiffnessForce(VectorType& rRightHandSideVector, InterfaceElementVariables& rVariables) { noalias(rVariables.UDimMatrix) = prod(trans(rVariables.Nu),trans(rVariables.RotationMatrix)); noalias(rVariables.UVector) = -1.0*prod(rVariables.UDimMatrix,rVariables.StressVector)*rVariables.IntegrationCoefficient; //Distribute stiffness block vector into elemental vector PoroElementUtilities::AssembleUBlockVector(rRightHandSideVector,rVariables.UVector); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddMixBodyForce(VectorType& rRightHandSideVector, InterfaceElementVariables& rVariables) { noalias(rVariables.UVector) = rVariables.Density*prod(trans(rVariables.Nu),rVariables.BodyAcceleration)*rVariables.JointWidth*rVariables.IntegrationCoefficient; //Distribute body force block vector into elemental vector PoroElementUtilities::AssembleUBlockVector(rRightHandSideVector,rVariables.UVector); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddCouplingTerms(VectorType& rRightHandSideVector, InterfaceElementVariables& rVariables) { noalias(rVariables.UDimMatrix) = prod(trans(rVariables.Nu),trans(rVariables.RotationMatrix)); noalias(rVariables.UVector) = prod(rVariables.UDimMatrix,rVariables.VoigtVector); noalias(rVariables.UPMatrix) = rVariables.BiotCoefficient*outer_prod(rVariables.UVector,rVariables.Np)*rVariables.IntegrationCoefficient; noalias(rVariables.UVector) = prod(rVariables.UPMatrix,rVariables.PressureVector); //Distribute coupling block vector 1 into elemental vector PoroElementUtilities::AssembleUBlockVector(rRightHandSideVector,rVariables.UVector); noalias(rVariables.PVector) = -1.0*prod(trans(rVariables.UPMatrix),rVariables.VelocityVector); //Distribute coupling block vector 2 into elemental vector PoroElementUtilities::AssemblePBlockVector< array_1d<double,TNumNodes> >(rRightHandSideVector,rVariables.PVector,TDim,TNumNodes); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddCompressibilityFlow(VectorType& rRightHandSideVector, InterfaceElementVariables& rVariables) { noalias(rVariables.PMatrix) = rVariables.BiotModulusInverse*outer_prod(rVariables.Np,rVariables.Np)*rVariables.JointWidth*rVariables.IntegrationCoefficient; noalias(rVariables.PVector) = -1.0*prod(rVariables.PMatrix,rVariables.DtPressureVector); //Distribute compressibility block vector into elemental vector PoroElementUtilities::AssemblePBlockVector< array_1d<double,TNumNodes> >(rRightHandSideVector,rVariables.PVector,TDim,TNumNodes); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddPermeabilityFlow(VectorType& rRightHandSideVector, InterfaceElementVariables& rVariables) { noalias(rVariables.PDimMatrix) = prod(rVariables.GradNpT,rVariables.LocalPermeabilityMatrix); noalias(rVariables.PMatrix) = rVariables.DynamicViscosityInverse*prod(rVariables.PDimMatrix,trans(rVariables.GradNpT))*rVariables.JointWidth*rVariables.IntegrationCoefficient; noalias(rVariables.PVector) = -1.0*prod(rVariables.PMatrix,rVariables.PressureVector); //Distribute permeability block vector into elemental vector PoroElementUtilities::AssemblePBlockVector< array_1d<double,TNumNodes> >(rRightHandSideVector,rVariables.PVector,TDim,TNumNodes); } //---------------------------------------------------------------------------------------- template< unsigned int TDim, unsigned int TNumNodes > void UPwSmallStrainInterfaceElement<TDim,TNumNodes>::CalculateAndAddFluidBodyFlow(VectorType& rRightHandSideVector, InterfaceElementVariables& rVariables) { noalias(rVariables.PDimMatrix) = prod(rVariables.GradNpT,rVariables.LocalPermeabilityMatrix)*rVariables.JointWidth*rVariables.IntegrationCoefficient; noalias(rVariables.PVector) = rVariables.DynamicViscosityInverse*rVariables.FluidDensity* prod(rVariables.PDimMatrix,rVariables.BodyAcceleration); //Distribute fluid body flow block vector into elemental vector PoroElementUtilities::AssemblePBlockVector< array_1d<double,TNumNodes> >(rRightHandSideVector,rVariables.PVector,TDim,TNumNodes); } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- template< > void UPwSmallStrainInterfaceElement<2,4>::InterpolateOutputDoubles( std::vector<double>& rOutput, const std::vector<double>& GPValues ) { //Interpolation of computed values at Lobatto GP to the standard GiD gauss points rOutput[0] = 0.6220084679281462 * GPValues[0] + 0.16666666666666663 * GPValues[1] + 0.044658198738520435 * GPValues[1] + 0.16666666666666663 * GPValues[0]; rOutput[1] = 0.16666666666666663 * GPValues[0] + 0.6220084679281462 * GPValues[1] + 0.16666666666666663 * GPValues[1] + 0.044658198738520435 * GPValues[0]; rOutput[2]= 0.044658198738520435 * GPValues[0] + 0.16666666666666663 * GPValues[1] + 0.6220084679281462 * GPValues[1] + 0.16666666666666663 * GPValues[0]; rOutput[3] = 0.16666666666666663 * GPValues[0] + 0.044658198738520435 * GPValues[1] + 0.16666666666666663 * GPValues[1] + 0.6220084679281462 * GPValues[0]; } //---------------------------------------------------------------------------------------- template< > void UPwSmallStrainInterfaceElement<3,6>::InterpolateOutputDoubles( std::vector<double>& rOutput, const std::vector<double>& GPValues ) { //Interpolation of computed values at Lobatto GP to the standard GiD gauss points rOutput[0] = 0.5257834230632086 * GPValues[0] + 0.13144585576580214 * GPValues[1] + 0.13144585576580214 * GPValues[2] + 0.14088324360345805 * GPValues[0] + 0.03522081090086451 * GPValues[1] + 0.03522081090086451 * GPValues[2]; rOutput[1] = 0.13144585576580214 * GPValues[0] + 0.5257834230632086 * GPValues[1] + 0.13144585576580214 * GPValues[2] + 0.03522081090086451 * GPValues[0] + 0.14088324360345805 * GPValues[1] + 0.03522081090086451 * GPValues[2]; rOutput[2] = 0.13144585576580214 * GPValues[0] + 0.13144585576580214 * GPValues[1] + 0.5257834230632086 * GPValues[2] + 0.03522081090086451 * GPValues[0] + 0.03522081090086451 * GPValues[1] + 0.14088324360345805 * GPValues[2]; rOutput[3] = 0.14088324360345805 * GPValues[0] + 0.03522081090086451 * GPValues[1] + 0.03522081090086451 * GPValues[2] + 0.5257834230632086 * GPValues[0] + 0.13144585576580214 * GPValues[1] + 0.13144585576580214 * GPValues[2]; rOutput[4] = 0.03522081090086451 * GPValues[0] + 0.14088324360345805 * GPValues[1] + 0.03522081090086451 * GPValues[2] + 0.13144585576580214 * GPValues[0] + 0.5257834230632086 * GPValues[1] + 0.13144585576580214 * GPValues[2]; rOutput[5] = 0.03522081090086451 * GPValues[0] + 0.03522081090086451 * GPValues[1] + 0.14088324360345805 * GPValues[2] + 0.13144585576580214 * GPValues[0] + 0.13144585576580214 * GPValues[1] + 0.5257834230632086 * GPValues[2]; } //---------------------------------------------------------------------------------------- template<> void UPwSmallStrainInterfaceElement<3,8>::InterpolateOutputDoubles( std::vector<double>& rOutput, const std::vector<double>& GPValues ) { //Interpolation of computed values at Lobatto GP to the standard GiD gauss points rOutput[0] = 0.4905626121623441 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.13144585576580212 * GPValues[3] + 0.13144585576580212 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.009437387837655926 * GPValues[2] + 0.035220810900864506 * GPValues[3]; rOutput[1] = 0.13144585576580212 * GPValues[0] + 0.4905626121623441 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.035220810900864506 * GPValues[3] + 0.035220810900864506 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.009437387837655926 * GPValues[3]; rOutput[2] = 0.035220810900864506 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.4905626121623441 * GPValues[2] + 0.13144585576580212 * GPValues[3] + 0.009437387837655926 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.035220810900864506 * GPValues[3]; rOutput[3] = 0.13144585576580212 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.4905626121623441 * GPValues[3] + 0.035220810900864506 * GPValues[0] + 0.009437387837655926 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.13144585576580212 * GPValues[3]; rOutput[4] = 0.13144585576580212 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.009437387837655926 * GPValues[2] + 0.035220810900864506 * GPValues[3] + 0.4905626121623441 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.13144585576580212 * GPValues[3]; rOutput[5] = 0.035220810900864506 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.009437387837655926 * GPValues[3] + 0.13144585576580212 * GPValues[0] + 0.4905626121623441 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.035220810900864506 * GPValues[3]; rOutput[6] = 0.009437387837655926 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.035220810900864506 * GPValues[3] + 0.035220810900864506 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.4905626121623441 * GPValues[2] + 0.13144585576580212 * GPValues[3]; rOutput[7] = 0.035220810900864506 * GPValues[0] + 0.009437387837655926 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.13144585576580212 * GPValues[3] + 0.13144585576580212 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.4905626121623441 * GPValues[3]; } //---------------------------------------------------------------------------------------- template<> template< class TValueType > void UPwSmallStrainInterfaceElement<2,4>::InterpolateOutputValues( std::vector<TValueType>& rOutput, const std::vector<TValueType>& GPValues ) { //Interpolation of computed values at Lobatto GP to the standard GiD gauss points noalias(rOutput[0]) = 0.6220084679281462 * GPValues[0] + 0.16666666666666663 * GPValues[1] + 0.044658198738520435 * GPValues[1] + 0.16666666666666663 * GPValues[0]; noalias(rOutput[1]) = 0.16666666666666663 * GPValues[0] + 0.6220084679281462 * GPValues[1] + 0.16666666666666663 * GPValues[1] + 0.044658198738520435 * GPValues[0]; noalias(rOutput[2])= 0.044658198738520435 * GPValues[0] + 0.16666666666666663 * GPValues[1] + 0.6220084679281462 * GPValues[1] + 0.16666666666666663 * GPValues[0]; noalias(rOutput[3]) = 0.16666666666666663 * GPValues[0] + 0.044658198738520435 * GPValues[1] + 0.16666666666666663 * GPValues[1] + 0.6220084679281462 * GPValues[0]; } //---------------------------------------------------------------------------------------- template<> template< class TValueType > void UPwSmallStrainInterfaceElement<3,6>::InterpolateOutputValues( std::vector<TValueType>& rOutput, const std::vector<TValueType>& GPValues ) { //Interpolation of computed values at Lobatto GP to the standard GiD gauss points noalias(rOutput[0]) = 0.5257834230632086 * GPValues[0] + 0.13144585576580214 * GPValues[1] + 0.13144585576580214 * GPValues[2] + 0.14088324360345805 * GPValues[0] + 0.03522081090086451 * GPValues[1] + 0.03522081090086451 * GPValues[2]; noalias(rOutput[1]) = 0.13144585576580214 * GPValues[0] + 0.5257834230632086 * GPValues[1] + 0.13144585576580214 * GPValues[2] + 0.03522081090086451 * GPValues[0] + 0.14088324360345805 * GPValues[1] + 0.03522081090086451 * GPValues[2]; noalias(rOutput[2]) = 0.13144585576580214 * GPValues[0] + 0.13144585576580214 * GPValues[1] + 0.5257834230632086 * GPValues[2] + 0.03522081090086451 * GPValues[0] + 0.03522081090086451 * GPValues[1] + 0.14088324360345805 * GPValues[2]; noalias(rOutput[3]) = 0.14088324360345805 * GPValues[0] + 0.03522081090086451 * GPValues[1] + 0.03522081090086451 * GPValues[2] + 0.5257834230632086 * GPValues[0] + 0.13144585576580214 * GPValues[1] + 0.13144585576580214 * GPValues[2]; noalias(rOutput[4]) = 0.03522081090086451 * GPValues[0] + 0.14088324360345805 * GPValues[1] + 0.03522081090086451 * GPValues[2] + 0.13144585576580214 * GPValues[0] + 0.5257834230632086 * GPValues[1] + 0.13144585576580214 * GPValues[2]; noalias(rOutput[5]) = 0.03522081090086451 * GPValues[0] + 0.03522081090086451 * GPValues[1] + 0.14088324360345805 * GPValues[2] + 0.13144585576580214 * GPValues[0] + 0.13144585576580214 * GPValues[1] + 0.5257834230632086 * GPValues[2]; } //---------------------------------------------------------------------------------------- template<> template< class TValueType > void UPwSmallStrainInterfaceElement<3,8>::InterpolateOutputValues( std::vector<TValueType>& rOutput, const std::vector<TValueType>& GPValues ) { //Interpolation of computed values at Lobatto GP to the standard GiD gauss points noalias(rOutput[0]) = 0.4905626121623441 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.13144585576580212 * GPValues[3] + 0.13144585576580212 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.009437387837655926 * GPValues[2] + 0.035220810900864506 * GPValues[3]; noalias(rOutput[1]) = 0.13144585576580212 * GPValues[0] + 0.4905626121623441 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.035220810900864506 * GPValues[3] + 0.035220810900864506 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.009437387837655926 * GPValues[3]; noalias(rOutput[2]) = 0.035220810900864506 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.4905626121623441 * GPValues[2] + 0.13144585576580212 * GPValues[3] + 0.009437387837655926 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.035220810900864506 * GPValues[3]; noalias(rOutput[3]) = 0.13144585576580212 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.4905626121623441 * GPValues[3] + 0.035220810900864506 * GPValues[0] + 0.009437387837655926 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.13144585576580212 * GPValues[3]; noalias(rOutput[4]) = 0.13144585576580212 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.009437387837655926 * GPValues[2] + 0.035220810900864506 * GPValues[3] + 0.4905626121623441 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.13144585576580212 * GPValues[3]; noalias(rOutput[5]) = 0.035220810900864506 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.009437387837655926 * GPValues[3] + 0.13144585576580212 * GPValues[0] + 0.4905626121623441 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.035220810900864506 * GPValues[3]; noalias(rOutput[6]) = 0.009437387837655926 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.035220810900864506 * GPValues[3] + 0.035220810900864506 * GPValues[0] + 0.13144585576580212 * GPValues[1] + 0.4905626121623441 * GPValues[2] + 0.13144585576580212 * GPValues[3]; noalias(rOutput[7]) = 0.035220810900864506 * GPValues[0] + 0.009437387837655926 * GPValues[1] + 0.035220810900864506 * GPValues[2] + 0.13144585576580212 * GPValues[3] + 0.13144585576580212 * GPValues[0] + 0.035220810900864506 * GPValues[1] + 0.13144585576580212 * GPValues[2] + 0.4905626121623441 * GPValues[3]; } //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- template void UPwSmallStrainInterfaceElement<2,4>::CalculateShapeFunctionsGradients< BoundedMatrix<double,4,2> > ( BoundedMatrix<double,4,2>& rGradNpT, SFGradAuxVariables& rAuxVariables, const Matrix& Jacobian,const BoundedMatrix<double,2,2>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint ); template void UPwSmallStrainInterfaceElement<2,4>::CalculateShapeFunctionsGradients< Matrix > ( Matrix& rGradNpT, SFGradAuxVariables& rAuxVariables,const Matrix& Jacobian, const BoundedMatrix<double,2,2>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint ); template void UPwSmallStrainInterfaceElement<3,6>::CalculateShapeFunctionsGradients< BoundedMatrix<double,6,3> > ( BoundedMatrix<double,6,3>& rGradNpT, SFGradAuxVariables& rAuxVariables, const Matrix& Jacobian,const BoundedMatrix<double,3,3>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint ); template void UPwSmallStrainInterfaceElement<3,6>::CalculateShapeFunctionsGradients< Matrix > ( Matrix& rGradNpT, SFGradAuxVariables& rAuxVariables,const Matrix& Jacobian, const BoundedMatrix<double,3,3>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint ); template void UPwSmallStrainInterfaceElement<3,8>::CalculateShapeFunctionsGradients< BoundedMatrix<double,8,3> > ( BoundedMatrix<double,8,3>& rGradNpT, SFGradAuxVariables& rAuxVariables, const Matrix& Jacobian,const BoundedMatrix<double,3,3>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint ); template void UPwSmallStrainInterfaceElement<3,8>::CalculateShapeFunctionsGradients< Matrix > ( Matrix& rGradNpT, SFGradAuxVariables& rAuxVariables,const Matrix& Jacobian, const BoundedMatrix<double,3,3>& RotationMatrix, const Matrix& DN_De,const Matrix& Ncontainer, const double& JointWidth,const unsigned int& GPoint ); //---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- template class UPwSmallStrainInterfaceElement<2,4>; template class UPwSmallStrainInterfaceElement<3,6>; template class UPwSmallStrainInterfaceElement<3,8>; } // Namespace Kratos
[ "ipouplana@cimne.upc.edu" ]
ipouplana@cimne.upc.edu
2216a3331cea3c8efd61338053e42c49fcbda91b
e661c0b2bee8f600517c5803dc362a945172aa7e
/src/config.cpp
a15ed4cd8c922da73fb635e8c88af3cdff85db97
[]
no_license
ivanildolucena/opendevice-lib-arduino
52d72b9657e5bee3b4bfc36840a6d1ccc2351778
53f02f42264cd0383091d18d22219b702ba09923
refs/heads/master
2020-03-25T01:18:54.747711
2018-07-08T21:52:35
2018-07-08T21:52:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,444
cpp
#include "config.h" namespace od { ConfigClass Config = { CONFIG_VERSION, // The default values "OpenDevice", "cloud.opendevice.io", "*", // APP_ID { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, // MAC { 0, 0, 0, 0 }, // IP -1, // ResetPIN false, // debugMode true, // keepAlive DEBUG_SERIAL, // debugTarget CONNECTION_MODE_SERVER, // ConnectionMode 0 // devicesLength // Device ... }; /** * Load configuration from storage (EEPROM). * Check if exist, if not, use default values **/ void ConfigClass::load(){ if(check()){ EEPROM.get(CONFIG_START, Config); } else{ memset(this->devices, 0, MAX_DEVICE); // initialize defaults as 0 // save(); // init and save defaults } } /** * Check if exist a valid configuration (memory layout) in EEPROM */ bool ConfigClass::check(){ return (EEPROM.read(CONFIG_START + 0) == CONFIG_VERSION[0] && EEPROM.read(CONFIG_START + 1) == CONFIG_VERSION[1] && EEPROM.read(CONFIG_START + 2) == CONFIG_VERSION[2]); } /** Save current configuration to storage */ void ConfigClass::save(){ EEPROM.put(CONFIG_START, Config); #if defined(ESP8266) EEPROM.commit(); #endif } /** * Clear saved setings */ void ConfigClass::clear(){ for (int i = CONFIG_START ; i < CONFIG_START + sizeof(Config) ; i++) { EEPROM.write(i, 0); } #if defined(ESP8266) EEPROM.commit(); #endif } }
[ "ricardo.jl.rufino@gmail.com" ]
ricardo.jl.rufino@gmail.com
c96dfb405011f73d1f175c2320155f90ac70a598
8056ed674aa7ac516e2e698235788f602b617b36
/scripts/7.cpp
34fe5585ce650c1b6b000ea5380c5b01b40585ed
[]
no_license
Swas99/ScalableComputingAssignments
aacc94a78eaa91fc310a086d0f065781a4eeb554
9396dd444b204b7dfc0753fd9415221aa404f64b
refs/heads/master
2020-03-30T09:39:52.701759
2018-12-01T16:33:42
2018-12-01T16:33:42
151,086,424
0
0
null
null
null
null
UTF-8
C++
false
false
2,520
cpp
#include <iostream> #include <fstream> #include <string> #include <algorithm> using namespace std; /* Driver program to test above function */ int main(void) { string data = ""; //Numbers // for(int i = 0; i<=99999; i++) // { // string x = to_string(i); // while(x.length() < 5) // x = "0" + x; // data += x + "\n"; // } long count = 0; string chars[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; for(char c1 = 'a'; c1<='z'; c1++) { string x1 = chars[c1-'a']; for(int c2 = 'a';c2<='z'; c2++) { string x2 = x1 + chars[c2-'a']; for(int c3 = 'a'; c3<='z'; c3++) { string x3 = x2 + chars[c3-'a']; for(int c4 = 'a'; c4<='z'; c4++) { string x4 = x3 + chars[c4-'a']; for(int c5 = 'a'; c5<='z'; c5++) { string x5 = x4 + chars[c5-'a']; for(int c6 = 'a'; c6<='z'; c6++) { string x6 = x5 + chars[c6-'a']; for(int c7 = 'a'; c7<='z'; c7++) { string x7 = x6 + chars[c7-'a']; for(int c8 = 'a'; c8<='z'; c8++) { string x8 = x7 + chars[c8-'a']; data += x8 + "\n"; count++; if(count%5000000 == 0) { string outputfile = "C:\\Users\\Swastik\\Desktop\\MastersDegree_CS\\Semester_1\\ScalableComputing\\Stefen\\Assignments\\all_lcase_8d.lst"; ofstream outfile; outfile.open(outputfile, std::ios_base::app); outfile << data; outfile.close(); data = ""; cout<<x8<<" "; float progress = count/((double)27*27*27*27*27*27*27*27.0); cout<<"progress = "<<progress<<endl; } } } } } } } } } if(data.length()>0) { string outputfile = "C:\\Users\\Swastik\\Desktop\\MastersDegree_CS\\Semester_1\\ScalableComputing\\Stefen\\Assignments\\all_lcase_8d.lst"; ofstream outfile; outfile.open(outputfile, std::ios_base::app); outfile << data; outfile.close(); } // string name = "C:\\Users\\Swastik\\Desktop\\MastersDegree_CS\\Semester_1\\ScalableComputing\\Stefen\\Assignments\\john180j1w\\run\\password.lst"; // string name = "C:\\Users\\Swastik\\Desktop\\MastersDegree_CS\\Semester_1\\ScalableComputing\\Stefen\\Assignments\\all_lcase_8d"; // std::ofstream out(name); // out << data; // out.close(); return 0; }
[ "swas.rishi@gmail.com" ]
swas.rishi@gmail.com
a3978cb8a460f69728dcc6e4df245d91dcb504d5
6157455a8627e82d77254289050bd04162d552ba
/PsiFcp/psifcp/call.cp
c45f27ab6cc89e959cb51a511efbbfcc94b30b49
[]
no_license
shapirolab/Logix
f769e6ab3fec12dcf5e4b59a3d172ed667291ead
6960cb3ff7dfef9885383b62b7996ae1d7e42538
refs/heads/master
2022-11-11T07:52:49.814029
2020-06-30T07:17:08
2020-06-30T07:17:08
275,871,063
1
0
null
null
null
null
UTF-8
C++
false
false
20,869
cp
/* Precompiler for Pi Calculus procedures - call management. Bill Silverman, December 1999. Last update by $Author: bill $ $Date: 2000/09/26 08:35:29 $ Currently locked by $Locker: $ $Revision: 1.3 $ $Source: /home/qiana/Repository/PsiFcp/psifcp/call.cp,v $ Copyright (C) 1999, Weizmann Institute of Science - Rehovot, ISRAEL */ -language(compound). -export([make_local_call/10, make_remote_call/8, prime_local_channels/3, sum_procedures/5]). make_local_call(ProcessDefinition, Locals, Primes, Body1, Body2, In, NextIn, Errors, NextErrors, CallDefinition) :- Body1 = true : ProcessDefinition = _, Locals = _, Primes = _, In = NextIn, Errors = NextErrors, Body2 = true, CallDefinition = []; Body1 =?= self : Body1' = `Name | extract_id(ProcessDefinition, Name, _Arity), self; arity(Body1) > 1, arg(1, Body1, self) | extract_id(ProcessDefinition, Name, _Arity), copy_goal_args(Body1, `Name?, Body1'), self; arity(Body1) > 1, arg(1, Body1, `Functor), string(Functor) | extract_id(ProcessDefinition, Name, _Arity), extract_lhs_parts(ProcessDefinition, ChannelNames, _OuterLHS, _InnerLHS), extract_arguments_or_substitutes(Name, Body1, Arguments, Substitutes, Errors, Errors'?), verify_call_channels(Name, Body1, ChannelNames, Locals, Errors', Errors''?), prime_local_channels(Primes, Arguments?, Arguments'), substituted_local_channels(Primes, Substitutes?, Substitutes'), lookup_call_functor, complete_local_call; Body1 = `Functor : Locals = _, Primes = _, Arguments = [], Substitutes = [] | extract_id(ProcessDefinition, Name, _Arity), lookup_call_functor, complete_local_call; Body1 = _ + _ : CallDefinition = {Name, 0, [/*fake_channels*/], {{fake_lhs}, {fake_lhs}}, sum(fake_rhs, fake_communication_rhs)}| make_summed_call(ProcessDefinition, Locals, Primes, Body1, Body2, Name, In, NextIn, Errors, NextErrors); otherwise, tuple(Body1), arity(Body1, 1), arg(1, Body1, Goals) : ProcessDefinition = _, Locals = _, Primes = _, Body2 = Goals, In = [logix_variables(LogixVars?) | NextIn], Errors = NextErrors, CallDefinition = [] | utilities#find_logix_variables(Body1, LogixVars, []); otherwise : Locals = _, Primes = _, Body2 = true, In = NextIn, Errors = [(Name? - invalid_local_call(Body1)) | NextErrors], CallDefinition = [] | extract_id(ProcessDefinition, Name, _Arity). substituted_local_channels(Primes, Substitutes, Primed) :- Primes ? {Channel, ChannelP} | prime_substitutes(Channel, ChannelP, Substitutes, Substitutes'), self; Primes =?= [] : Primed = Substitutes. prime_substitutes(Channel, ChannelP, SubsIn, SubsOut) :- SubsIn ? (Substitute = Sub), Sub =?= Channel : SubsOut ! (Substitute = ChannelP) | self; SubsIn ? (Substitute = Sub), Sub =\= Channel : SubsOut ! (Substitute = Sub) | self; SubsIn =?= [] : Channel = _, ChannelP = _, SubsOut = []. verify_call_channels(Name, Goal, ChannelNames, Locals, Errors, NextErrors) + (Index = 2) :- arg(Index, Goal, (_ = String)), string =\= "_", Index++ | utilities#verify_channel(Name, String, ChannelNames, Locals, _OkChannel, Errors, Errors'?), self; arg(Index, Goal, String), string =\= "_", Index++ | utilities#verify_channel(Name, String, ChannelNames, Locals, _OkChannel, Errors, Errors'?), self; Index =< arity(Goal), otherwise, Index++ | self; Index > arity(Goal) : Name = _, ChannelNames = _, Locals = _, Errors = NextErrors. complete_local_call(CallType, CallDefinition, Arguments, Substitutes, Name, Body1, Body2, Errors, NextErrors) :- CallType =?= none : CallDefinition = _, Arguments = _, Substitutes = _, Name = _, Body2 = true, Errors = [Name - unknown_local_process(Body1) | NextErrors]; CallType =\= none, list(Arguments) : Substitutes = _, Name = _, Body1 = _ | extract_id(CallDefinition, _Name, Arity), extract_lhs_parts(CallDefinition, _ChannelNames, Atom, _InnerLHS), substitute_arguments+(Index = 1, Substitutes = Substitutes'), call_with_substitutes; CallType =?= outer, Arguments =?= [] : Errors = NextErrors, Name = _, Body1 = _ | extract_lhs_parts(CallDefinition, _ChannelNames, Atom, _InnerLHS), call_with_substitutes; CallType =?= inner, Arguments =?= [] : Name = _, Body1 = _, Errors = NextErrors | extract_lhs_parts(CallDefinition, _ChannelNames, _OuterLHS, Atom), call_with_substitutes. substitute_arguments(Index, Atom, Arity, Arguments, Substitutes, Name, Body1, Errors, NextErrors) :- Index++ =< Arity, arg(Index', Atom, S), Arguments ? C, S =\= `C : Substitutes ! {S, C} | self; Index++ =< Arity, arg(Index', Atom, S), Arguments ? C, S =?= `C | self; Index > Arity, Arguments = [] : Atom = _, Name = _, Body1 = _, Substitutes = [], Errors = NextErrors; Index > Arity, Arguments =\= [] : Atom = _, Substitutes = [], Errors = [Name - too_many_arguments(Body1) | NextErrors]; Index =< Arity, Arguments =?= [] : Atom = _, Substitutes = [], Errors = [Name - not_enough_arguments(Body1) | NextErrors]. call_with_substitutes(Atom, Substitutes, Body2) :- Substitutes =?= [], arg(1, Atom, Name) : Body2 = Name; Substitutes =\= [], arg(1, Atom, Name) : Body2 = Name + Added | add_substitutes. add_substitutes(Substitutes, Added) :- Substitutes =?= [{S, C}] : Added = (S = `C); Substitutes ? {S, C}, Substitutes' =\= [] : Added = (S = `C, Added') | self. lookup_call_functor(Name, ProcessDefinition, Functor, CallType, CallDefinition, In, NextIn) :- Functor =?= Name : CallType = inner, CallDefinition = ProcessDefinition, In = NextIn; otherwise : Name = _, ProcessDefinition = _, In = [lookup_functor(Functor, CallType, CallDefinition) | NextIn]. extract_arguments_or_substitutes(Name, Tuple, Arguments, Substitutes, Errors, NextErrors) + (Index = 2, Type = _) :- arg(Index, Tuple, Channel), string(Channel), Channel =\= "_", Index++ : Type = channel, Arguments ! Channel | self; arg(Index, Tuple, `Channel), string(Channel), Channel =\= "_", Index++ : Type = channel, Arguments ! Channel | self; arg(Index, Tuple, S = C), string(S), S =\= "_", string(C), Index++ : Type = substitute, Substitutes ! {`S, C} | self; arg(Index, Tuple, S = `C), string(S), S =\= "_", string(C), Index++ : Type = substitute, Substitutes ! {`S, C} | self; arg(Index, Tuple, `S = C), string(S), S =\= "_", string(C), Index++ : Type = substitute, Substitutes ! {`S, C} | self; arg(Index, Tuple, `S = `C), string(S), S =\= "_", string(C), Index++ : Type = substitute, Substitutes ! {`S, C} | self; arity(Tuple) < Index : Name = _, Type = _, Arguments = [], Substitutes = [], Errors = NextErrors; otherwise, Index =:= 2 : Type = _, Arguments = [], Substitutes = [], Errors = [Name - first_argument_invalid(Tuple) | NextErrors]; otherwise, Type = channel, arg(Index, Tuple, Arg), Index++ : Arguments ! "_", Errors ! (Name - invalid_channel_argument(Arg, Tuple)) | self; otherwise, Type = substitute, arg(Index, Tuple, Arg), Index++ : Errors ! (Name - invalid_substitute(Arg, Tuple)) | self. make_remote_call(Name, ChannelNames, Locals, Primes, PiCall, CompoundCall, Errors, NextErrors) :- extract_arguments_or_substitutes(Name, PiCall, Arguments, _Subs, Errors, Errors'?, 2, channel), verify_call_channels(Name, PiCall, ChannelNames, Locals, Errors', Errors''?), prime_local_channels(Primes, Arguments?, Arguments'), complete_remote_call(Name, PiCall, Arguments'?, CompoundCall, Errors'', NextErrors). complete_remote_call(Name, PiCall, Arguments, CompoundCall, Errors, NextErrors) :- arg(1, PiCall, `Functor), string(Functor), Arguments =\= [] : Name = _, Errors = NextErrors | utilities#make_lhs_tuple(Functor, Arguments, CompoundCall); arg(1, PiCall, `Functor), string(Functor), Arguments =?= [] : Name = _, CompoundCall = Functor, Errors = NextErrors; otherwise : Arguments = _, CompoundCall = [], Errors = [Name - invalid_remote_call(PiCall) | NextErrors]. prime_local_channels(Primes, Arguments, Primed) :- Primes ? {Channel, ChannelP} | prime_arguments(Channel, ChannelP, Arguments, Arguments'), self; Primes =?= [] : Primed = Arguments. prime_arguments(Channel, ChannelP, ArgsIn, ArgsOut) :- ArgsIn ? Arg, Arg =?= Channel : ArgsOut ! ChannelP | self; ArgsIn ? Arg, Arg =\= Channel : ArgsOut ! Arg | self; ArgsIn =?= [] : Channel = _, ChannelP = _, ArgsOut = []. /***************** Summation Process server predicates. **********************/ make_summed_call(ProcessDefinition, Locals, Primes, Sum, Call, Name, In, NextIn, Errors, NextErrors) :- true : In ! call_sum(Name?, Procedures?, Call) | utils#binary_sort_merge(Names?, NameList), concatenated_sum_name(NameList?, Name), summed_call(ProcessDefinition, Locals, Primes, Sum, Names, Procedures, In', NextIn, Errors, NextErrors). concatenated_sum_name(NameList, Name) + (NLH = NLT?, NLT) :- NameList ? N : ascii("+", Plus), NLT' ! Plus | string_to_dlist(N, NLT, NLT'), self; NameList =?= [N], string_to_dlist(N, NH, []) : NLT = NH | list_to_string(NLH, Name); NameList = [] : NLH = _, NLT = _, Name = false. summed_call(ProcessDefinition, Locals, Primes, Sum, Names, Procedures, In, NextIn, Errors, NextErrors) :- Sum = `Name + Sum', string(Name) : Names ! Name, Procedures ! {Call?, CallDefinition?} | make_local_call(ProcessDefinition, Locals, Primes, `Name, Call, In, In', Errors, Errors'?, CallDefinition), self; Sum = Sum' + `Name, string(Name) : Names ! Name, Procedures ! {Call?, CallDefinition?} | make_local_call(ProcessDefinition, Locals, Primes, `Name, Call, In, In', Errors, Errors'?, CallDefinition), self; Sum = `Name, string(Name) : Names = [Name], Procedures = [{Call?, CallDefinition?}] | make_local_call(ProcessDefinition, Locals, Primes, `Name, Call, In, NextIn, Errors, NextErrors, CallDefinition); Sum = Tuple + Sum', arg(1,Tuple,`Name), string(Name) : Names ! Name, Procedures ! {Call?, CallDefinition?} | make_local_call(ProcessDefinition, Locals, Primes, Tuple, Call, In, In', Errors, Errors'?, CallDefinition), self; Sum = Sum' + Tuple, arg(1,Tuple,`Name), string(Name) : Names ! Name, Procedures ! {Call?, CallDefinition?} | make_local_call(ProcessDefinition, Locals, Primes, Tuple, Call, In, In', Errors, Errors'?, CallDefinition), self; arg(1,Sum,`Name), string(Name) : Names = [Name], Procedures = [{Call?, CallDefinition?}] | make_local_call(ProcessDefinition, Locals, Primes, Sum, Call, In, NextIn, Errors, NextErrors, CallDefinition); otherwise : Locals = _, Primes = _, Errors = [Name - illegal_process_summation(Sum) | NextErrors], Names = [], Procedures = false, In = NextIn | extract_id(ProcessDefinition, Name, _Arity). /****************** Summation Empty server predicates. **********************/ sum_procedures(Summed, Entries, Optimize, NextOptimize, Errors) + (Cumulated = []) :- Summed ? Name(Procedures, Call) | cumulate, extract_procedure_parts(Procedures, Names, Calls, Channels, CodeTuples), optimize_sum(Name, Names, Optimize, Optimize'?), cumulated; Summed = [] : Cumulated = _, Entries = [], Optimize = NextOptimize, Errors = []. extract_procedure_parts(Procedures, Names, Calls, Channels, CodeTuples) :- Procedures ? {Call, ProcedureDefinition}, ProcedureDefinition =?= {Name, _Arity, ChannelNames, _LHS, CodeTuple} : Names ! Name, Calls ! Call, Channels ! ChannelNames, CodeTuples ! CodeTuple | self; Procedures ? _Ignore, otherwise | self; Procedures = [] : Names = [], Calls = [], Channels = [], CodeTuples = []. cumulate(Name, Cumulated, Reply) :- Cumulated = [Name | _] : Reply = found; Cumulated ? Other, Other =\= Name | self; Cumulated = [] : Name = _, Reply = new. cumulated(Summed, Entries, Optimize, NextOptimize, Errors, Cumulated, Name, Calls, Channels, CodeTuples, Call, Reply) :- Reply =?= found : Channels = _, CodeTuples = _ | make_sum_call(Name, Calls, Call, Errors, Errors'?), sum_procedures; Reply =?= new : Cumulated' = [Name | Cumulated] | make_summed_rhs(Name, Calls, CodeTuples, 1, Prepares, Code, Results, FinalMode, Errors, Errors'?), utilities#sort_out_duplicates(Channels?, SumChannels, _Reply), make_named_list(Prepares?, _Requests, Name-duplicate_channel_in_sum, Errors', Errors''?), make_named_guard(Prepares?, Ask, Tell), /* Eliminate duplicate stream names. */ utils#binary_sort_merge(Results, Results'), make_named_predicates(';', Code?, RHS), utilities#make_lhs_tuple(Name, SumChannels, Tuple), make_sum_procedure(FinalMode?, Name, (Ask? : Tell?), RHS?, Tuple?, Results'?, Entries, Entries'?), make_sum_call(Name, Calls, Call, Errors'', Errors'''?), sum_procedures. optimize_sum(Name, Names, Optimize, NextOptimize) :- Names =?= [] : Name = _, Optimize = NextOptimize; Names =\= [] : Optimize ! procedure(Notes?, 0, {Name?}, _Value) | % screen#display(sum(Name, Value)), add_calls_and_channels. add_calls_and_channels(Names, Optimize, NextOptimize, Notes) :- Names ? Name : Optimize ! procedure([], 0, {Name}, {Calls, Channels}), Notes ! call(Calls), Notes' ! variables(Channels) | % screen#display(add(Name, Calls, Channels)), self; Names = [] : Optimize = NextOptimize, Notes = []. make_sum_call(Name, Calls, Call, Errors, NextErrors) + (NamedArgs = AddArgs?, AddArgs) :- Calls ? String, string(String) | self; Calls ? (_Name + Arguments) | extract_named_arguments(Arguments, AddArgs, AddArgs'?), self; Calls = [] : AddArgs = [] | make_named_list(NamedArgs, ArgList, Name-duplicate_channel_substitution, Errors, NextErrors), complete_sum_call. complete_sum_call(Name, ArgList, Call) :- ArgList =?= [] : Call = Name; ArgList =\= [] : Call = Name+(Substitutes) | make_named_predicates(',', ArgList, Substitutes). make_summed_rhs(Name, Calls, CodeTuples, Index, Prepares, Code, Results, FinalMode, Errors, NextErrors) + (Mode = none, Sender = _) :- CodeTuples ? ProcessMode(SendRHS, ProcessRHS), Calls ? _, SendRHS =?= (Idents : Tells | _Relay) | utilities#untuple_predicate_list(",", Idents, Asks), utilities#untuple_predicate_list(",", Tells, Tells'), utilities#untuple_predicate_list(";", ProcessRHS, ClauseList), add_sends_and_receives(Asks?, Tells'?, ClauseList?, Name, Index, Index', Prepares, Prepares'?, Code, Code'?, Results, Results'?), utilities#update_process_mode(Mode, ProcessMode, Mode'), self; CodeTuples ? ProcessMode([], []), Calls ? Call : Errors ! (Name-invalid_mode_in_summation(Call? - ProcessMode)) | utilities#update_process_mode(Mode, ProcessMode, Mode'), self; CodeTuples = [] : Calls = _, Index = _, Prepares = [], Code = [], Results = [], FinalMode = Mode, Errors = NextErrors | final_process_mode(Name, Mode, Sender). final_process_mode(Name, Mode, Sender) :- Mode =?= mixed : Name = _, Sender = `psifcp(sendid); Mode =?= send : Sender = Name; /* receive or none */ otherwise : Name = _, Mode = _, Sender = []. add_sends_and_receives(Asks, Tells, ClauseList, Name, Index, NewIndex, Prepares, NextPrepares, Code, NextCode, Results, NextResults) :- Asks ? Identify, Identify =?= vector(`ChannelName), Tells ? Request, Request =?= request(Type,_,_,_), ClauseList ? Communication, Communication =?= (`psifcp(chosen) = _Index : Result = Tuple | Body), Index++ : Prepares ! {Type(ChannelName), Identify, Request'?}, Results ! Result, Code ! Index((`psifcp(chosen) = Index : Result = Tuple | Body)) | reindex_request(Request, ChannelName, Index, Request'), self; Asks ? Identify, Identify =?= vector(`ChannelName), Tells ? Request, Request =?= request(Type,_,_,_), ClauseList ? Communication, Communication =?= (`psifcp(chosen) = _Index, Result = Tuple | Body), Index++ : Prepares ! {Type(ChannelName), Identify, Request'?}, Results ! Result, Code ! Index((`psifcp(chosen) = Index, Result = Tuple | Body)) | reindex_request(Request, ChannelName, Index, Request'), self; ClauseList = [] : Name = _, Asks = _, Tells = _, NewIndex = Index, NextPrepares = Prepares, Code = NextCode, Results = NextResults. reindex_request(Request, ChannelName, Index, NewRequest) :- Request = request(Type, ChannelName, Multiplier, _Index) : NewRequest = request(Type, ChannelName, Multiplier, Index). /* Compare to make_rhs2 */ make_sum_procedure(Mode, Name, Requests, RHS, Tuple, Results, Entries, NextEntries) :- Mode =?= communicate : Entries = [Mode(Atom?, (Requests | SendChoices?), (ChoiceAtom? :- RHS)) | NextEntries] | utilities#tuple_to_atom(Tuple, Atom), make_choice_name(Name, ".comm", SendChoices), make_choice_atom(Atom, SendChoices?, [`psifcp(chosen) | Results], ChoiceAtom); /* conflict */ otherwise : Name = _, Requests = _, Results = _, Entries = [Mode(Atom?, RHS, []) | NextEntries] | utilities#tuple_to_atom(Tuple, Atom). make_choice_name(Prefix, Suffix, Name) :- string_to_dlist(Prefix, PL, PS), string_to_dlist(Suffix, SL, []) : PS = SL | list_to_string(PL, Name). make_choice_atom(InnerLHS, Name, ChoiceVars, ChoiceAtom) :- utils#tuple_to_dlist(InnerLHS, [_ | ChannelVariables], ChoiceVars), utils#list_to_tuple([Name | ChannelVariables], ChoiceAtom). extract_id(Definition, Name, Arity) :- true : Definition = {Name, Arity, _ChannelNames, _LHS, _CodeTuple}. extract_lhs_parts(Definition, ChannelNames, OuterLHS, InnerLHS) :- true : Definition = {_Name, _Arity, ChannelNames, LHS, _CodeTuple}, LHS = {OuterLHS, InnerLHS}. /************************** Summation Utilities ******************************/ make_named_guard(Requests, Ask, Tell) :- Requests ? _Name(Idents, Request), Requests' =\= [] : Ask = (Idents, Ask'?), Tell = (Request, Tell'?) | self; Requests = [_Name(Idents, Request)] : Ask = Idents, Tell = Request; Requests = [] : Ask = true, Tell = true. make_named_list(NamedClauses, Clauses, Diagnostic, Errors, NextErrors) :- utilities#sort_out_duplicates([NamedClauses], Clauses, Reply), diagnose_duplicate. diagnose_duplicate(Reply, Diagnostic, Errors, NextErrors) :- Reply ? Duplicate, Diagnostic = Name - String : Errors ! (Name - String(Duplicate)) | self; Reply =?= [] : Diagnostic = _, Errors = NextErrors; otherwise : Reply = _, Errors = [Diagnostic | NextErrors]. make_named_predicates(Operator, List, PredicateList) :- List =?= [] : Operator = _, PredicateList = true; List ? Name(Predicate1, Predicate2, Predicate3) : PredicateList = {Operator, Predicate1, {Operator, Predicate2, PredicateList'}}, List'' = [Name(Predicate3) | List'] | self; List ? Name(Predicate1, Predicate2) : PredicateList = {Operator, Predicate1, PredicateList'}, List'' = [Name(Predicate2) | List'] | self; List ? _Name(Predicate), List' =\= [] : PredicateList = {Operator, Predicate, PredicateList'?} | self; List =?= [_Name(Predicate)] : Operator = _, PredicateList = Predicate. extract_named_arguments(Arguments, Args, NextArgs) :- Arguments = (Substitution, Arguments'), Substitution =?= (`Name = _Value) : Args ! Name(Substitution) | self; Arguments =\= (_ , _), Arguments =?= (`Name = _Value) : Args = [Name(Arguments) | NextArgs].
[ "bill" ]
bill
a559d9e4a24314a81e6063ac74e7c695f9822a5e
954ca6ef34be759f4485e07233cee296ea9ce077
/password/dictionary.h
fee46333629cdd01a6b8bcdd12d01bb3215946b9
[]
no_license
Jackychen8/class_c-
2ddd734129e7fd7ee154cd4365c24e3989da0dc3
545b1ed4fa7625474469bc58aecaea419213349d
refs/heads/master
2021-04-15T17:36:42.095469
2018-03-21T07:40:27
2018-03-21T07:40:27
126,138,842
0
0
null
null
null
null
UTF-8
C++
false
false
1,584
h
// // dictionary.h // password-mac // // Created by Jacky Chen on 2/15/15. // Copyright (c) 2015 Sanjay Madhav. All rights reserved. // #pragma once #include "unordered_map" #include <string> #include "map" #include "list" #include <iostream> #include "timer.h" #include "sha1.h" #include <fstream> #include "bruteForce.h" #include <iterator> struct encodingVars{ std::string plainPassword; unsigned char hash[20]; char hex_str[41]; }; class dictionary{ public: // Name: fillDictionary // Function: fill a map (encoDictionary) with passwords from a file to check common passwords // Input: the name of the dictionary file // Output: none void fillDictionary(const std::string& dicName); // Name: compareDiction // Function: Basically does everything. // This runs through all of the passwords in encoDictionary. Then it calls a function from bruteForce // to run through all 4 digit permutations of lower case letters and numbers. // Then it creates the pass_solved.txt file // Input: the name of the file containing all the passwords you want to crack // Output: none void compareDiction(const std::string& passName); // Name: delete dictionary // Function: runs through all the dictionary's .seconds (encodingVars*) // and deletes them // Input: none // Output: none void deleteDict(); private: // Stores the "most often used" passwords Dictionary that is matched with passwords std::unordered_map<std::string, encodingVars*> encoDictionary; };
[ "chenjacky9@gmail.com" ]
chenjacky9@gmail.com
8618643f34e716759986100b4706aa5b69d72bfa
40759a3d38a71023670f6510a0b03c1c84c471f7
/codecs.h
03de389a7671e4c34f16fb74015a50ec06d7a5ec
[ "Apache-2.0" ]
permissive
phaistos-networks/Trinity
f78cb880fe6d24dc331659b034f97c4e19be3836
a745a0c13719ca9d041e1dfcfeb81e6bf85a996f
refs/heads/master
2021-01-19T04:34:31.721194
2019-11-08T18:12:31
2019-11-08T18:12:31
84,192,219
250
23
null
null
null
null
UTF-8
C++
false
false
17,598
h
#pragma once #include "common.h" #include "docidupdates.h" #include "docset_iterators_base.h" #include "docwordspace.h" #include "runtime.h" // Use of Codecs::Google results in a somewhat large index, while the access time is similar(maybe somewhat slower) to Lucene's codec namespace Trinity { struct candidate_document; struct queryexec_ctx; // Information about a term's posting list and number of documents it matches. // We track the number of documents because it may be useful(and it is) to some codecs, and also // is extremely useful during execution where we re-order the query nodes based on evaluation cost which // is directly related to the a term's posting list size based on the number of documents it matches. struct term_index_ctx final { uint32_t documents; // For each each term, the inverted index contains a `posting list`, where // each posting contains the occurrences information (e.g frequences and positions) // for documents that contain the trerm. This is the chunk in the index that // holds the posting list. // This is codec specific though -- for some codecs, this could mean something else // e.g for a memory-resident index source/segment, you could use inexChunk to refer to some in-memory data range32_t indexChunk; term_index_ctx(const uint32_t d, const range32_t c) : documents{d}, indexChunk{c} { } term_index_ctx(const term_index_ctx &o) { documents = o.documents; indexChunk = o.indexChunk; } term_index_ctx(term_index_ctx &&o) { documents = o.documents; indexChunk = o.indexChunk; } term_index_ctx &operator=(const term_index_ctx &o) { documents = o.documents; indexChunk = o.indexChunk; return *this; } term_index_ctx &operator=(const term_index_ctx &&o) { documents = o.documents; indexChunk = o.indexChunk; return *this; } term_index_ctx() = default; }; namespace Codecs { struct Encoder; struct AccessProxy; // Represents a new indexer session // All indexer sessions have an `indexOut` that holds the inverted index(posting lists for each distinct term) // but other codecs may e.g open/track more files or buffers depending on their needs. // // The base path makes sense for disk based storage, but some codecs may only operate on in-memory // data so it may not be used in those designs. struct IndexSession { enum class Capabilities : uint8_t { // append_index_chunk() is implemented AppendIndexChunk = 1, Merge = 1 << 1 }; const uint8_t caps; IOBuffer indexOut; // Whenever you flush indexOut to disk, say, every few MBs or GBs, // you need to adjust indexOutFlushed, because the various codecs implementations need to compute some offset in the index // // Obviously, you are not required to flush, but it's an option. // Doing this would also likely improve performance, for instead of expanding indexOut's underlying allocated memory and thus // likely incurring a memmcpy() cost, by keeping the buffer small and flushing it periodically to a backing file, this is avoided, memory // allocation remainins low/constant and no need for memcpy() is required (if no reallocations are required) // // TODO: consider an alternative idea, where instead of flushing to disk, we 'll just steal indexOut memory (via IOBuffer::release() ) and // length, and track that in a vector, and flush indexOut, and in the end, we 'll just compile a new indexOut from those chunks. // This would provide those benefits: // - no need to allocate large chunks of memory to hold the whold index; will allocate smaller chunks (and maybe even in the end // serialize all them to disk, free their memory, and allocate memory for the index and load it from disk) // - no need to resize the IOBuffer, i.e no need for memcpy() the data to new buffers on reallocation uint32_t indexOutFlushed; char basePath[PATH_MAX]; // The segment name should be the generation // e.g for path Trinity/Indices/Wikipedia/Segments/100 // the generation is extracted as 100, but, again, this is codec specific IndexSession(const char *bp, const uint8_t capabilities = 0) : caps{capabilities}, indexOutFlushed{0} { strcpy(basePath, bp); } virtual ~IndexSession() { } // Utility method // Demonstrates how you should update indexOutFlushed void flush_index(int fd); // Handy utility function // see SegmentIndexSession::commit() void persist_terms(std::vector<std::pair<str8_t, term_index_ctx>> &); // Subclasses should e.g open files, allocate memory etc virtual void begin() = 0; // Subclasses should undo begin() ops. e.g close files and release resources virtual void end() = 0; // This may be stored in a segment directory in order to determine // which codec to use to access it virtual strwlen8_t codec_identifier() = 0; // Constructs a new encoder // Handy utility function virtual Encoder *new_encoder() = 0; // This is used during merge // By providing the access to an index and a term's tctx, we should append to the current indexOut // for most codecs, that's just a matter of copying the region in tctx.indexChunk into indexOut, but // some other codecs may need to access other files in the src // (e.g lucene codec uses an extra files for positions/attributes) // // must hold that (src->codec_identifier() == this->codec_identifier()) // // XXX: If you want to filter a chunk's documents though, don't use this method. // See MergeCandidatesCollection::merge() // // If you have a fancy codec that you don't expect to use for merging other segments // (e.g some fancy in-memory wrapper that is // really only used for queries as an IndexSource), then you can just implement this and merge() as no-ops. // // see MergeCandidatesCollection::merge() impl. // // UPDATE: this is now optional. If your codec implements it, make sure you set (Capabilities::AppendIndexChunk) // in capabilities flags passed to Codecs::IndexSession::IndexSession(). Both Google and Lucene's do so. // The default impl. does nothing/aborts virtual range32_t append_index_chunk(const AccessProxy *src, const term_index_ctx srcTCTX) { std::abort(); return {}; } // If we have multiple postng lists for the same term(i.e merging 2+ segments // and same term exists in 2+ of them) // where we can't just use append_index_chunk() but instead we need to merge them, // and to do that, we we need to use this codec-specific merge function // that will do this for us. Use append_index_chunk() otherwise. // // You are expected to have encoder->begin_term() before invoking this method, // and to invoke encoder->end_term() after the method has returned // // The input pairs hold an AccessProxy for the data and a range in the the index of that data, and // the encoder the target codec encoder // // See MergeCandidatesCollection::merge() impl. struct merge_participant final { AccessProxy * ap; term_index_ctx tctx; masked_documents_registry *maskedDocsReg; }; // UPDATE: now optional; if you override and implement it, make sure you set Capabilities::Merge in the constructo virtual void merge(merge_participant *participants, const uint16_t participantsCnt, Encoder *const encoder) { } }; // Encoder interface for encoding a single term's posting list struct Encoder { IndexSession *const sess; // You should have s->begin() before you use encode any postlists for that session Encoder(IndexSession *s) : sess{s} { } virtual ~Encoder() { } virtual void begin_term() = 0; virtual void begin_document(const isrc_docid_t documentID) = 0; // If you want to register a hit for a special token (e.g site:foo.com) where position makes no sense, // you should use position 0(or a very high position, but 0 is preferrable) // You will likely only need to set payload for special terms (e.g site:foo.com). // Payload can be upto 8 byte sin size(sizeof(uint64_t)). You should try to keep that as low as possible. virtual void new_hit(const uint32_t position, const range_base<const uint8_t *, const uint8_t> payload) = 0; virtual void end_document() = 0; virtual void end_term(term_index_ctx *) = 0; }; // This is how postings lists are accessed and hits are materialized. // It is created by a Codecs::Decoder, and it should in practice hold a reference // to the decoder and delegate work to it, but that should depend on your codec's impl. // // In the past, Decoder's implemented next() and advance()/seek(), but it turned to be a bad idea // because it was somewhat challenging to support multiple terms in the query, where you want to access // the same underlying decoder state, but traverse them independently. struct Decoder; struct PostingsListIterator : public Trinity::DocsSetIterators::Iterator { // decoder that created this iterator Decoder *const dec; // For current document tokenpos_t freq; PostingsListIterator(Decoder *const d) : Iterator{Trinity::DocsSetIterators::Type::PostingsListIterator}, dec{d} { } virtual ~PostingsListIterator() { } // Materializes hits for the _current_ document in the postings list // You must also dwspace->set(termID, pos) for positions != 0 // // XXX: if you materialize, it's likely that curDocument.freq will be reset to 0 // so you should not materialize if have already done so. virtual void materialize_hits(DocWordsSpace *dwspace, term_hit *out) = 0; inline auto decoder() noexcept { return dec; } inline const Decoder *decoder() const noexcept { return dec; } #ifdef RDP_NEED_TOTAL_MATCHES inline uint32_t total_matches() override final { return freq; } #endif }; // Decoder interface for decoding a single term's posting list. // If a decoder makes use of skiplist data, they are expected to be serialized in the index // and the decoder is responsible for deserializing and using them from there, although this is specific to the codec // // Decoder is responsible for maintaining term-specific segment state, and for creating new Posting Lists iterators, which in turn // should just contain iterator-specific state and logic working in conjuction with the Decoder that created/provided it. struct Decoder { // Term specific data for the term of this decode // see e.g DocsSetIterators::cost() term_index_ctx indexTermCtx; // use set_exec() to set those exec_term_id_t execCtxTermID{0}; queryexec_ctx *rctx{nullptr}; constexpr auto exec_ctx_termid() const noexcept { return execCtxTermID; } // Initialise the decoding state for accessing the postings list // // Not going to rely on a constructor for initialization because // we want to force subclasses to define a method with this signature virtual void init(const term_index_ctx &, AccessProxy *) = 0; // This is how you are going to access the postings list virtual PostingsListIterator *new_iterator() = 0; Decoder() { } virtual ~Decoder() { } void set_exec(exec_term_id_t tid, queryexec_ctx *const r) { execCtxTermID = tid; rctx = r; } }; // Responsible for initializing segment/codec specific state and for generating(factory) decoders for terms // All AccessProxy instances have a pointer to the actual index(posts lists) in common struct AccessProxy { const char *basePath; // Index of the posting lists for all distinct terms // This is typically a pointer to memory mapped index file, or a memory-resident anything, or // something other specific to the codec const uint8_t *const indexPtr; // Utility function: returns an initialised new decoder for a term's posting list // Some codecs(e.g lucene's) may need to access the filesystem and/or other codec specific state // AccessProxy faciliates that (this is effectively a pointer to self) // // XXX: Make sure you Decoder::init() before you return from the method // see e.g Google::AccessProxy::new_decoder() // // See Codecs::Decoder for execCtxTermID virtual Decoder *new_decoder(const term_index_ctx &tctx) = 0; AccessProxy(const char *bp, const uint8_t *index_ptr) : basePath{bp}, indexPtr{index_ptr} { // Subclasses should open files, etc } // See IndexSession::codec_identifier() virtual strwlen8_t codec_identifier() = 0; virtual ~AccessProxy() { } }; } // namespace Codecs } // namespace Trinity
[ "mpapadakis@phaistosnetworks.gr" ]
mpapadakis@phaistosnetworks.gr
f88a1d42c710516e15ae546bd9f6ff8e78437d8f
24a7f138d7be0c4d566c085bd8abaf7b9f1b9b26
/image_morphing/main.cpp
55300cb4ba6f34328fff322aaceffffdb5e2a983
[]
no_license
AbhinavJindl/image_processing
53a4023f41525963c0d50cf1fc207c473a63a5ca
1bbc6fb139bfd21883f3c070129c3af611e4ba1b
refs/heads/master
2021-01-24T01:39:50.384143
2018-02-25T08:10:52
2018-02-25T08:10:52
122,817,168
0
0
null
null
null
null
UTF-8
C++
false
false
13,410
cpp
/* ----------------------readme--------------- --------how to compile-------------- $g++ a2_abhinav_2016csb1026.cpp -o output `pkg-config --cflags --libs opencv` $./output -------------references-------------- 1)Learn Opencv for triangulation syntax and understanding the concept of how to use triangulation 2)Material provided by sir for concept understanding 3)github for input example --------assumptions--------------- 1)input and output images and text file should be present in same folder. 2)text file should have y coordinate followed by x coordinate. 3)Size of image can change for part 1 but not for part 2. */ #include <iostream> #include <opencv2/core/core.hpp> #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include <cmath> #include <fstream> # define pi 3.141592653589793238462643383279502884 using namespace std; using namespace cv; float area(float t0,float t1,float t2,float t3,float t4,float t5){ float area=(abs((t0-t2)*(t5-t1)-(t0-t4)*(t3-t1)))/2; return area; } void part1(string image1,int noOfImages){ Mat image = imread(image1,0); Mat T(2,3,CV_32F,0.0); //T.at<float>(0,1)=1; //T.at<float>(1,0)=-1; //T.at<float>(0,0)=2; //T.at<float>(1,1)=2; cout<<"Enter the transf matrix:"; for(int i=0;i<2;i++){ for(int j=0;j<3;j++){ cin>>T.at<float>(i,j); } } vector<Point2f>initialcoord,tempinitialcoord; initialcoord.push_back(Point2f(0,0)); initialcoord.push_back(Point2f(image.rows,0)); initialcoord.push_back(Point2f(0,image.cols)); initialcoord.push_back(Point2f(image.rows,image.cols)); tempinitialcoord.push_back(Point2f(0,0)); tempinitialcoord.push_back(Point2f(image.rows,0)); tempinitialcoord.push_back(Point2f(0,image.cols)); float finalcoord[4][2]={0.0}; for(int i=0;i<4;i++){ //cout<<initialcoord[i]<<endl; finalcoord[i][0]=initialcoord[i].x*T.at<float>(0,0)+initialcoord[i].y*T.at<float>(0,1)+T.at<float>(0,2); finalcoord[i][1]=initialcoord[i].x*T.at<float>(1,0)+initialcoord[i].y*T.at<float>(1,1)+T.at<float>(0,2); } for(int n=0;n<=noOfImages;n++){ Mat input=image.clone(); float alpha=(float)n/noOfImages; vector<Point2f> cornerpoints; cornerpoints.push_back(Point2f((1-alpha)*0+(alpha)*finalcoord[0][0],(1-alpha)*0+(alpha)*finalcoord[0][1])); cornerpoints.push_back(Point2f((1-alpha)*initialcoord[1].x+(alpha)*finalcoord[1][0],(1-alpha)*initialcoord[1].y+(alpha)*finalcoord[1][1])); cornerpoints.push_back(Point2f((1-alpha)*initialcoord[2].x+(alpha)*finalcoord[2][0],(1-alpha)*initialcoord[2].y+(alpha)*finalcoord[2][1])); cornerpoints.push_back(Point2f((1-alpha)*initialcoord[3].x+(alpha)*finalcoord[3][0],(1-alpha)*initialcoord[3].y+(alpha)*finalcoord[3][1])); int maxR=0; int minR=image.rows; int maxC=0; int minC=image.cols; for(int i=0;i<cornerpoints.size();i++){ //cout<<cornerpoints[i]<<endl; if(cornerpoints[i].x<minR){ minR=cornerpoints[i].x; } if(cornerpoints[i].y<minC){ minC=cornerpoints[i].y; } if(cornerpoints[i].x>maxR){ maxR=cornerpoints[i].x; } if(cornerpoints[i].y>maxC){ maxC=cornerpoints[i].y; } } cornerpoints.pop_back(); Mat transf=getAffineTransform(cornerpoints,tempinitialcoord); int colsize=maxC-minC; int rowsize=maxR-minR; Mat out(rowsize,colsize,CV_8U,0.0); for(int i=0;i<rowsize;i++){ for(int j=0;j<colsize;j++){ int x=transf.at<double>(0,0)*(i+minR)+transf.at<double>(0,1)*(j+minC)+transf.at<double>(0,2); int y=transf.at<double>(1,0)*(i+minR)+transf.at<double>(1,1)*(j+minC)+transf.at<double>(1,2); if(x>=0&&y>=0&&x<input.rows&&y<input.cols) out.at<uchar>(i,j)=input.at<uchar>(x,y); } } ostringstream str1; str1 << n; string n1 = str1.str(); string a="./images/morph"+n1+".jpg"; imwrite(a,out); } } void part2(string image1,string image2,string file1,string file2,int noOfImages){ Mat oriimg = imread(image1,0); Mat finalimg = imread(image2,0); Size size = oriimg.size(); cout<<size.height<<" "<<size.width<<endl; Rect rect(0, 0, size.height,size.width); vector<Point2f> points[2]; char* File1=new char(file1.size()); for(int i=0;i<file1.size();i++){ File1[i]=file1[i]; } char* File2=new char(file2.size()); for(int i=0;i<file2.size();i++){ File2[i]=file2[i]; } cout<<File1<<" "<<File2<<endl; int x, y,fx,fy; ifstream ift(File2); //ift.open (File2); if (ift.is_open()) { // cout << "File successfully open"; } else { cout<<"2\n"; cout << "Error opening file"; return; } while(ift >>fy>>fx) { //cout<<"csd\n"; points[1].push_back(Point2f(fx,fy)); } ifstream ifs(File1); if (ifs.is_open()) { //cout << "File successfully open"; } else { cout<<"!\n"; cout << "Error opening file"; return ; } while(ifs >>y>>x) { points[0].push_back(Point2f(x,y)); //points[1].push_back(Point2f(fx,fy)); } Mat finalout[noOfImages+1]; //loop for no of frames //cout<<"2\n"; for(int n=0;n<=noOfImages;n++){ Mat out(oriimg.rows,oriimg.cols,CV_8U,0.0); Subdiv2D subdiv(rect); vector<Point2f> intpoints; //intermediate points for triangulation for(int i=0;i<points[0].size();i++){ intpoints.push_back(Point2f(points[0][i].x*(1-(float)((float)n/noOfImages))+points[1][i].x*(float)((float)n/noOfImages),points[0][i].y*(1-((float)n/noOfImages))+points[1][i].y*((float)n/noOfImages))); //cout<<intpoints[i]<<endl; } for( vector<Point2f>::iterator it = intpoints.begin(); it != intpoints.end(); it++) { subdiv.insert(*it); } Mat img; img=oriimg.clone(); //making 3 triangle lists for initial ,final and intermediate images and one temporary vector<Vec6f> temptriangleList,triangleList,initialtriangleList,finaltriangleList; subdiv.getTriangleList(temptriangleList); Vec6f ini,f,t; vector<Point> pt(3); for(size_t it=0;it<temptriangleList.size();it++){ int temp=0; for(int i=0;i<6;i++){ if(temptriangleList[it][i]>=0 && temptriangleList[it][i]<img.rows && i%2==0){ temp++; } else if(temptriangleList[it][i]>=0 && temptriangleList[it][i]<img.cols && i%2==1){ temp++; } } if(temp==6){ triangleList.push_back(temptriangleList[it]); } } for( size_t it = 0; it < triangleList.size(); it++ ){ t = triangleList[it]; pt[0] = Point(cvRound(t[0]), cvRound(t[1])); pt[1] = Point(cvRound(t[2]), cvRound(t[3])); pt[2] = Point(cvRound(t[4]), cvRound(t[5])); int minI=min(cvRound(t[0]),cvRound(t[2])); minI=min(minI,cvRound(t[4])); int minJ=min(cvRound(t[1]),cvRound(t[3])); minJ=min(minJ,cvRound(t[5])); int maxI=max(cvRound(t[0]),cvRound(t[2])); maxI=max(maxI,cvRound(t[4])); int maxJ=max(cvRound(t[1]),cvRound(t[3])); maxJ=max(maxJ,cvRound(t[5])); //cout<<pt[0]<<" cds "<<pt[1]<<" Csd "<<pt[2]<<endl; /*if (rect.contains(pt[0]) && rect.contains(pt[1]) && rect.contains(pt[2])){ line(img, pt[0], pt[1], delaunay_color, 1); line(img, pt[1], pt[2], delaunay_color, 1); line(img, pt[2], pt[0], delaunay_color, 1); }*/ //getting initial anf final points with respect to triangle for( int i=0;i<intpoints.size();i++) { if(intpoints[i].x==t[0]&&intpoints[i].y==t[1]){ ini[0]=points[0][i].x; ini[1]=points[0][i].y; f[0]=points[1][i].x; f[1]=points[1][i].y; break; } } for( int i=0;i<intpoints.size();i++) { if(intpoints[i].x==t[2]&&intpoints[i].y==t[3]){ ini[2]=points[0][i].x; ini[3]=points[0][i].y; f[2]=points[1][i].x; f[3]=points[1][i].y; break; } } for( int i=0;i<intpoints.size();i++) { if(intpoints[i].x==t[4]&&intpoints[i].y==t[5]){ ini[4]=points[0][i].x; ini[5]=points[0][i].y; f[4]=points[1][i].x; f[5]=points[1][i].y; break; } } initialtriangleList.push_back(ini); finaltriangleList.push_back(f); //vector created to give as input to get affine vector<Point2f> intpointstransf; vector<Point2f> inipointstransf; vector<Point2f> finalpointstransf; intpointstransf.push_back(Point2f(cvRound(triangleList[it][0]),cvRound(triangleList[it][1]))); intpointstransf.push_back(Point2f(cvRound(triangleList[it][2]),cvRound(triangleList[it][3]))); intpointstransf.push_back(Point2f(cvRound(triangleList[it][4]),cvRound(triangleList[it][5]))); inipointstransf.push_back(Point2f(cvRound(initialtriangleList[it][0]),cvRound(initialtriangleList[it][1]))); inipointstransf.push_back(Point2f(cvRound(initialtriangleList[it][2]),cvRound(initialtriangleList[it][3]))); inipointstransf.push_back(Point2f(cvRound(initialtriangleList[it][4]),cvRound(initialtriangleList[it][5]))); finalpointstransf.push_back(Point2f(cvRound(finaltriangleList[it][0]),cvRound(finaltriangleList[it][1]))); finalpointstransf.push_back(Point2f(cvRound(finaltriangleList[it][2]),cvRound(finaltriangleList[it][3]))); finalpointstransf.push_back(Point2f(cvRound(finaltriangleList[it][4]),cvRound(finaltriangleList[it][5]))); //get transform matrices Mat t1=getAffineTransform(intpointstransf,inipointstransf); Mat t2=getAffineTransform(intpointstransf,finalpointstransf); int count=0; for(int r=minI-1;r<maxI+1;r++){ for(int c=minJ-1;c<maxJ+1;c++){ float area1=area(t[0],t[1],t[2],t[3],t[4],t[5]); float area2=area(t[0],t[1],t[2],t[3],(float)r,(float)c); float area3=area(t[0],t[1],t[4],t[5],(float)r,(float)c); float area4=area(t[4],t[5],t[2],t[3],(float)r,(float)c); if(abs(area1-(area2+area3+area4))<0.01){ int inir=t1.at<double>(0,0)*(double)r+t1.at<double>(0,1)*(double)c+t1.at<double>(0,2); int inic=t1.at<double>(1,0)*(double)r+t1.at<double>(1,1)*(double)c+t1.at<double>(1,2); int finr=t2.at<double>(0,0)*(double)r+t2.at<double>(0,1)*(double)c+t2.at<double>(0,2); int finc=t2.at<double>(1,0)*(double)r+t2.at<double>(1,1)*(double)c+t2.at<double>(1,2); out.at<uchar>(r,c)=(uchar)(oriimg.at<uchar>(inir,inic)*(1-((float)n/noOfImages))+finalimg.at<uchar>(finr,finc)*(((float)n/noOfImages))); } } } } //imshow("morph",out); //waitKey(0); finalout[n]=out.clone(); } bool f=true; for(int n=0;n<=noOfImages;n++){ ostringstream str1; str1 << n; string n1 = str1.str(); string a="./images2/morph"+n1+".jpg"; imwrite(a,finalout[n]); imshow("morph",finalout[n]); waitKey(100); } } int main(int argc, char** argv){ string imagetitle= "Morphing"; Scalar delaunay_color(255,255,255), points_color(0, 0, 255); bool part; int noOfImages; string image1,image2; cout<<"Enter the part you want to execute(0 or 1):"; cin>>part; if(part==0){ cout<<"Enter image name:"; cin>>image1; cout<<"Enter no of frames"; cin>>noOfImages; noOfImages--; part1(image1,noOfImages); } else if(part==1){ cout<<"Enter first image name:"; cin>>image1; cout<<"Enter second image name:"; cin>>image2; string file1,file2; cout<<"Enter file names in resp. order(files should have tie points as y x):"; cin>>file1>>file2; cout<<"Enter no of frames"; cin>>noOfImages; noOfImages--; //image1="image1.jpg"; //image2="image2.jpg"; //file1="1.txt"; //file2="2.txt"; part2(image1,image2,file1,file2,noOfImages); } return 0; }
[ "2016csb1026@iitrpr.ac.in" ]
2016csb1026@iitrpr.ac.in
e82a97a14f3a716e2bd846f415efe4a0b73acd75
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/Implementation/599.cpp
f7d2c84f2b8a4a4180a80132a3ee2357f2c0447a
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
304
cpp
#include<iostream> #include<string> using namespace std; int main() { int a,b; while(cin>>a>>b) { int arr[55]={}; for(int i=0;i<a;i++) cin>>arr[i]; int c=0; for(int i=0;i<a;i++) if(arr[i]>=arr[b-1] && arr[i])c++; cout<<c<<endl; } return 0; }
[ "mukeshchugani10@gmail.com" ]
mukeshchugani10@gmail.com
e5d4827835473782179f7514132755f788ce7b3d
f83ef53177180ebfeb5a3e230aa29794f52ce1fc
/ACE/ACE_wrappers/TAO/orbsvcs/tests/Notify/Structured_Multi_Filter/Notify_Push_Consumer.cpp
6d3074d443b5c97925d39c306699151f607e892e
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-sun-iiop" ]
permissive
msrLi/portingSources
fe7528b3fd08eed4a1b41383c88ee5c09c2294ef
57d561730ab27804a3172b33807f2bffbc9e52ae
refs/heads/master
2021-07-08T01:22:29.604203
2019-07-10T13:07:06
2019-07-10T13:07:06
196,183,165
2
1
Apache-2.0
2020-10-13T14:30:53
2019-07-10T10:16:46
null
UTF-8
C++
false
false
4,917
cpp
#include "Notify_Push_Consumer.h" #include "Notify_Test_Client.h" #include "tao/debug.h" Notify_Push_Consumer::Notify_Push_Consumer (const char* name, int sent, NS_FilterType consumerFilter, NS_FilterType supplierFilter, Notify_Test_Client& client) : name_ (name) , sent_(sent) , received_(0) , expected_(sent) , client_(client) , consumerFilter_(consumerFilter) , supplierFilter_(supplierFilter) { // Calculate the expected number. ACE_ASSERT(sent % 9 == 0); // The supplier side filters combine group != 0 and type != 0, while the // consumer side combines group != 1 and type != 1 if (consumerFilter == AndOp && supplierFilter == AndOp) { // group != 0 && type != 0 && group != 1 && type != 1 expected_ = sent_ / 9; } else if (consumerFilter == AndOp && supplierFilter == OrOp) { // group != 0 || type != 0 && group != 1 && type != 1 expected_ = sent_ * 3 / 9; } else if (consumerFilter == AndOp && supplierFilter == None) { // group != 1 && type != 1 expected_ = sent_ * 4 / 9; } else if (consumerFilter == OrOp && supplierFilter == AndOp) { // group != 0 && type != 0 && group != 1 || type != 1 expected_ = sent_ * 3 / 9; } else if (consumerFilter == OrOp && supplierFilter == OrOp) { // group != 0 || type != 0 && group != 1 || type != 1 expected_ = sent_ * 7 / 9; } else if (consumerFilter == OrOp && supplierFilter == None) { // group != 1 || type != 1 expected_ = sent_ * 8 / 9; } else if (consumerFilter == None && supplierFilter == OrOp) { // group != 0 && type != 0 expected_ = sent_ * 8 / 9; } else if (consumerFilter == None && supplierFilter == AndOp) { // group != 0 && type != 0 expected_ = sent_ * 4 / 9; } else if (consumerFilter == None && supplierFilter == None) { expected_ = sent_; } else { bool unknown_filter_combination = false; ACE_ASSERT(unknown_filter_combination); ACE_UNUSED_ARG(unknown_filter_combination); } this->client_.consumer_start (this); } void Notify_Push_Consumer::_connect (CosNotifyChannelAdmin::ConsumerAdmin_ptr consumer_admin, CosNotifyChannelAdmin::EventChannel_ptr notify_channel) { CosNotifyComm::StructuredPushConsumer_var objref = this->_this (); CosNotifyChannelAdmin::ProxySupplier_var proxysupplier = consumer_admin->obtain_notification_push_supplier ( CosNotifyChannelAdmin::STRUCTURED_EVENT, proxy_id_); if (consumerFilter_ != None) { CosNotifyFilter::FilterFactory_var ffact = notify_channel->default_filter_factory (); CosNotifyFilter::Filter_var filter = ffact->create_filter ("ETCL"); ACE_ASSERT(! CORBA::is_nil (filter.in ())); CosNotifyFilter::ConstraintExpSeq constraint_list (1); constraint_list.length (1); constraint_list[0].event_types.length (0); constraint_list[0].constraint_expr = CORBA::string_dup ("$group != 1"); filter->add_constraints (constraint_list); proxysupplier->add_filter (filter.in ()); } this->proxy_ = CosNotifyChannelAdmin::StructuredProxyPushSupplier::_narrow ( proxysupplier.in ()); this->proxy_->connect_structured_push_consumer (objref.in ()); // give ownership to POA this->_remove_ref (); } static void validate_expression(bool expr, const char* msg) { if (! expr) { ACE_ERROR((LM_ERROR, "Error: %s\n", msg)); } } #define validate(expr) validate_expression(expr, #expr) void Notify_Push_Consumer::push_structured_event ( const CosNotification::StructuredEvent& event) { ACE_DEBUG((LM_DEBUG, "-")); received_++; CORBA::ULong id = 0; CORBA::ULong group = 0; CORBA::ULong type = 0; ACE_ASSERT(event.filterable_data.length() == 3); ACE_ASSERT(ACE_OS::strcmp(event.filterable_data[0].name.in(), "id") == 0); ACE_ASSERT(ACE_OS::strcmp(event.filterable_data[1].name.in(), "group") == 0); ACE_ASSERT(ACE_OS::strcmp(event.filterable_data[2].name.in(), "type") == 0); event.filterable_data[0].value >>= id; event.filterable_data[1].value >>= group; event.filterable_data[2].value >>= type; if (consumerFilter_ == OrOp) validate(type != 1 || group != 1); else if (consumerFilter_ == AndOp) validate(type != 1 && group != 1); if (supplierFilter_ == OrOp) validate(type != 0 || group != 0); else if (supplierFilter_ == OrOp) validate(type != 0 && group != 0); if (received_ > expected_) { ACE_ERROR((LM_ERROR, "\nError: Expected %d, Received %d\n", expected_, received_)); this->client_.consumer_done (this); return; } if (received_ >= expected_) { ACE_DEBUG((LM_DEBUG, "\nConsumer received %d events.\n", received_)); this->client_.consumer_done (this); return; } }
[ "lihuibin705@163.com" ]
lihuibin705@163.com
d08ef0a1c968f76601442a58be0ffc3dc26325a0
b71b8bd385c207dffda39d96c7bee5f2ccce946c
/testcases/CWE762_Mismatched_Memory_Management_Routines/s04/CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_18.cpp
1ec437c2b13d46e40788a967ae8575999b6306b1
[]
no_license
Sporknugget/Juliet_prep
e9bda84a30bdc7938bafe338b4ab2e361449eda5
97d8922244d3d79b62496ede4636199837e8b971
refs/heads/master
2023-05-05T14:41:30.243718
2021-05-25T16:18:13
2021-05-25T16:18:13
369,334,230
0
0
null
null
null
null
UTF-8
C++
false
false
2,975
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_18.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-18.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 18 Control flow: goto statements * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_18 { #ifndef OMITBAD void bad() { long * data; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (long *)realloc(data, 100*sizeof(long)); if (data == NULL) {exit(-1);} /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G() - use badsource and goodsink by reversing the blocks on the second goto statement */ static void goodB2G() { long * data; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (long *)realloc(data, 100*sizeof(long)); if (data == NULL) {exit(-1);} /* FIX: Deallocate the memory using free() */ free(data); } /* goodG2B() - use goodsource and badsink by reversing the blocks on the first goto statement */ static void goodG2B() { long * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using new */ data = new long; /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } void good() { goodB2G(); goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_18; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "jaredzap@rams.colostate.edu" ]
jaredzap@rams.colostate.edu
26d14821362d3975fde293101277269d27400a8a
68b877fc50cdadd08e657a0d06773ccd7210a138
/1364A.cpp
0a230f86165fbebd682aecfb5f0e71a01af6d49b
[]
no_license
Priyanshu2802/Competitive-Programming
b58ffa0d25cd80e137af0a5661360afd346fe831
24c77990308439ff805750a97e2f010c47777c1c
refs/heads/master
2023-06-12T10:10:40.876731
2021-07-05T15:10:10
2021-07-05T15:10:10
377,078,294
0
0
null
null
null
null
UTF-8
C++
false
false
1,713
cpp
//LordNeo #include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef long double ld; #define endl "\n"; typedef vector<ll> vll; typedef vector<pair<ll, ll>> vp; typedef map<ll, ll> ml; typedef unordered_map<ll, ll> uml; #define pb push_back #define ff first #define ss second const ll inf = INT_MAX; ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b); } ll lcm(ll a, ll b) { return (a / gcd(a, b)) * b; } int factorial(ll n) { return (n == 1 || n == 0) ? 1 : n * factorial(n - 1); } ll sm(ll n) { ll ans = n * (n + 1) / 2; return ans; } bool isprime(ll x) { for (ll i = 2; i * i <= x; i++) { if (x % i == 0) return 0; } return 1; } bool perfectSquare(ld x) { ld sr = sqrt(x); return ((sr - floor(sr)) == 0); } /*___________________*workplace*_______________________*/ void solve() { ll n, x, i, sum = 0, a, l = -1, r = l; cin >> n >> x; bool flag = 0; for (i = 0; i < n; i++) { cin >> a; sum += a; if (a % x) { if (l == -1) { l = i; r = l; } else r = i; } } if (sum % x) { cout << n << endl; } else if (l != -1) { ll t = min(l + 1, n - r); cout << n - t << endl; } else cout << "-1" << endl; } int main() { /*#ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif*/ ios_base::sync_with_stdio(0); cin.tie(0); ll test_case; cin >> test_case; while (test_case--) { solve(); } return 0; }
[ "priyanshuranjan2001@gmail.com" ]
priyanshuranjan2001@gmail.com
91b8bf8a671dd8ad4f04c5f090c67aec4c5e25aa
8672ce66faffeb411c52f2acc929196db15d17bb
/PhysicsCarGame-Finished/AirRide3D.cpp
777cbd17e65ecbc2ac742ea7fc42ac88e2193591
[]
no_license
SergiPC/Racing_Game_3D
25990f04402e8008e98d47776a9abe64517cfaea
c77deba63a159097ffe07b390321ccc53c5d680b
refs/heads/master
2021-01-10T15:37:08.616013
2015-12-18T20:43:23
2015-12-18T20:43:23
48,252,688
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include "AirRide3D.h" AirRide3D::AirRide3D(btRigidBody* _body) : PhysBody3D(_body) { PhysBody3D* physb = new PhysBody3D(_body); body = physb; } AirRide3D::~AirRide3D() { } void AirRide3D::ApplyForce(vec3 force, vec3 pos) { body->ApplyForce(force.x, force.y, force.z, pos.x, pos.y, pos.z); }
[ "sergi.p.crespo@gmail.com" ]
sergi.p.crespo@gmail.com
c8e93d819d3f508b99f2f759f29e8aa74ce10663
18ea9da58773b0c1b28e593cbd0b54e4b9321946
/Huffman.cpp
2a2ba1f18cfb05c9accee21e90610eb495aae4af
[]
no_license
liontting/HYU_ITE2039
9a9b0d3936c700c5bb8c9af44baaeedf29a26154
6f44d1ecc9a0e077962e2c9e5acdf7d0736efcf2
refs/heads/master
2023-07-02T20:26:10.610873
2021-07-31T06:32:46
2021-07-31T06:32:46
391,249,675
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,518
cpp
// 2019042497_¼ÛÁ¤¸í_11802 #include <stdio.h> #include <string.h> #include <algorithm> int N, total, dap; typedef struct node { char* s; int cnt; node* left; node* right; }node; struct HeapStruct { int Size; node* Elements; }; HeapStruct* CreateHeap() { HeapStruct* heap = (HeapStruct*)malloc(sizeof(HeapStruct)); heap->Elements = (node*)malloc(sizeof(node)*(30010)); heap->Size = 0; return heap; } void Insert(HeapStruct* heap, node value) { int i; for (i = ++heap->Size; i != 1 && heap->Elements[i / 2].cnt > value.cnt; i /= 2) { heap->Elements[i] = heap->Elements[i / 2]; } heap->Elements[i] = value; } node* DeleteMin(HeapStruct* heap) { int i, child; node* Min = (node*)malloc(sizeof(node)); node Last; if (heap->Size == 0) return NULL; Min->cnt = heap->Elements[1].cnt; Min->left = heap->Elements[1].left; Min->right = heap->Elements[1].right; if (heap->Elements[1].s != NULL) { Min->s = (char*)malloc(5); strcpy(Min->s, heap->Elements[1].s); } else Min->s = NULL; Last = heap->Elements[heap->Size--]; for (i = 1; i * 2 <= heap->Size; i = child) { child = i * 2; if (child != heap->Size&&heap->Elements[child + 1].cnt < heap->Elements[child].cnt) child++; if (Last.cnt > heap->Elements[child].cnt) heap->Elements[i] = heap->Elements[child]; else break; } heap->Elements[i] = Last; return Min; } node* buildHuffmanTree(HeapStruct* heap) { while (1) { node* first = DeleteMin(heap); node* second = DeleteMin(heap); if (second == NULL) return first; node* newOne = (node*)malloc(sizeof(node)); newOne->left = first; newOne->right = second; newOne->cnt = first->cnt + second->cnt; newOne->s = NULL; Insert(heap, *newOne); } } void Huffman(node* cur, int count) { if (!cur) return; count++; Huffman(cur->left, count); Huffman(cur->right, count); if (cur->s != NULL) { dap += count * cur->cnt; //printf("%s, %d, count: %d\n", cur->s, cur->cnt, count); } } int main() { HeapStruct* h = CreateHeap(); scanf("%d", &N); for (int i = 0; i < N; i++) { char s[5]; int n; scanf("%s", s); scanf("%d", &n); node* newOne = (node*)malloc(sizeof(node)); newOne->left = NULL; newOne->right = NULL; newOne->s = (char*)malloc(5); strcpy(newOne->s, s); newOne->cnt = n; Insert(h, *newOne); } scanf("%d", &total); int yee = 1, soo = 0; while (N > yee) { yee *= 2; soo++; } node* tree = buildHuffmanTree(h); Huffman(tree, -1); printf("%d\n", total*soo); printf("%d\n", dap); return 0; }
[ "2019042497@hanyang.ac.kr" ]
2019042497@hanyang.ac.kr
81cf2bd927a25949fb6946e3defef7ff8f1faf3a
1e702ab4d4980e87c10afa2596e357956217f09a
/LintCode-CPP/437.copy-books/solution.cpp
4f1e2daccd4541a02a4996001b459e8a76223709
[]
no_license
cxjwin/algorithms
2154e536197e08b38c9d0653ceb3b432c70f6da6
cc6a0e3f3320a25c003f9e4441ed8dcd19b39a73
refs/heads/master
2021-07-05T05:32:20.604221
2020-11-13T00:09:19
2020-11-13T00:09:19
200,500,935
0
0
null
null
null
null
UTF-8
C++
false
false
1,547
cpp
// // Created by smart on 2019/11/5. // #define CATCH_CONFIG_MAIN #include "../catch.hpp" #include <vector> using namespace std; class Solution { public: /** * @param pages: an array of integers * @param k: An integer * @return: an integer */ int copyBooks(vector<int> &pages, int k) { vector<int>::size_type n = pages.size(); if (n == 0) { return 0; } if (k > n) { k = n; } vector<vector<int>> f = vector<vector<int>>(); for (int i = 0; i <= k; ++i) { vector<int> t = vector<int>(n + 1, 0); f.push_back(t); } for (int i = 1; i <= n; ++i) { f[0][i] = INT_MAX; } int sum = 0; for (int t = 1; t <= k; ++t) { f[t][0] = 0; for (int i = 1; i <= n; ++i) { f[t][i] = INT_MAX; sum = 0; for (int j = i; j >= 0; --j) { f[t][i] = min(f[t][i], max(f[t-1][j], sum)); if (j > 0) { sum += pages[j-1]; } } } } return f[k][n]; } }; TEST_CASE("437", "[copyBooks]") { Solution s; /* Input: pages = [3, 2, 4], k = 2 Output: 5 Explanation: First person spends 5 minutes to copy book 1 and book 2. Second person spends 4 minutes to copy book 3. */ vector<int> pages = vector<int>{3, 2, 4}; REQUIRE( s.copyBooks(pages, 2) == 5 ); }
[ "88cxjwin@gmail.com" ]
88cxjwin@gmail.com
bf05caabfcd64057b9460abbe3f5ab97c863af8a
cb07cbace79d8c673ea9149d4ee878cb4f20a1dd
/include/error_code.h
a51aab702692e65bf4ecc51d26918288e3312ecc
[]
no_license
pk-otus/13_join_server
8682097bbaa30348113e0622418a37034be6edbf
73166db3bc0db14ea3b9e1e3fdd7ca4b78666684
refs/heads/master
2020-04-03T03:22:56.839728
2018-11-12T09:06:38
2018-11-12T09:06:38
154,984,243
0
0
null
null
null
null
UTF-8
C++
false
false
388
h
#pragma once #include <string> namespace join_server { enum class error_code { ok = 0, parse_error = 1, duplicate = 2 }; inline std::string error_string(error_code ec) { const char * ERRORS[] = { "OK", "parse error", "duplicate element" }; return (error_code::ok == ec ? std::string() : std::string("ERR ")) + ERRORS[static_cast<int>(ec)]; } }
[ "a@a.a" ]
a@a.a
82adad8e0e5235951048ff851ff2641fed117ed0
25284bc98ae6983d663d165c46b9fa4dab1c0eb6
/Userland/Libraries/LibJS/Runtime/Temporal/DurationConstructor.h
6c8bfa4ff6214e73578fa61022bc6d795d7701c2
[ "BSD-2-Clause" ]
permissive
bgianfo/serenity
6c6564e9b72360c4046c538c60b546b6c2a51cd9
a813b941b82a48d04859669787cbbb21ea469f1e
refs/heads/master
2023-04-14T20:53:16.173060
2022-04-22T02:52:55
2022-07-08T22:27:38
233,478,401
2
1
BSD-2-Clause
2022-02-03T09:02:53
2020-01-13T00:07:49
C++
UTF-8
C++
false
false
774
h
/* * Copyright (c) 2021, Linus Groh <linusg@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include <LibJS/Runtime/NativeFunction.h> namespace JS::Temporal { class DurationConstructor final : public NativeFunction { JS_OBJECT(DurationConstructor, NativeFunction); public: explicit DurationConstructor(GlobalObject&); virtual void initialize(GlobalObject&) override; virtual ~DurationConstructor() override = default; virtual ThrowCompletionOr<Value> call() override; virtual ThrowCompletionOr<Object*> construct(FunctionObject& new_target) override; private: virtual bool has_constructor() const override { return true; } JS_DECLARE_NATIVE_FUNCTION(from); JS_DECLARE_NATIVE_FUNCTION(compare); }; }
[ "mail@linusgroh.de" ]
mail@linusgroh.de
510e9841778095fbca6b3307f27f67874b30ed23
191707dd19837f7abd6f4255cd42b78d3ca741c5
/X11R5/mit/lib/nls/Ximp/zh_TW/Codeset.cpp
0cfcc1627508791bf52e32cd8b4113c379d71c91
[]
no_license
yoya/x.org
4709089f97b1b48f7de2cfbeff1881c59ea1d28e
fb9e6d4bd0c880cfc674d4697322331fe39864d9
refs/heads/master
2023-08-08T02:00:51.277615
2023-07-25T14:05:05
2023-07-25T14:05:05
163,954,490
2
0
null
null
null
null
UTF-8
C++
false
false
1,086
cpp
/* $XConsortium: Codeset.cpp,v 1.2 93/02/24 18:11:31 rws Exp $ */ NAME EUC MB_CUR_MAX 4 STATE_DEPEND_ENCODING FALSE WC_ENCODING_MASK 0x3fffc000 WC_SHIFT_BITS 7 CODESET0 GL INITIAL_STATE_GL LENGTH 1 WC_ENCODING 0x00000000 ENCODING ISO8859-1 GL CNS11643-0 GL FONT ISO8859-1 GL CNS11643-0 GL CODESET1 GR INITIAL_STATE_GR LENGTH 2 WC_ENCODING 0x30000000 ENCODING CNS11643-1 GR FONT CNS11643-1 GL CODESET2 # plane 2 GR LENGTH 2 MB_ENCODING <SS> 0x8e 0xa2 WC_ENCODING 0x10088000 ENCODING CNS11643-2 GR FONT CNS11643-2 GL CODESET3 # plane 14 GR LENGTH 2 MB_ENCODING <SS> 0x8e 0xae WC_ENCODING 0x100b8000 ENCODING CNS11643-14 GR FONT CNS11643-14 GL CODESET4 # plane 15 GR LENGTH 2 MB_ENCODING <SS> 0x8e 0xaf WC_ENCODING 0x100bc000 ENCODING CNS11643-15 GR FONT CNS11643-15 GL CODESET5 # plane 16 GR LENGTH 2 MB_ENCODING <SS> 0x8e 0xb0 WC_ENCODING 0x100c0000 ENCODING CNS11643-16 GR FONT CNS11643-16 GL
[ "yoya@awm.jp" ]
yoya@awm.jp
e7bb5b918c35e4222c409feac1efeab619f07d89
3ea61f80e1e4b2113523624f0de88457b2669852
/src/host/vrm3dvision_backup/srv_gen/cpp/include/vrm3dvision/setExposure.h
7faab3cb858df8f6e205a478d95cec538af17f9a
[]
no_license
rneerg/RoboVision3D
c4f8e05e91702a0df04eeb902771dad52588eb45
f0293ea5f1aaaf64d4530ac9f0f92a3583b55ef6
refs/heads/master
2020-04-18T16:03:55.217179
2014-09-04T11:55:03
2014-09-04T11:55:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,743
h
/* Auto-generated by genmsg_cpp for file /home/jeppe/workspace-d3/robovision3d/host/vrm3dvision/srv/setExposure.srv */ #ifndef VRM3DVISION_SERVICE_SETEXPOSURE_H #define VRM3DVISION_SERVICE_SETEXPOSURE_H #include <string> #include <vector> #include <map> #include <ostream> #include "ros/serialization.h" #include "ros/builtin_message_traits.h" #include "ros/message_operations.h" #include "ros/time.h" #include "ros/macros.h" #include "ros/assert.h" #include "ros/service_traits.h" namespace vrm3dvision { template <class ContainerAllocator> struct setExposureRequest_ { typedef setExposureRequest_<ContainerAllocator> Type; setExposureRequest_() : camera(0) , exposure() { } setExposureRequest_(const ContainerAllocator& _alloc) : camera(0) , exposure(_alloc) { } typedef int32_t _camera_type; int32_t camera; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _exposure_type; std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > exposure; enum { LEFT_CAMERA = 1 }; enum { RIGHT_CAMERA = 2 }; enum { LEFT_AND_RIGHT_CAMERA = 3 }; enum { COLOR_CAMERA = 4 }; enum { ALL_CAMERAS = 7 }; typedef boost::shared_ptr< ::vrm3dvision::setExposureRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::vrm3dvision::setExposureRequest_<ContainerAllocator> const> ConstPtr; boost::shared_ptr<std::map<std::string, std::string> > __connection_header; }; // struct setExposureRequest typedef ::vrm3dvision::setExposureRequest_<std::allocator<void> > setExposureRequest; typedef boost::shared_ptr< ::vrm3dvision::setExposureRequest> setExposureRequestPtr; typedef boost::shared_ptr< ::vrm3dvision::setExposureRequest const> setExposureRequestConstPtr; template <class ContainerAllocator> struct setExposureResponse_ { typedef setExposureResponse_<ContainerAllocator> Type; setExposureResponse_() : success(false) { } setExposureResponse_(const ContainerAllocator& _alloc) : success(false) { } typedef uint8_t _success_type; uint8_t success; typedef boost::shared_ptr< ::vrm3dvision::setExposureResponse_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::vrm3dvision::setExposureResponse_<ContainerAllocator> const> ConstPtr; boost::shared_ptr<std::map<std::string, std::string> > __connection_header; }; // struct setExposureResponse typedef ::vrm3dvision::setExposureResponse_<std::allocator<void> > setExposureResponse; typedef boost::shared_ptr< ::vrm3dvision::setExposureResponse> setExposureResponsePtr; typedef boost::shared_ptr< ::vrm3dvision::setExposureResponse const> setExposureResponseConstPtr; struct setExposure { typedef setExposureRequest Request; typedef setExposureResponse Response; Request request; Response response; typedef Request RequestType; typedef Response ResponseType; }; // struct setExposure } // namespace vrm3dvision namespace ros { namespace message_traits { template<class ContainerAllocator> struct IsMessage< ::vrm3dvision::setExposureRequest_<ContainerAllocator> > : public TrueType {}; template<class ContainerAllocator> struct IsMessage< ::vrm3dvision::setExposureRequest_<ContainerAllocator> const> : public TrueType {}; template<class ContainerAllocator> struct MD5Sum< ::vrm3dvision::setExposureRequest_<ContainerAllocator> > { static const char* value() { return "74690dad3b322aa8761f4ad7fe2c58c2"; } static const char* value(const ::vrm3dvision::setExposureRequest_<ContainerAllocator> &) { return value(); } static const uint64_t static_value1 = 0x74690dad3b322aa8ULL; static const uint64_t static_value2 = 0x761f4ad7fe2c58c2ULL; }; template<class ContainerAllocator> struct DataType< ::vrm3dvision::setExposureRequest_<ContainerAllocator> > { static const char* value() { return "vrm3dvision/setExposureRequest"; } static const char* value(const ::vrm3dvision::setExposureRequest_<ContainerAllocator> &) { return value(); } }; template<class ContainerAllocator> struct Definition< ::vrm3dvision::setExposureRequest_<ContainerAllocator> > { static const char* value() { return "int32 LEFT_CAMERA = 1\n\ int32 RIGHT_CAMERA = 2\n\ int32 LEFT_AND_RIGHT_CAMERA = 3\n\ int32 COLOR_CAMERA = 4\n\ int32 ALL_CAMERAS = 7\n\ \n\ int32 camera\n\ string exposure\n\ \n\ "; } static const char* value(const ::vrm3dvision::setExposureRequest_<ContainerAllocator> &) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace message_traits { template<class ContainerAllocator> struct IsMessage< ::vrm3dvision::setExposureResponse_<ContainerAllocator> > : public TrueType {}; template<class ContainerAllocator> struct IsMessage< ::vrm3dvision::setExposureResponse_<ContainerAllocator> const> : public TrueType {}; template<class ContainerAllocator> struct MD5Sum< ::vrm3dvision::setExposureResponse_<ContainerAllocator> > { static const char* value() { return "358e233cde0c8a8bcfea4ce193f8fc15"; } static const char* value(const ::vrm3dvision::setExposureResponse_<ContainerAllocator> &) { return value(); } static const uint64_t static_value1 = 0x358e233cde0c8a8bULL; static const uint64_t static_value2 = 0xcfea4ce193f8fc15ULL; }; template<class ContainerAllocator> struct DataType< ::vrm3dvision::setExposureResponse_<ContainerAllocator> > { static const char* value() { return "vrm3dvision/setExposureResponse"; } static const char* value(const ::vrm3dvision::setExposureResponse_<ContainerAllocator> &) { return value(); } }; template<class ContainerAllocator> struct Definition< ::vrm3dvision::setExposureResponse_<ContainerAllocator> > { static const char* value() { return "bool success\n\ \n\ \n\ "; } static const char* value(const ::vrm3dvision::setExposureResponse_<ContainerAllocator> &) { return value(); } }; template<class ContainerAllocator> struct IsFixedSize< ::vrm3dvision::setExposureResponse_<ContainerAllocator> > : public TrueType {}; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::vrm3dvision::setExposureRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.camera); stream.next(m.exposure); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct setExposureRequest_ } // namespace serialization } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::vrm3dvision::setExposureResponse_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.success); } ROS_DECLARE_ALLINONE_SERIALIZER; }; // struct setExposureResponse_ } // namespace serialization } // namespace ros namespace ros { namespace service_traits { template<> struct MD5Sum<vrm3dvision::setExposure> { static const char* value() { return "5ba508c10b2f392acb59bcd971e154d8"; } static const char* value(const vrm3dvision::setExposure&) { return value(); } }; template<> struct DataType<vrm3dvision::setExposure> { static const char* value() { return "vrm3dvision/setExposure"; } static const char* value(const vrm3dvision::setExposure&) { return value(); } }; template<class ContainerAllocator> struct MD5Sum<vrm3dvision::setExposureRequest_<ContainerAllocator> > { static const char* value() { return "5ba508c10b2f392acb59bcd971e154d8"; } static const char* value(const vrm3dvision::setExposureRequest_<ContainerAllocator> &) { return value(); } }; template<class ContainerAllocator> struct DataType<vrm3dvision::setExposureRequest_<ContainerAllocator> > { static const char* value() { return "vrm3dvision/setExposure"; } static const char* value(const vrm3dvision::setExposureRequest_<ContainerAllocator> &) { return value(); } }; template<class ContainerAllocator> struct MD5Sum<vrm3dvision::setExposureResponse_<ContainerAllocator> > { static const char* value() { return "5ba508c10b2f392acb59bcd971e154d8"; } static const char* value(const vrm3dvision::setExposureResponse_<ContainerAllocator> &) { return value(); } }; template<class ContainerAllocator> struct DataType<vrm3dvision::setExposureResponse_<ContainerAllocator> > { static const char* value() { return "vrm3dvision/setExposure"; } static const char* value(const vrm3dvision::setExposureResponse_<ContainerAllocator> &) { return value(); } }; } // namespace service_traits } // namespace ros #endif // VRM3DVISION_SERVICE_SETEXPOSURE_H
[ "soelund@mail.dk" ]
soelund@mail.dk
dbceca93d86bcbd05e1c2e69dae7a0579c5ff8ab
73ee941896043f9b3e2ab40028d24ddd202f695f
/external/chromium_org/gpu/command_buffer/service/feature_info.cc
41c6a1b03a316013162b83296f789d7547b9063a
[ "BSD-3-Clause" ]
permissive
CyFI-Lab-Public/RetroScope
d441ea28b33aceeb9888c330a54b033cd7d48b05
276b5b03d63f49235db74f2c501057abb9e79d89
refs/heads/master
2022-04-08T23:11:44.482107
2016-09-22T20:15:43
2016-09-22T20:15:43
58,890,600
5
3
null
null
null
null
UTF-8
C++
false
false
25,687
cc
// Copyright (c) 2012 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 "gpu/command_buffer/service/feature_info.h" #include <set> #include "base/command_line.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "gpu/command_buffer/service/gl_utils.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "ui/gl/gl_implementation.h" #if defined(OS_MACOSX) #include "ui/gl/io_surface_support_mac.h" #endif namespace gpu { namespace gles2 { namespace { struct FormatInfo { GLenum format; const GLenum* types; size_t count; }; class StringSet { public: StringSet() {} StringSet(const char* s) { Init(s); } StringSet(const std::string& str) { Init(str); } void Init(const char* s) { std::string str(s ? s : ""); Init(str); } void Init(const std::string& str) { std::vector<std::string> tokens; Tokenize(str, " ", &tokens); string_set_.insert(tokens.begin(), tokens.end()); } bool Contains(const char* s) { return string_set_.find(s) != string_set_.end(); } bool Contains(const std::string& s) { return string_set_.find(s) != string_set_.end(); } private: std::set<std::string> string_set_; }; // Process a string of wordaround type IDs (seperated by ',') and set up // the corresponding Workaround flags. void StringToWorkarounds( const std::string& types, FeatureInfo::Workarounds* workarounds) { DCHECK(workarounds); std::vector<std::string> pieces; base::SplitString(types, ',', &pieces); for (size_t i = 0; i < pieces.size(); ++i) { int number = 0; bool succeed = base::StringToInt(pieces[i], &number); DCHECK(succeed); switch (number) { #define GPU_OP(type, name) \ case gpu::type: \ workarounds->name = true; \ break; GPU_DRIVER_BUG_WORKAROUNDS(GPU_OP) #undef GPU_OP default: NOTIMPLEMENTED(); } } if (workarounds->max_texture_size_limit_4096) workarounds->max_texture_size = 4096; if (workarounds->max_cube_map_texture_size_limit_4096) workarounds->max_cube_map_texture_size = 4096; if (workarounds->max_cube_map_texture_size_limit_1024) workarounds->max_cube_map_texture_size = 1024; if (workarounds->max_cube_map_texture_size_limit_512) workarounds->max_cube_map_texture_size = 512; } } // anonymous namespace. FeatureInfo::FeatureFlags::FeatureFlags() : chromium_framebuffer_multisample(false), multisampled_render_to_texture(false), use_img_for_multisampled_render_to_texture(false), oes_standard_derivatives(false), oes_egl_image_external(false), npot_ok(false), enable_texture_float_linear(false), enable_texture_half_float_linear(false), chromium_stream_texture(false), angle_translated_shader_source(false), angle_pack_reverse_row_order(false), arb_texture_rectangle(false), angle_instanced_arrays(false), occlusion_query_boolean(false), use_arb_occlusion_query2_for_occlusion_query_boolean(false), use_arb_occlusion_query_for_occlusion_query_boolean(false), native_vertex_array_object(false), enable_shader_name_hashing(false), enable_samplers(false), ext_draw_buffers(false), ext_frag_depth(false), use_async_readpixels(false) { } FeatureInfo::Workarounds::Workarounds() : #define GPU_OP(type, name) name(false), GPU_DRIVER_BUG_WORKAROUNDS(GPU_OP) #undef GPU_OP max_texture_size(0), max_cube_map_texture_size(0) { } FeatureInfo::FeatureInfo() { static const GLenum kAlphaTypes[] = { GL_UNSIGNED_BYTE, }; static const GLenum kRGBTypes[] = { GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_5_6_5, }; static const GLenum kRGBATypes[] = { GL_UNSIGNED_BYTE, GL_UNSIGNED_SHORT_4_4_4_4, GL_UNSIGNED_SHORT_5_5_5_1, }; static const GLenum kLuminanceTypes[] = { GL_UNSIGNED_BYTE, }; static const GLenum kLuminanceAlphaTypes[] = { GL_UNSIGNED_BYTE, }; static const FormatInfo kFormatTypes[] = { { GL_ALPHA, kAlphaTypes, arraysize(kAlphaTypes), }, { GL_RGB, kRGBTypes, arraysize(kRGBTypes), }, { GL_RGBA, kRGBATypes, arraysize(kRGBATypes), }, { GL_LUMINANCE, kLuminanceTypes, arraysize(kLuminanceTypes), }, { GL_LUMINANCE_ALPHA, kLuminanceAlphaTypes, arraysize(kLuminanceAlphaTypes), } , }; for (size_t ii = 0; ii < arraysize(kFormatTypes); ++ii) { const FormatInfo& info = kFormatTypes[ii]; ValueValidator<GLenum>& validator = texture_format_validators_[info.format]; for (size_t jj = 0; jj < info.count; ++jj) { validator.AddValue(info.types[jj]); } } } bool FeatureInfo::Initialize(const char* allowed_features) { disallowed_features_ = DisallowedFeatures(); AddFeatures(*CommandLine::ForCurrentProcess()); return true; } bool FeatureInfo::Initialize(const DisallowedFeatures& disallowed_features, const char* allowed_features) { disallowed_features_ = disallowed_features; AddFeatures(*CommandLine::ForCurrentProcess()); return true; } void FeatureInfo::AddFeatures(const CommandLine& command_line) { // Figure out what extensions to turn on. StringSet extensions( reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))); if (command_line.HasSwitch(switches::kGpuDriverBugWorkarounds)) { std::string types = command_line.GetSwitchValueASCII( switches::kGpuDriverBugWorkarounds); StringToWorkarounds(types, &workarounds_); } feature_flags_.enable_shader_name_hashing = !command_line.HasSwitch(switches::kDisableShaderNameHashing); bool npot_ok = false; AddExtensionString("GL_ANGLE_translated_shader_source"); AddExtensionString("GL_CHROMIUM_async_pixel_transfers"); AddExtensionString("GL_CHROMIUM_bind_uniform_location"); AddExtensionString("GL_CHROMIUM_command_buffer_query"); AddExtensionString("GL_CHROMIUM_command_buffer_latency_query"); AddExtensionString("GL_CHROMIUM_copy_texture"); AddExtensionString("GL_CHROMIUM_discard_backbuffer"); AddExtensionString("GL_CHROMIUM_get_error_query"); AddExtensionString("GL_CHROMIUM_lose_context"); AddExtensionString("GL_CHROMIUM_pixel_transfer_buffer_object"); AddExtensionString("GL_CHROMIUM_rate_limit_offscreen_context"); AddExtensionString("GL_CHROMIUM_resize"); AddExtensionString("GL_CHROMIUM_resource_safe"); AddExtensionString("GL_CHROMIUM_set_visibility"); AddExtensionString("GL_CHROMIUM_strict_attribs"); AddExtensionString("GL_CHROMIUM_stream_texture"); AddExtensionString("GL_CHROMIUM_texture_mailbox"); AddExtensionString("GL_EXT_debug_marker"); if (workarounds_.enable_chromium_fast_npot_mo8_textures) AddExtensionString("GL_CHROMIUM_fast_NPOT_MO8_textures"); feature_flags_.chromium_stream_texture = true; // OES_vertex_array_object is emulated if not present natively, // so the extension string is always exposed. AddExtensionString("GL_OES_vertex_array_object"); if (!disallowed_features_.gpu_memory_manager) AddExtensionString("GL_CHROMIUM_gpu_memory_manager"); if (extensions.Contains("GL_ANGLE_translated_shader_source")) { feature_flags_.angle_translated_shader_source = true; } // Check if we should allow GL_EXT_texture_compression_dxt1 and // GL_EXT_texture_compression_s3tc. bool enable_dxt1 = false; bool enable_dxt3 = false; bool enable_dxt5 = false; bool have_s3tc = extensions.Contains("GL_EXT_texture_compression_s3tc"); bool have_dxt3 = have_s3tc || extensions.Contains("GL_ANGLE_texture_compression_dxt3"); bool have_dxt5 = have_s3tc || extensions.Contains("GL_ANGLE_texture_compression_dxt5"); if (extensions.Contains("GL_EXT_texture_compression_dxt1") || have_s3tc) { enable_dxt1 = true; } if (have_dxt3) { enable_dxt3 = true; } if (have_dxt5) { enable_dxt5 = true; } if (enable_dxt1) { AddExtensionString("GL_EXT_texture_compression_dxt1"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGB_S3TC_DXT1_EXT); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT1_EXT); } if (enable_dxt3) { // The difference between GL_EXT_texture_compression_s3tc and // GL_CHROMIUM_texture_compression_dxt3 is that the former // requires on the fly compression. The latter does not. AddExtensionString("GL_CHROMIUM_texture_compression_dxt3"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT3_EXT); } if (enable_dxt5) { // The difference between GL_EXT_texture_compression_s3tc and // GL_CHROMIUM_texture_compression_dxt5 is that the former // requires on the fly compression. The latter does not. AddExtensionString("GL_CHROMIUM_texture_compression_dxt5"); validators_.compressed_texture_format.AddValue( GL_COMPRESSED_RGBA_S3TC_DXT5_EXT); } // Check if we should enable GL_EXT_texture_filter_anisotropic. if (extensions.Contains("GL_EXT_texture_filter_anisotropic")) { AddExtensionString("GL_EXT_texture_filter_anisotropic"); validators_.texture_parameter.AddValue( GL_TEXTURE_MAX_ANISOTROPY_EXT); validators_.g_l_state.AddValue( GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); } // Check if we should support GL_OES_packed_depth_stencil and/or // GL_GOOGLE_depth_texture / GL_CHROMIUM_depth_texture. // // NOTE: GL_OES_depth_texture requires support for depth cubemaps. // GL_ARB_depth_texture requires other features that // GL_OES_packed_depth_stencil does not provide. // // Therefore we made up GL_GOOGLE_depth_texture / GL_CHROMIUM_depth_texture. // // GL_GOOGLE_depth_texture is legacy. As we exposed it into NaCl we can't // get rid of it. // bool enable_depth_texture = false; if (!workarounds_.disable_depth_texture && (extensions.Contains("GL_ARB_depth_texture") || extensions.Contains("GL_OES_depth_texture") || extensions.Contains("GL_ANGLE_depth_texture"))) { enable_depth_texture = true; } if (enable_depth_texture) { AddExtensionString("GL_CHROMIUM_depth_texture"); AddExtensionString("GL_GOOGLE_depth_texture"); texture_format_validators_[GL_DEPTH_COMPONENT].AddValue(GL_UNSIGNED_SHORT); texture_format_validators_[GL_DEPTH_COMPONENT].AddValue(GL_UNSIGNED_INT); validators_.texture_internal_format.AddValue(GL_DEPTH_COMPONENT); validators_.texture_format.AddValue(GL_DEPTH_COMPONENT); validators_.pixel_type.AddValue(GL_UNSIGNED_SHORT); validators_.pixel_type.AddValue(GL_UNSIGNED_INT); } if (extensions.Contains("GL_EXT_packed_depth_stencil") || extensions.Contains("GL_OES_packed_depth_stencil")) { AddExtensionString("GL_OES_packed_depth_stencil"); if (enable_depth_texture) { texture_format_validators_[GL_DEPTH_STENCIL].AddValue( GL_UNSIGNED_INT_24_8); validators_.texture_internal_format.AddValue(GL_DEPTH_STENCIL); validators_.texture_format.AddValue(GL_DEPTH_STENCIL); validators_.pixel_type.AddValue(GL_UNSIGNED_INT_24_8); } validators_.render_buffer_format.AddValue(GL_DEPTH24_STENCIL8); } if (extensions.Contains("GL_OES_vertex_array_object") || extensions.Contains("GL_ARB_vertex_array_object") || extensions.Contains("GL_APPLE_vertex_array_object")) { feature_flags_.native_vertex_array_object = true; } // If we're using client_side_arrays we have to emulate // vertex array objects since vertex array objects do not work // with client side arrays. if (workarounds_.use_client_side_arrays_for_stream_buffers) { feature_flags_.native_vertex_array_object = false; } if (extensions.Contains("GL_OES_element_index_uint") || gfx::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_element_index_uint"); validators_.index_type.AddValue(GL_UNSIGNED_INT); } bool enable_texture_format_bgra8888 = false; bool enable_read_format_bgra = false; // Check if we should allow GL_EXT_texture_format_BGRA8888 if (extensions.Contains("GL_EXT_texture_format_BGRA8888") || extensions.Contains("GL_APPLE_texture_format_BGRA8888") || extensions.Contains("GL_EXT_bgra")) { enable_texture_format_bgra8888 = true; } if (extensions.Contains("GL_EXT_bgra")) { enable_texture_format_bgra8888 = true; enable_read_format_bgra = true; } if (extensions.Contains("GL_EXT_read_format_bgra") || extensions.Contains("GL_EXT_bgra")) { enable_read_format_bgra = true; } if (enable_texture_format_bgra8888) { AddExtensionString("GL_EXT_texture_format_BGRA8888"); texture_format_validators_[GL_BGRA_EXT].AddValue(GL_UNSIGNED_BYTE); validators_.texture_internal_format.AddValue(GL_BGRA_EXT); validators_.texture_format.AddValue(GL_BGRA_EXT); } if (enable_read_format_bgra) { AddExtensionString("GL_EXT_read_format_bgra"); validators_.read_pixel_format.AddValue(GL_BGRA_EXT); } if (extensions.Contains("GL_OES_rgb8_rgba8") || gfx::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_rgb8_rgba8"); validators_.render_buffer_format.AddValue(GL_RGB8_OES); validators_.render_buffer_format.AddValue(GL_RGBA8_OES); } // Check if we should allow GL_OES_texture_npot if (extensions.Contains("GL_ARB_texture_non_power_of_two") || extensions.Contains("GL_OES_texture_npot")) { AddExtensionString("GL_OES_texture_npot"); npot_ok = true; } // Check if we should allow GL_OES_texture_float, GL_OES_texture_half_float, // GL_OES_texture_float_linear, GL_OES_texture_half_float_linear bool enable_texture_float = false; bool enable_texture_float_linear = false; bool enable_texture_half_float = false; bool enable_texture_half_float_linear = false; bool have_arb_texture_float = extensions.Contains("GL_ARB_texture_float"); if (have_arb_texture_float) { enable_texture_float = true; enable_texture_float_linear = true; enable_texture_half_float = true; enable_texture_half_float_linear = true; } else { if (extensions.Contains("GL_OES_texture_float") || have_arb_texture_float) { enable_texture_float = true; if (extensions.Contains("GL_OES_texture_float_linear") || have_arb_texture_float) { enable_texture_float_linear = true; } } if (extensions.Contains("GL_OES_texture_half_float") || have_arb_texture_float) { enable_texture_half_float = true; if (extensions.Contains("GL_OES_texture_half_float_linear") || have_arb_texture_float) { enable_texture_half_float_linear = true; } } } if (enable_texture_float) { texture_format_validators_[GL_ALPHA].AddValue(GL_FLOAT); texture_format_validators_[GL_RGB].AddValue(GL_FLOAT); texture_format_validators_[GL_RGBA].AddValue(GL_FLOAT); texture_format_validators_[GL_LUMINANCE].AddValue(GL_FLOAT); texture_format_validators_[GL_LUMINANCE_ALPHA].AddValue(GL_FLOAT); validators_.pixel_type.AddValue(GL_FLOAT); validators_.read_pixel_type.AddValue(GL_FLOAT); AddExtensionString("GL_OES_texture_float"); if (enable_texture_float_linear) { AddExtensionString("GL_OES_texture_float_linear"); } } if (enable_texture_half_float) { texture_format_validators_[GL_ALPHA].AddValue(GL_HALF_FLOAT_OES); texture_format_validators_[GL_RGB].AddValue(GL_HALF_FLOAT_OES); texture_format_validators_[GL_RGBA].AddValue(GL_HALF_FLOAT_OES); texture_format_validators_[GL_LUMINANCE].AddValue(GL_HALF_FLOAT_OES); texture_format_validators_[GL_LUMINANCE_ALPHA].AddValue(GL_HALF_FLOAT_OES); validators_.pixel_type.AddValue(GL_HALF_FLOAT_OES); validators_.read_pixel_type.AddValue(GL_HALF_FLOAT_OES); AddExtensionString("GL_OES_texture_half_float"); if (enable_texture_half_float_linear) { AddExtensionString("GL_OES_texture_half_float_linear"); } } // Check for multisample support if (!disallowed_features_.multisampling) { bool ext_has_multisample = extensions.Contains("GL_EXT_framebuffer_multisample"); if (!workarounds_.disable_angle_framebuffer_multisample) { ext_has_multisample |= extensions.Contains("GL_ANGLE_framebuffer_multisample"); } if (ext_has_multisample) { feature_flags_.chromium_framebuffer_multisample = true; validators_.frame_buffer_target.AddValue(GL_READ_FRAMEBUFFER_EXT); validators_.frame_buffer_target.AddValue(GL_DRAW_FRAMEBUFFER_EXT); validators_.g_l_state.AddValue(GL_READ_FRAMEBUFFER_BINDING_EXT); validators_.g_l_state.AddValue(GL_MAX_SAMPLES_EXT); validators_.render_buffer_parameter.AddValue(GL_RENDERBUFFER_SAMPLES_EXT); AddExtensionString("GL_CHROMIUM_framebuffer_multisample"); } else { if (extensions.Contains("GL_EXT_multisampled_render_to_texture")) { feature_flags_.multisampled_render_to_texture = true; } else if (extensions.Contains("GL_IMG_multisampled_render_to_texture")) { feature_flags_.multisampled_render_to_texture = true; feature_flags_.use_img_for_multisampled_render_to_texture = true; } if (feature_flags_.multisampled_render_to_texture) { validators_.render_buffer_parameter.AddValue( GL_RENDERBUFFER_SAMPLES_EXT); validators_.g_l_state.AddValue(GL_MAX_SAMPLES_EXT); validators_.frame_buffer_parameter.AddValue( GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT); AddExtensionString("GL_EXT_multisampled_render_to_texture"); } } } if (extensions.Contains("GL_OES_depth24") || gfx::HasDesktopGLFeatures()) { AddExtensionString("GL_OES_depth24"); validators_.render_buffer_format.AddValue(GL_DEPTH_COMPONENT24); } if (!workarounds_.disable_oes_standard_derivatives && (extensions.Contains("GL_OES_standard_derivatives") || gfx::HasDesktopGLFeatures())) { AddExtensionString("GL_OES_standard_derivatives"); feature_flags_.oes_standard_derivatives = true; validators_.hint_target.AddValue(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES); validators_.g_l_state.AddValue(GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES); } if (extensions.Contains("GL_OES_EGL_image_external")) { AddExtensionString("GL_OES_EGL_image_external"); feature_flags_.oes_egl_image_external = true; validators_.texture_bind_target.AddValue(GL_TEXTURE_EXTERNAL_OES); validators_.get_tex_param_target.AddValue(GL_TEXTURE_EXTERNAL_OES); validators_.texture_parameter.AddValue(GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES); validators_.g_l_state.AddValue(GL_TEXTURE_BINDING_EXTERNAL_OES); } if (extensions.Contains("GL_OES_compressed_ETC1_RGB8_texture")) { AddExtensionString("GL_OES_compressed_ETC1_RGB8_texture"); validators_.compressed_texture_format.AddValue(GL_ETC1_RGB8_OES); } // Ideally we would only expose this extension on Mac OS X, to // support GL_CHROMIUM_iosurface and the compositor. We don't want // applications to start using it; they should use ordinary non- // power-of-two textures. However, for unit testing purposes we // expose it on all supported platforms. if (extensions.Contains("GL_ARB_texture_rectangle")) { AddExtensionString("GL_ARB_texture_rectangle"); feature_flags_.arb_texture_rectangle = true; validators_.texture_bind_target.AddValue(GL_TEXTURE_RECTANGLE_ARB); // For the moment we don't add this enum to the texture_target // validator. This implies that the only way to get image data into a // rectangular texture is via glTexImageIOSurface2DCHROMIUM, which is // just fine since again we don't want applications depending on this // extension. validators_.get_tex_param_target.AddValue(GL_TEXTURE_RECTANGLE_ARB); validators_.g_l_state.AddValue(GL_TEXTURE_BINDING_RECTANGLE_ARB); } #if defined(OS_MACOSX) if (IOSurfaceSupport::Initialize()) { AddExtensionString("GL_CHROMIUM_iosurface"); } #endif // TODO(gman): Add support for these extensions. // GL_OES_depth32 feature_flags_.enable_texture_float_linear |= enable_texture_float_linear; feature_flags_.enable_texture_half_float_linear |= enable_texture_half_float_linear; feature_flags_.npot_ok |= npot_ok; if (extensions.Contains("GL_ANGLE_pack_reverse_row_order")) { AddExtensionString("GL_ANGLE_pack_reverse_row_order"); feature_flags_.angle_pack_reverse_row_order = true; validators_.pixel_store.AddValue(GL_PACK_REVERSE_ROW_ORDER_ANGLE); validators_.g_l_state.AddValue(GL_PACK_REVERSE_ROW_ORDER_ANGLE); } if (extensions.Contains("GL_ANGLE_texture_usage")) { AddExtensionString("GL_ANGLE_texture_usage"); validators_.texture_parameter.AddValue(GL_TEXTURE_USAGE_ANGLE); } if (extensions.Contains("GL_EXT_texture_storage")) { AddExtensionString("GL_EXT_texture_storage"); validators_.texture_parameter.AddValue(GL_TEXTURE_IMMUTABLE_FORMAT_EXT); if (enable_texture_format_bgra8888) validators_.texture_internal_format_storage.AddValue(GL_BGRA8_EXT); if (enable_texture_float) { validators_.texture_internal_format_storage.AddValue(GL_RGBA32F_EXT); validators_.texture_internal_format_storage.AddValue(GL_RGB32F_EXT); validators_.texture_internal_format_storage.AddValue(GL_ALPHA32F_EXT); validators_.texture_internal_format_storage.AddValue( GL_LUMINANCE32F_EXT); validators_.texture_internal_format_storage.AddValue( GL_LUMINANCE_ALPHA32F_EXT); } if (enable_texture_half_float) { validators_.texture_internal_format_storage.AddValue(GL_RGBA16F_EXT); validators_.texture_internal_format_storage.AddValue(GL_RGB16F_EXT); validators_.texture_internal_format_storage.AddValue(GL_ALPHA16F_EXT); validators_.texture_internal_format_storage.AddValue( GL_LUMINANCE16F_EXT); validators_.texture_internal_format_storage.AddValue( GL_LUMINANCE_ALPHA16F_EXT); } } bool have_ext_occlusion_query_boolean = extensions.Contains("GL_EXT_occlusion_query_boolean"); bool have_arb_occlusion_query2 = extensions.Contains("GL_ARB_occlusion_query2"); bool have_arb_occlusion_query = extensions.Contains("GL_ARB_occlusion_query"); if (!workarounds_.disable_ext_occlusion_query && (have_ext_occlusion_query_boolean || have_arb_occlusion_query2 || have_arb_occlusion_query)) { AddExtensionString("GL_EXT_occlusion_query_boolean"); feature_flags_.occlusion_query_boolean = true; feature_flags_.use_arb_occlusion_query2_for_occlusion_query_boolean = !have_ext_occlusion_query_boolean && have_arb_occlusion_query2; feature_flags_.use_arb_occlusion_query_for_occlusion_query_boolean = !have_ext_occlusion_query_boolean && have_arb_occlusion_query && !have_arb_occlusion_query2; } if (!workarounds_.disable_angle_instanced_arrays && (extensions.Contains("GL_ANGLE_instanced_arrays") || (extensions.Contains("GL_ARB_instanced_arrays") && extensions.Contains("GL_ARB_draw_instanced")))) { AddExtensionString("GL_ANGLE_instanced_arrays"); feature_flags_.angle_instanced_arrays = true; validators_.vertex_attribute.AddValue(GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE); } if (!workarounds_.disable_ext_draw_buffers && (extensions.Contains("GL_ARB_draw_buffers") || extensions.Contains("GL_EXT_draw_buffers"))) { AddExtensionString("GL_EXT_draw_buffers"); feature_flags_.ext_draw_buffers = true; GLint max_color_attachments = 0; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS_EXT, &max_color_attachments); for (GLenum i = GL_COLOR_ATTACHMENT1_EXT; i < static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + max_color_attachments); ++i) { validators_.attachment.AddValue(i); } validators_.g_l_state.AddValue(GL_MAX_COLOR_ATTACHMENTS_EXT); validators_.g_l_state.AddValue(GL_MAX_DRAW_BUFFERS_ARB); GLint max_draw_buffers = 0; glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &max_draw_buffers); for (GLenum i = GL_DRAW_BUFFER0_ARB; i < static_cast<GLenum>(GL_DRAW_BUFFER0_ARB + max_draw_buffers); ++i) { validators_.g_l_state.AddValue(i); } } if (extensions.Contains("GL_EXT_frag_depth") || gfx::HasDesktopGLFeatures()) { AddExtensionString("GL_EXT_frag_depth"); feature_flags_.ext_frag_depth = true; } bool ui_gl_fence_works = extensions.Contains("GL_NV_fence") || extensions.Contains("GL_ARB_sync"); if (ui_gl_fence_works && extensions.Contains("GL_ARB_pixel_buffer_object") && !workarounds_.disable_async_readpixels) { feature_flags_.use_async_readpixels = true; } if (!disallowed_features_.swap_buffer_complete_callback) AddExtensionString("GL_CHROMIUM_swapbuffers_complete_callback"); bool is_es3 = false; const char* str = reinterpret_cast<const char*>(glGetString(GL_VERSION)); if (str) { std::string lstr(StringToLowerASCII(std::string(str))); is_es3 = (lstr.substr(0, 12) == "opengl es 3."); } if (is_es3 || extensions.Contains("GL_ARB_sampler_objects")) { feature_flags_.enable_samplers = true; // TODO(dsinclair): Add AddExtensionString("GL_CHROMIUM_sampler_objects") // when available. } } void FeatureInfo::AddExtensionString(const std::string& str) { if (extensions_.find(str) == std::string::npos) { extensions_ += (extensions_.empty() ? "" : " ") + str; } } FeatureInfo::~FeatureInfo() { } } // namespace gles2 } // namespace gpu
[ "ProjectRetroScope@gmail.com" ]
ProjectRetroScope@gmail.com
f7673384f75d908527dd55a1e50285f4d1f7b6e8
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/webrtc/base/win32window.cc
4d41014054124321f32d0ad443cb67a86687a759
[ "BSD-3-Clause", "LicenseRef-scancode-google-patent-license-webrtc", "MIT", "GPL-1.0-or-later", "LicenseRef-scancode-takuya-ooura", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "MS-LPL", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown", "LGPL-2.0-or-later", "Apa...
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
3,663
cc
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/base/common.h" #include "webrtc/base/logging.h" #include "webrtc/base/win32window.h" namespace rtc { /////////////////////////////////////////////////////////////////////////////// // Win32Window /////////////////////////////////////////////////////////////////////////////// static const wchar_t kWindowBaseClassName[] = L"WindowBaseClass"; HINSTANCE Win32Window::instance_ = NULL; ATOM Win32Window::window_class_ = 0; Win32Window::Win32Window() : wnd_(NULL) { } Win32Window::~Win32Window() { ASSERT(NULL == wnd_); } bool Win32Window::Create(HWND parent, const wchar_t* title, DWORD style, DWORD exstyle, int x, int y, int cx, int cy) { if (wnd_) { // Window already exists. return false; } if (!window_class_) { if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<LPCWSTR>(&Win32Window::WndProc), &instance_)) { LOG_GLE(LS_ERROR) << "GetModuleHandleEx failed"; return false; } // Class not registered, register it. WNDCLASSEX wcex; memset(&wcex, 0, sizeof(wcex)); wcex.cbSize = sizeof(wcex); wcex.hInstance = instance_; wcex.lpfnWndProc = &Win32Window::WndProc; wcex.lpszClassName = kWindowBaseClassName; window_class_ = ::RegisterClassEx(&wcex); if (!window_class_) { LOG_GLE(LS_ERROR) << "RegisterClassEx failed"; return false; } } wnd_ = ::CreateWindowEx(exstyle, kWindowBaseClassName, title, style, x, y, cx, cy, parent, NULL, instance_, this); return (NULL != wnd_); } void Win32Window::Destroy() { VERIFY(::DestroyWindow(wnd_) != FALSE); } void Win32Window::Shutdown() { if (window_class_) { ::UnregisterClass(MAKEINTATOM(window_class_), instance_); window_class_ = 0; } } bool Win32Window::OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) { switch (uMsg) { case WM_CLOSE: if (!OnClose()) { result = 0; return true; } break; } return false; } LRESULT Win32Window::WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { Win32Window* that = reinterpret_cast<Win32Window*>( ::GetWindowLongPtr(hwnd, GWLP_USERDATA)); if (!that && (WM_CREATE == uMsg)) { CREATESTRUCT* cs = reinterpret_cast<CREATESTRUCT*>(lParam); that = static_cast<Win32Window*>(cs->lpCreateParams); that->wnd_ = hwnd; ::SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(that)); } if (that) { LRESULT result; bool handled = that->OnMessage(uMsg, wParam, lParam, result); if (WM_DESTROY == uMsg) { for (HWND child = ::GetWindow(hwnd, GW_CHILD); child; child = ::GetWindow(child, GW_HWNDNEXT)) { LOG(LS_INFO) << "Child window: " << static_cast<void*>(child); } } if (WM_NCDESTROY == uMsg) { ::SetWindowLongPtr(hwnd, GWLP_USERDATA, NULL); that->wnd_ = NULL; that->OnNcDestroy(); } if (handled) { return result; } } return ::DefWindowProc(hwnd, uMsg, wParam, lParam); } } // namespace rtc
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
34e5ba4c214854478a0125130d5e23c139be5914
b9440b02caf2ba7f2a5acc406b1d79e5fd258cce
/Encoder.h
5d932859a4b1a81ad89859329a88dc719208ca01
[]
no_license
ehunck/IOSpooferFirmware
6a3bd04e28050995572b9dbb120a9238aed6e03a
153b3052faba3dbbc8392951866b2f7ef874db9e
refs/heads/master
2021-03-22T22:12:59.919849
2020-04-26T04:16:29
2020-04-26T04:16:29
247,402,132
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
#ifndef _ENCODER_H_ #define _ENCODER_H_ #include "mbed.h" class Encoder{ public: Encoder(PinName phaseA, PinName phaseB, PinName button); virtual ~Encoder(); void Init(); bool GetButtonState(); int32_t GetEncoderChange(); private: typedef enum{ Phase_0, Phase_1, Phase_2, Phase_3 } Phase; Phase _current_phase; Phase GetPhase(int A, int B); void HandleEncoderChange(); bool _state; int32_t _count; InterruptIn _phaseA; InterruptIn _phaseB; InterruptIn _button; }; #endif // _ENCODER_H_
[ "ehunck@aol.com" ]
ehunck@aol.com
e24a03e333cc9f7361e175ea9ef57dca4bad15d6
9133d7c763d613ff96371154a760c45ed970469f
/libnrec/ln_mrqcof.cpp
33a2e858b232c180993852aac9db4a1b3a7f7c79
[]
no_license
proteinprospector/prospector
48fc20eead274e4296ed772835ebf96d1c3e8b9e
13e856884120a7479cdffab3d9a99e45354ae37c
refs/heads/master
2021-01-10T04:37:53.346194
2015-12-01T20:23:54
2015-12-01T20:23:54
44,890,436
2
0
null
null
null
null
UTF-8
C++
false
false
4,437
cpp
/****************************************************************************** * * * Library : libnrec * * * * Filename : ln_mrqcof.cpp * * * * Created : * * * * Purpose : * * * * Author(s) : Peter Baker * * * * This file is the confidential and proprietary product of The Regents of * * the University of California. Any unauthorized use, reproduction or * * transfer of this file is strictly prohibited. * * * * Copyright (2000-2007) The Regents of the University of California. * * * * All rights reserved. * * * ******************************************************************************/ #include <nr.h> void mrqmin ( double* x, double* y, double* sig, int ndata, double* a, int ma, int* lista, int mfit, double** covar, double** alpha, double* chisq, void (*funcs)(double, double*, double*, double*, int ), double* alamda ) { int k,kk,j,ihit; static double *da,*atry,**oneda,*beta,ochisq; if (*alamda < 0.0) { oneda=nrmatrix(1,mfit,1,1); atry=nrvector(1,ma); da=nrvector(1,ma); beta=nrvector(1,ma); kk=mfit+1; for (j=1;j<=ma;j++) { ihit=0; for (k=1;k<=mfit;k++) if (lista[k] == j) ihit++; if (ihit == 0) lista[kk++]=j; else if (ihit > 1) nrerror("Bad LISTA permutation in MRQMIN-1"); } if (kk != ma+1) nrerror("Bad LISTA permutation in MRQMIN-2"); *alamda=0.001; mrqcof(x,y,sig,ndata,a,ma,lista,mfit,alpha,beta,chisq,funcs); ochisq=(*chisq); } for (j=1;j<=mfit;j++) { for (k=1;k<=mfit;k++) covar[j][k]=alpha[j][k]; covar[j][j]=alpha[j][j]*(1.0+(*alamda)); oneda[j][1]=beta[j]; } gaussj(covar,mfit,oneda,1); for (j=1;j<=mfit;j++) da[j]=oneda[j][1]; if (*alamda == 0.0) { covsrt(covar,ma,lista,mfit); free_nrvector(beta,1,ma); free_nrvector(da,1,ma); free_nrvector(atry,1,ma); free_nrmatrix(oneda,1,mfit,1,1); return; } for (j=1;j<=ma;j++) atry[j]=a[j]; for (j=1;j<=mfit;j++) atry[lista[j]] = a[lista[j]]+da[j]; mrqcof(x,y,sig,ndata,atry,ma,lista,mfit,covar,da,chisq,funcs); if (*chisq < ochisq) { *alamda *= 0.1; ochisq=(*chisq); for (j=1;j<=mfit;j++) { for (k=1;k<=mfit;k++) alpha[j][k]=covar[j][k]; beta[j]=da[j]; a[lista[j]]=atry[lista[j]]; } } else { *alamda *= 10.0; *chisq=ochisq; } return; } void mrqcof ( double* x, double* y, double* sig, int ndata, double* a, int ma, int* lista, int mfit, double** alpha, double* beta, double* chisq, void (*funcs)(double, double*, double*, double*, int ) ) { int k,j,i; double ymod,wt,sig2i,dy,*dyda; dyda=nrvector(1,ma); for (j=1;j<=mfit;j++) { for (k=1;k<=j;k++) alpha[j][k]=0.0; beta[j]=0.0; } *chisq=0.0; for (i=1;i<=ndata;i++) { (*funcs)(x[i],a,&ymod,dyda,ma); sig2i=1.0/(sig[i]*sig[i]); dy=y[i]-ymod; for (j=1;j<=mfit;j++) { wt=dyda[lista[j]]*sig2i; for (k=1;k<=j;k++) alpha[j][k] += wt*dyda[lista[k]]; beta[j] += dy*wt; } (*chisq) += dy*dy*sig2i; } for (j=2;j<=mfit;j++) for (k=1;k<=j-1;k++) alpha[k][j]=alpha[j][k]; free_nrvector(dyda,1,ma); } void fgauss ( double x, double* a, double* y, double* dyda, int na ) { int i; double fac,ex,arg; // a [i]................intensity // a [i+1]..............mean // a [i+2]..............width [sqrt(2)*stddev] *y=0.0; for (i=1;i<=na-1;i+=3) { arg=(x-a[i+1])/a[i+2]; ex=exp(-arg*arg); fac=a[i]*ex*2.0*arg; *y += a[i]*ex; dyda[i]=ex; dyda[i+1]=fac/a[i+2]; dyda[i+2]=fac*arg/a[i+2]; } }
[ "root@localhost.localdomain" ]
root@localhost.localdomain
9f1d4333fffed7d3fbafc9b2426747d474819f2c
b6a39420b94a48cc486424551afc6d0c41db4387
/Projects/SampleApp_RTS/UnitFactory.cpp
f4eddf2f5cc3bde65856bad8d9396932b8e1fa1b
[ "CC-BY-3.0" ]
permissive
blittle/ezEngine
26268e6217da64c5b79cfa29d38698d5370efd98
4fd29950f77d3dc1857ccb9ce9285ec72181a836
refs/heads/master
2021-01-18T17:23:19.211837
2014-03-27T16:58:17
2014-03-27T16:58:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,385
cpp
#include <PCH.h> #include <SampleApp_RTS/Level.h> template<typename ComponentType, typename ManagerType> ComponentType* AddComponent(ezWorld* pWorld, ezGameObject* pObject) { ManagerType* pManager = pWorld->GetComponentManager<ManagerType>(); ComponentType* pComponent = NULL; ezComponentHandle hComponent = pManager->CreateComponent(pComponent); pObject->AddComponent(hComponent); return pComponent; } ezGameObject* Level::CreateGameObject(const ezVec3& vPosition, const ezQuat& qRotation, float fScaling) { ezGameObjectDesc desc; desc.m_LocalPosition = vPosition; desc.m_LocalRotation = qRotation; desc.m_LocalScaling.Set(fScaling); ezGameObject* pObject = NULL; m_pWorld->CreateObject(desc, pObject); return pObject; } ezGameObjectHandle Level::CreateUnit_Default(const ezVec3& vPosition, const ezQuat& qRotation, float fScaling) { ezGameObject* pObject = CreateGameObject(vPosition, qRotation, fScaling); UnitComponent* pUnitComponent; // Unit component { pUnitComponent = AddComponent<UnitComponent, UnitComponentManager>(m_pWorld, pObject); pUnitComponent->SetUnitType(UnitType::Default); static float fBias = 0.0f; pUnitComponent->m_fSpeedBias = fBias; fBias += 0.1f; } // Revealer component { RevealerComponent* pComponent = AddComponent<RevealerComponent, RevealerComponentManager>(m_pWorld, pObject); } // Obstacle component { ObstacleComponent* pComponent = AddComponent<ObstacleComponent, ObstacleComponentManager>(m_pWorld, pObject); } // Avoid Obstacle Steering Behavior component { AvoidObstacleSteeringComponent* pComponent = AddComponent<AvoidObstacleSteeringComponent, AvoidObstacleSteeringComponentManager>(m_pWorld, pObject); } // Follow Path Steering Behavior component { FollowPathSteeringComponent* pComponent = AddComponent<FollowPathSteeringComponent, FollowPathSteeringComponentManager>(m_pWorld, pObject); pComponent->SetPath(&pUnitComponent->m_Path); } return pObject->GetHandle(); } ezGameObjectHandle Level::CreateUnit(UnitType::Enum Type, const ezVec3& vPosition, const ezQuat& qRotation, float fScaling) { switch (Type) { case UnitType::Default: return CreateUnit_Default(vPosition + ezVec3(0.5f, 0, 0.5f), qRotation, fScaling); } EZ_REPORT_FAILURE("Unknown Unit Type %i", Type); return ezGameObjectHandle(); }
[ "jan@krassnigg.de" ]
jan@krassnigg.de
981c1f8e4852c586c22c1f7dc0afc6dbcf001161
456d0675848b8b11bfec8d052590bdf7eab3a20d
/codes/raulcr-p2798-Accepted-s1056990.cpp
e5053164c23514e7b7282521a3a927b57dbc8536
[ "MIT" ]
permissive
iocodz/coj-solutions
7dfa34ec0b7c830cca00cb0171ee6de18e6553a5
b8c4d6009869b76a67d7bc1d5328b9bd6bfc33ca
refs/heads/master
2022-11-07T09:10:58.938466
2020-06-23T06:21:28
2020-06-23T06:21:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
594
cpp
#include <bits/stdc++.h> using namespace std; typedef long long i64; const int MAXN = 101; i64 TP[MAXN][MAXN]; int M, N, Q; void solve(){ for(int i = 0; i < MAXN; i++) TP[i][0] = TP[i][i] = 1; for(int i = 1; i < MAXN; i++) for(int j = 1; j < i; j++) TP[i][j] = TP[i - 1][j - 1] + TP[i - 1][j]; } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); solve(); cin >> Q; while(Q--){ cin >> M >> N; cout << M << ' ' << TP[N + 9][N] << '\n'; } return 0; }
[ "rrubencr@estudiantes.uci.cu" ]
rrubencr@estudiantes.uci.cu
6f5124ea7074e0d0d29023d4e1b60ee28b851375
90920557422db115b84f066268bdb22218f671a4
/SphereCollision3D/GLIncludes.h
519213ed279156aa280a13281d119f2465f1961d
[]
no_license
IGME-RIT/physics-sphereCollision-3D-VisualStudio
300811cb0175fc7d62ce85ea420e32da0f1664b2
c9ef08b1a2bd20e8e16763335a236f82a0723bcf
refs/heads/master
2020-06-07T08:43:42.090638
2019-06-30T15:09:33
2019-06-30T15:09:33
192,977,531
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,448
h
/* Title: Sphere-sphere 3D collision Detection File Name: GLIncludes.h Copyright © 2015 Original authors: Srinivasan Thiagarajan Written under the supervision of David I. Schwartz, Ph.D., and supported by a professional development seed grant from the B. Thomas Golisano College of Computing & Information Sciences (https://www.rit.edu/gccis) at the Rochester Institute of Technology. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Description: This is a collision test between two spheres in 3D. We check for collision by comparing the distance between the centers of the two spheres and the total sum of their radii. If the distance is greater, then the spheres are not intersecting/colliding; otherwise they are colliding. The movable sphere changes color when a collision is detected. Use Mouse to move in x-y plane, and "w and s" to move in z axis. References: AABB-2D by Brockton Roth */ #ifndef _GL_INCLUDES_H #define _GL_INCLUDES_H #include <iostream> #include <fstream> #include <vector> #include <string> #include <algorithm> #include "gl\glew.h" #include "glfw\glfw3.h" #include "glm\glm.hpp" #include "glm\gtc\matrix_transform.hpp" #include "glm\gtc\type_ptr.hpp" #include "glm\gtc\quaternion.hpp" #include "glm\gtx\quaternion.hpp" #include "glm\gtx\rotate_vector.hpp" #define PI 3.14159265 #define DIVISIONS 40 // We create a VertexFormat struct, which defines how the data passed into the shader code wil be formatted struct VertexFormat { glm::vec4 color; // A vector4 for color has 4 floats: red, green, blue, and alpha glm::vec3 position; // A vector3 for position has 3 float: x, y, and z coordinates // Default constructor VertexFormat() { color = glm::vec4(0.0f); position = glm::vec3(0.0f); } // Constructor VertexFormat(const glm::vec3 &pos, const glm::vec4 &iColor) { position = pos; color = iColor; } }; #endif _GL_INCLUDES_H
[ "njp2424@ad.rit.edu" ]
njp2424@ad.rit.edu
dd92f4c4abdbccfad59e8e173482a9495a7b7f6e
fb8a0ab0af25f4adf4d69c845f6916948cd7f35c
/NSU/Practice/20131221/H.cpp
ebc86fedde44b50281fcf8c613386c7abe107e79
[]
no_license
enterstudio/sport-programming
851cb713856cfe913b50ca28cd217800fc8f0f05
e4268e3103b25991a0abe7cecc700c1588446ce9
refs/heads/master
2021-05-12T00:05:06.827550
2016-10-14T09:02:42
2016-10-14T09:09:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,407
cpp
// In the name of Allah, Most Gracious, Most Merciful // / // // // // // ?? #include <cassert> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <algorithm> #include <deque> #include <functional> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> #define SET(c, v) memset(c, v, sizeof(c)) #define LEN(c) (sizeof(c)/sizeof(c[0])) #define ALL(c) c.begin(), c.end() #define SLC(c, n) c, c+(n) using namespace std; typedef unsigned int uint; typedef long long vlong; typedef unsigned long long uvlong; const double EPS = 1e-12; const double PI = acos(-1.0); enum { }; map<string, int> M; vector<pair<string, double> > V; char B[35]; int main() { int T; scanf("%d", &T); gets(B); gets(B); while(T--) { M.clear(); V.clear(); int L = 0; while(true) { if(gets(B) == NULL || !B[0]) { break; } ++M[string(B)]; ++L; } for(map<string, int>::iterator it = M.begin(); it != M.end(); ++it) { V.push_back(pair<string, double>(it->first, double(it->second) / double(L) * 100)); } sort(ALL(V)); for(int i = 0; i < V.size(); ++i) { printf("%s %0.4lf\n", V[i].first.c_str(), V[i].second); } if(T != 0) { printf("\n"); } } return 0; }
[ "m@hjr265.me" ]
m@hjr265.me
787b8a74e74e2fbe2b2c69c0dc013774fd349e9f
cde72953df2205c2322aac3debf058bb31d4f5b9
/win10.19042/System32/DiagnosticInvoker.dll.cpp
e5471cc61f3a5b17451af115aa3f5458fbe8c179
[]
no_license
v4nyl/dll-exports
928355082725fbb6fcff47cd3ad83b7390c60c5a
4ec04e0c8f713f6e9a61059d5d87abc5c7db16cf
refs/heads/main
2023-03-30T13:49:47.617341
2021-04-10T20:01:34
2021-04-10T20:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
310
cpp
#print comment(linker, "/export:DllCanUnloadNow=\"C:\\Windows\\System32\\DiagnosticInvoker.dll\"") #print comment(linker, "/export:DllGetActivationFactory=\"C:\\Windows\\System32\\DiagnosticInvoker.dll\"") #print comment(linker, "/export:DllGetClassObject=\"C:\\Windows\\System32\\DiagnosticInvoker.dll\"")
[ "magnus@stubman.eu" ]
magnus@stubman.eu
67b93673790b3c4865c0481a6ac87b9f8e1bc452
4cc7c74b4bb7b818562bedffd026a86f9ec78f41
/chrome/browser/android/webapk/webapk_update_manager.cc
44d52932451167fa4c4da822bc4a6939cbe0504b
[ "BSD-3-Clause" ]
permissive
jennyb2911/chromium
1e03c9e5a63af1cf82832e0e99e0028e255872bd
62b48b4fdb3984762f4d2fd3690f02f167920f52
refs/heads/master
2023-01-10T01:08:34.961976
2018-09-28T03:36:36
2018-09-28T03:36:36
150,682,761
1
0
NOASSERTION
2018-09-28T03:49:28
2018-09-28T03:49:27
null
UTF-8
C++
false
false
6,085
cc
// Copyright 2016 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 <jni.h> #include <memory> #include <vector> #include "base/android/callback_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/files/file_path.h" #include "base/strings/string16.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/android/shortcut_info.h" #include "chrome/browser/android/webapk/webapk_install_service.h" #include "chrome/browser/android/webapk/webapk_installer.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "content/public/browser/browser_thread.h" #include "jni/WebApkUpdateManager_jni.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/android/java_bitmap.h" #include "url/gurl.h" using base::android::JavaRef; using base::android::JavaParamRef; using base::android::ScopedJavaGlobalRef; namespace { // Called after the update either succeeds or fails. void OnUpdated(const JavaRef<jobject>& java_callback, WebApkInstallResult result, bool relax_updates, const std::string& webapk_package) { JNIEnv* env = base::android::AttachCurrentThread(); Java_WebApkUpdateCallback_onResultFromNative( env, java_callback, static_cast<int>(result), relax_updates); } } // anonymous namespace // static JNI method. static void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jstring>& java_update_request_path, const JavaParamRef<jstring>& java_start_url, const JavaParamRef<jstring>& java_scope, const JavaParamRef<jstring>& java_name, const JavaParamRef<jstring>& java_short_name, const JavaParamRef<jstring>& java_primary_icon_url, const JavaParamRef<jobject>& java_primary_icon_bitmap, const JavaParamRef<jstring>& java_badge_icon_url, const JavaParamRef<jobject>& java_badge_icon_bitmap, const JavaParamRef<jobjectArray>& java_icon_urls, const JavaParamRef<jobjectArray>& java_icon_hashes, jint java_display_mode, jint java_orientation, jlong java_theme_color, jlong java_background_color, const JavaParamRef<jstring>& java_web_manifest_url, const JavaParamRef<jstring>& java_webapk_package, jint java_webapk_version, jboolean java_is_manifest_stale, jint java_update_reason, const JavaParamRef<jobject>& java_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string update_request_path = ConvertJavaStringToUTF8(env, java_update_request_path); ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url))); info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope)); info.name = ConvertJavaStringToUTF16(env, java_name); info.short_name = ConvertJavaStringToUTF16(env, java_short_name); info.user_title = info.short_name; info.display = static_cast<blink::WebDisplayMode>(java_display_mode); info.orientation = static_cast<blink::WebScreenOrientationLockType>(java_orientation); info.theme_color = (int64_t)java_theme_color; info.background_color = (int64_t)java_background_color; info.best_primary_icon_url = GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url)); info.best_badge_icon_url = GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url)); info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url)); base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls.obj(), &info.icon_urls); std::vector<std::string> icon_hashes; base::android::AppendJavaStringArrayToStringVector( env, java_icon_hashes.obj(), &icon_hashes); std::map<std::string, std::string> icon_url_to_murmur2_hash; for (size_t i = 0; i < info.icon_urls.size(); ++i) icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i]; gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap); SkBitmap primary_icon = gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock); primary_icon.setImmutable(); SkBitmap badge_icon; if (!java_badge_icon_bitmap.is_null()) { gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap); gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock); badge_icon.setImmutable(); } std::string webapk_package; ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package); WebApkUpdateReason update_reason = static_cast<WebApkUpdateReason>(java_update_reason); WebApkInstaller::StoreUpdateRequestToFile( base::FilePath(update_request_path), info, primary_icon, badge_icon, webapk_package, std::to_string(java_webapk_version), icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason, base::BindOnce(&base::android::RunBooleanCallbackAndroid, ScopedJavaGlobalRef<jobject>(java_callback))); } // static JNI method. static void JNI_WebApkUpdateManager_UpdateWebApkFromFile( JNIEnv* env, const JavaParamRef<jclass>& clazz, const JavaParamRef<jstring>& java_update_request_path, const JavaParamRef<jobject>& java_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ScopedJavaGlobalRef<jobject> callback_ref(java_callback); Profile* profile = ProfileManager::GetLastUsedProfile(); if (profile == nullptr) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&OnUpdated, callback_ref, WebApkInstallResult::FAILURE, false /* relax_updates */, "" /* webapk_package */)); return; } std::string update_request_path = ConvertJavaStringToUTF8(env, java_update_request_path); WebApkInstallService::Get(profile)->UpdateAsync( base::FilePath(update_request_path), base::Bind(&OnUpdated, callback_ref)); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b8048363be1a016f8abf7e5c6453b723b1359e50
57534a699c35f9543bdee08325d01a4b14b91ab4
/localProcessInfo.h
fe7612e2792ccb11d4ada344f3dffe95134225f0
[]
no_license
TibbersDriveMustang/DME
19024907552a85d8b7dfd699e783dfc79a54b8f9
3989a987dade05729ac28b05cc7238f83bec7cd8
refs/heads/master
2021-01-21T20:37:51.353592
2015-04-04T07:43:25
2015-04-04T07:43:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
528
h
#include "messageFormat.h" #include <vector> class algorithmDataStruct { protected: int quorumSize; int totalNodeNumber; public: int nodeID; vector<int> quorumMembers; bool REQUESTING; bool TOKEN; bool USING; bool KNOWFLAG; int TADDR; //save the nodeID of which hold the token bool SERVFLAG; int SERVEE; //save the nodeID of which the local node is serving char **mapIDtoIP; //save the IP Address of correspond nodeID void receiveMessage(Packet msg); void sendMessage(Packet msg); }
[ "guohongyi1991@gmail.com" ]
guohongyi1991@gmail.com
7ab9fe2aae06419fecd4b77af5641011abf55b4f
42020c6b3bd1b112d3279f6b120965e9dc5fddcf
/topcoder/fox_and_sight_seeing/fox_and_sight_seeing.cpp
1c4e64e4185a081b4e692791c0e35d736e178f5c
[]
no_license
FishinLab/Algorithms_FisHinLab
e594191730e724015693f2ee3d3d7e6990baeb3f
f1e9f622c94dcf7eb87b2f0f53c9c82213f08ef0
refs/heads/master
2020-04-04T19:28:02.325165
2013-11-15T01:14:52
2013-11-15T01:14:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
825
cpp
#include <iostream> #include <math.h> using namespace std; #define MAX_LIMIT 100000 int get_dist(int* data, int len){ int res; for(int i = 0; i < len - 1; ++i){ res += abs(data[i] - data[i + 1]); } return res; } int main(int argc, const char* argv[]){ int length = argc - 1; int* data = new int[length]; for(int i = 0; i < length; ++i) data[i] = atoi(argv[i + 1]); int result = MAX_LIMIT; int c = 0; while(c < length){ int* tmp_data = new int[length - 1]; for(int j = 0; j < length; ++j){ if(j == c) continue; tmp_data[j] = data[c]; c++; } int dist = get_dist(tmp_data, length - 1); if(result > dist) result = dist; } cout << "fox_and_sight_seeing: " << result << endl; return 0; }
[ "fishinlab@sina.com" ]
fishinlab@sina.com
b78dc476f1ac3cf83d6ef16bddc66ca319854fd3
133ca087e9762340f232c4b5b2318c94fe7153e1
/src/dolier-clu-seq2.cpp
c88f1944bebc2ccb0335f7b6ebd159e1470d6a90
[ "MIT" ]
permissive
vbonnici/DoLiER
8fe4a0fe5dab4cb8d7e89c34c6ed4f3abe69ee58
6f628b4ac5ddcbe941196813cb5faba551bd2a26
refs/heads/master
2021-06-23T19:14:41.578431
2021-03-18T16:37:41
2021-03-18T16:37:41
210,795,762
0
0
null
null
null
null
UTF-8
C++
false
false
6,631
cpp
/* * dolier-clu-seq1.cpp * * Created on: Feb 5, 2014 * Author: vbonnici */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <string> #include <sstream> #include <set> #include "data_ts.h" #include "timer.h" #include "trim.h" #include "pars_t.h" #include "dimers.h" #include "DNA5Alphabet.h" #include "FASTAReader.h" #include "CstyleIndex.h" #include "NSAIterator.h" #include "Cs5DLIndex.h" #include "SASearcher.h" #include "main_common.h" #include "fvector.h" #include "seq2.h" #include "distances.h" using namespace dolierlib; using namespace dolierlib::seq1; char* scmd; void pusage(){ std::cout<<"Usage: "<<scmd<<" <input_file> <output_file> <minDist> [--normalize] [--keep-only value] [--weights] [--log-weights] [--yupac] [-v]\n"; } class mpars_t : public pars_t{ public: std::string ifile; std::string ofile; double minDist; bool opt_normalize; double keep_only; bool opt_weights; bool opt_log_weights; bool opt_yupac; bool opt_v; mpars_t(int argc, char* argv[]) : pars_t(argc,argv){ minDist = 0; opt_normalize = false; keep_only = 0; opt_weights = false; opt_log_weights = false; opt_yupac = false; opt_v = false; } ~mpars_t(){} virtual void print(){ std::cout<<"[ARG][ifile]["<<ifile<<"]\n"; std::cout<<"[ARG][ofile]["<<ofile<<"]\n"; std::cout<<"[ARG][minDist]["<<minDist<<"]\n"; std::cout<<"[ARG][normalize]["<<opt_normalize<<"]\n"; std::cout<<"[ARG][keep_only]["<<keep_only<<"]\n"; std::cout<<"[ARG][weights]["<<opt_weights<<"]\n"; std::cout<<"[ARG][log_weights]["<<opt_log_weights<<"]\n"; std::cout<<"[ARG][yupac]["<<opt_yupac<<"]\n"; } virtual void check(){ print(); std::cout<<"check...\n"; ifile = trim(ifile); ofile = trim(ofile); if( (ifile.length() == 0) || (ofile.length() == 0) || (minDist < 0) || (keep_only < 0) ){ usage(); exit(1); } } virtual void usage(){ pusage(); } virtual void parse(){ ifile = next_string(); ofile = next_string(); minDist = next_double(); std::string cmd; while(has_more()){ cmd = next_string(); if(cmd == "--normalize"){ opt_normalize = true; } else if(cmd == "--keep-only"){ keep_only = next_double(); } else if(cmd == "--weights"){ opt_weights = true; } else if(cmd == "--log-weights"){ opt_log_weights = true; } else if(cmd == "--yupac"){ opt_yupac = true; } else if(cmd == "-v"){ opt_v = true; } else{ usage(); exit(1); } } check(); } }; int main(int argc, char* argv[]){ scmd = argv[0]; mpars_t pars(argc,argv); pars.parse(); size_t max_length = 0; std::ifstream ifs; ifs.open(pars.ifile.c_str(), std::ios::in); if(!ifs.is_open() || ifs.bad()){ std::cout<<"Error on opening input file : "<<pars.ifile<<" \n"; exit(1); } std::vector<dna5_t*> f_sequences; std::vector<usize_t> f_lengths; std::string ikmer; while(ifs >> ikmer){ f_sequences.push_back(to_dna5(ikmer)); f_lengths.push_back(ikmer.length()); if(ikmer.length() > max_length) max_length = ikmer.length(); } ifs.close(); std::cout<<"nof seqs = "<<f_sequences.size()<<"\n"; leading_shuffle(f_sequences, f_lengths, static_cast<size_t>(ceil(f_sequences.size() * 0.1))); shuffle(f_sequences, f_lengths, f_sequences.size()*10); // std::cout<<"-----------------------------------------------------------------------\n"; // for(size_t i=0; i<f_sequences.size(); i++){ // std::cout<<i<<"\t";print_dna5(f_sequences[i], f_lengths[i]);std::cout<<"\n"; // } // std::cout<<"-----------------------------------------------------------------------\n"; double **vectors; size_t vlength = 0; double *weights; fvector(f_sequences,f_lengths,&vectors, &vlength, &weights); // print_matrix(vectors, f_sequences.size(), vlength); //double *weights = new double[vlength]; if(pars.opt_weights){ //get_fvectors_weights(weights, vlength); if(pars.opt_log_weights){ for(size_t i=0; i<vlength; i++) weights[i] = log(weights[i]); } } else{ for(size_t i=0 ;i<vlength; i++){ weights[i] = 1; } } std::cout<<"nof sequences "<<f_sequences.size()<<"\n"; std::cout<<"vector length "<<vlength<<"\n"; size_t nlength = vlength; if(pars.keep_only > 0){ keep_only(vectors, f_sequences.size(), vlength, 2.0, &nlength, weights); std::cout<<"vector length "<<nlength<<"\n"; } if(pars.opt_normalize) normalize(vectors, f_sequences.size(), nlength); if(pars.opt_v){ for(size_t i=0; i<f_sequences.size(); i++){ for(size_t j=0; j<i; j++){ print_dna5(f_sequences[i], f_lengths[i]); std::cout<<" "; print_dna5(f_sequences[j], f_lengths[j]); std::cout<<" "; std::cout<<dist_tanimoto(vectors[i], vectors[j], weights, nlength); std::cout<<"\n"; } } } seq2_algorithm algo(vectors, f_sequences.size(), nlength, weights, pars.minDist); //algo.run(); algo.run(f_sequences, f_lengths); if(pars.opt_v){ std::vector<size_t> dmetoids; algo.get_metoids_by_mindist(dmetoids); for(size_t i=0; i<algo.clusters.size(); i++){ std::cout<<"Cluster["<<i<<"]\n"; std::cout<<"\tdmetoid\t"; print_dna5(f_sequences[dmetoids[i]],f_lengths[dmetoids[i]]); std::cout<<"\n"; for(std::set<size_t>::iterator IT = algo.clusters[i].begin(); IT!=algo.clusters[i].end(); IT++){ print_dna5(f_sequences[(*IT)], f_lengths[(*IT)]); std::cout<<"\n"; } } } // std::vector<size_t> mmetoids; // std::vector<size_t> dmetoids; // algo.get_metoids_by_mean(mmetoids); // algo.get_metoids_by_mindist(dmetoids); // for(size_t i=0; i<algo.clusters.size(); i++){ //// std::cout<<"Cluster["<<i<<"]\t"; //// print_dna5(f_sequences[dmetoids[i]],f_lengths[dmetoids[i]]); std::cout<<"\n"; // std::cout<<"Cluster["<<i<<"]\n"; // std::cout<<"\tmmetoid\t"; print_dna5(f_sequences[mmetoids[i]],f_lengths[mmetoids[i]]); std::cout<<"\n"; // std::cout<<"\tdmetoid\t"; print_dna5(f_sequences[dmetoids[i]],f_lengths[dmetoids[i]]); std::cout<<"\n"; // //std::vector< std::set<size_t> > // for(std::set<size_t>::iterator IT = algo.clusters[i].begin(); IT!=algo.clusters[i].end(); IT++){ // print_dna5(f_sequences[(*IT)], f_lengths[(*IT)]); std::cout<<"\n"; // } // } std::ofstream ofs; ofs.open((pars.ofile).c_str(), std::ios::out); if(!ofs.is_open() || ofs.bad()){ std::cout<<"Error on opening output file : "<<pars.ofile<<" \n"; exit(1); } if(!pars.opt_yupac){ std::vector<size_t> dmetoids; algo.get_metoids_by_mindist(dmetoids); for(size_t i=0; i<dmetoids.size(); i++){ ofs<<to_string(f_sequences[dmetoids[i]],f_lengths[dmetoids[i]])<<"\n"; } } else{ } ofs.flush(); ofs.close(); }
[ "vincenzo.bonnici@gmail.com" ]
vincenzo.bonnici@gmail.com
f596db83fd09d2df6cbfde312553e03c67dc8423
20a209dc3d68447bfb2ebcd32165627097ed7f68
/src/plugins/RemoveAttributeCommand/RemoveAttributePlugin.cpp
c9944db15d432d4b62e8182b9273c6d83c5ac410
[]
no_license
refaqtor/ProjectConceptor
f25512176518b05d64554b95a8cd7412c5fee7e0
4f481d5a53a341b9ac194293a62bbd28ad2dcfad
refs/heads/master
2022-04-21T16:10:44.538439
2020-04-16T07:39:09
2020-04-16T07:39:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include "RemoveAttributePlugin.h" extern "C" _EXPORT BasePlugin *NewProjektConceptorPlugin(image_id); BasePlugin* NewProjektConceptorPlugin( image_id id ) { RemoveAttributePlugin *basicCommand=new RemoveAttributePlugin( id ); return basicCommand; } RemoveAttributePlugin::RemoveAttributePlugin(image_id id):BasePlugin(id) { }
[ "paradoxon@f08798fa-4112-0410-b753-e4f865caae7a" ]
paradoxon@f08798fa-4112-0410-b753-e4f865caae7a
55d331c2e5894e59015fe1cacc38ec271a533c71
6e0ea161c7d5188781aff57768f55ee734dffeb4
/mainwindow.h
64b9fa8547deff91e54d14328ae52eb8108472a4
[]
no_license
JasserBOUKRYA/smart_municipality_2A10
0ef3d0c306484b71655526c5ac30c0e806f27ff6
cea7760e2f6493db33b3b5935c8e0290c7779f10
refs/heads/master
2023-02-10T05:35:54.447904
2021-01-09T15:55:20
2021-01-09T15:55:20
316,346,057
0
0
null
null
null
null
UTF-8
C++
false
false
589
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMessageBox> #include <QSound> #include <QSqlError> #include <QSqlQuery> #include <QSqlQueryModel> #include "menu.h" #include <QPalette> #include "menuadmin.h" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); QString matriculegeneral; private slots: void on_pushButton_clicked(); private: Ui::MainWindow *ui; QSound *son; }; #endif // MAINWINDOW_H
[ "75099727+Flija0@users.noreply.github.com" ]
75099727+Flija0@users.noreply.github.com
1b7cdd741b4f0281061e3e630fcbc7f52205e405
798dd8cc7df5833999dfceb0215bec7384783e6a
/unit_tests/queryagg.cpp
40fd41aa9646a32716a99e67b99f1361739011f1
[ "BSD-3-Clause" ]
permissive
sblanas/pythia
8cf85b39d555c6ce05445d9d690d5462d0e80007
b138eaa0fd5917cb4665094b963abe458bd33d0f
refs/heads/master
2016-09-06T03:43:26.647265
2014-02-10T21:39:24
2014-02-10T21:39:24
16,710,063
15
8
null
2014-03-08T05:29:34
2014-02-10T21:31:16
C++
UTF-8
C++
false
false
4,746
cpp
/* * Copyright 2014, Pythia authors (see AUTHORS file). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "libconfig.h++" #include "../query.h" #include "../operators/operators.h" #include "../visitors/allvisitors.h" #include "common.h" const char* tempfilename = "artzimpourtzikaioloulas.tmp"; // #define VERBOSE const int TUPLES = 20; const int FILTERVAL = 10; using namespace std; using namespace libconfig; Query q; void compute() { int verify[FILTERVAL]; for (int i=0; i<FILTERVAL; ++i) { verify[i] = 0; } q.threadInit(); Operator::Page* out; Operator::GetNextResultT result; if (q.scanStart() != Operator::Ready) { fail("Scan initialization failed."); } while(result.first == Operator::Ready) { result = q.getNext(); out = result.second; Operator::Page::Iterator it = out->createIterator(); void* tuple; while ( (tuple = it.next()) ) { #ifdef VERBOSE cout << q.getOutSchema().prettyprint(tuple, ' ') << endl; #endif long long v = q.getOutSchema().asLong(tuple, 0); if (v <= 0) fail("Values that never were generated appear in the output stream."); if (v >= FILTERVAL) fail("Read values that filter should have eliminated."); if (verify[v-1] != 0) fail("Aggregation group appears twice."); if (q.getOutSchema().asLong(tuple, 1) != 1) fail("Aggregation value is wrong."); verify[v-1]++; } } if (q.scanStop() != Operator::Ready) { fail("Scan stop failed."); } q.threadClose(); } int main() { const int aggbuckets = 1; // 16; const int buffsize = 1 << 4;// 20; createfile(tempfilename, TUPLES); AggregateCount node1; Filter node2; ScanOp node3; Config cfg; // init node1 Setting& aggnode = cfg.getRoot().add("aggcount", Setting::TypeGroup); aggnode.add("field", Setting::TypeInt) = 0; Setting& agghashnode = aggnode.add("hash", Setting::TypeGroup); agghashnode.add("fn", Setting::TypeString) = "modulo"; agghashnode.add("buckets", Setting::TypeInt) = aggbuckets; agghashnode.add("field", Setting::TypeInt) = 0; // init node2 ostringstream oss; oss << FILTERVAL; Setting& filternode = cfg.getRoot().add("filter", Setting::TypeGroup); filternode.add("field", Setting::TypeInt) = 0; filternode.add("op", Setting::TypeString) = "<"; filternode.add("value", Setting::TypeString) = oss.str(); // init node3 cfg.getRoot().add("path", Setting::TypeString) = "./"; cfg.getRoot().add("buffsize", Setting::TypeInt) = buffsize; Setting& scannode = cfg.getRoot().add("scan", Setting::TypeGroup); scannode.add("filetype", Setting::TypeString) = "text"; scannode.add("file", Setting::TypeString) = tempfilename; Setting& schemanode = scannode.add("schema", Setting::TypeList); schemanode.add(Setting::TypeString) = "long"; schemanode.add(Setting::TypeString) = "long"; // build plan tree q.tree = &node1; node1.nextOp = &node2; node2.nextOp = &node3; // initialize each node node3.init(cfg, scannode); node2.init(cfg, filternode); node1.init(cfg, aggnode); #ifdef VERBOSE cout << "---------- QUERY PLAN START ----------" << endl; PrettyPrinterVisitor ppv; q.accept(&ppv); cout << "----------- QUERY PLAN END -----------" << endl; #endif compute(); q.destroynofree(); deletefile(tempfilename); return 0; }
[ "blanas.2@osu.edu" ]
blanas.2@osu.edu
949d29b33ba814e753c1ca71e5b6a914e850550c
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/winmgmt/coredll/import.cpp
9eee8eee8765b93f7939f3f6b65f556fced3f50e
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,995
cpp
/*++ Copyright (C) 1996-2001 Microsoft Corporation Module Name: IMPORT.CPP Abstract: History: --*/ #include "precomp.h" #ifdef _MMF #include <StdIo.h> #include <ConIo.h> #include "ObjDb.h" #include "Import.h" #include "export.h" #include <WbemUtil.h> #include <FastAll.h> #include "Sinks.h" #include <corex.h> #include <reg.h> template <class T> class CMyRelMe { T m_p; public: CMyRelMe(T p) : m_p(p) {}; ~CMyRelMe() { if (m_p) m_p->Release(); } void Set(T p) { m_p = p; } }; void CRepImporter::DecodeTrailer() { DWORD dwTrailerSize = 0; DWORD dwTrailer[4]; DWORD dwSize = 0; if ((ReadFile(m_hFile, &dwTrailerSize, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, LOG_WBEMCORE,"Failed to decode a block trailer\n")); throw FAILURE_READ; } if (dwTrailerSize != REP_EXPORT_END_TAG_SIZE) { DEBUGTRACE((LOG_WBEMCORE, "Failed to decode a block trailer\n")); throw FAILURE_INVALID_TRAILER; } if ((ReadFile(m_hFile, dwTrailer, REP_EXPORT_END_TAG_SIZE, &dwSize, NULL) == 0) || (dwSize != REP_EXPORT_END_TAG_SIZE)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to decode a block trailer\n")); throw FAILURE_READ; } for (int i = 0; i < 4; i++) { if (dwTrailer[i] != REP_EXPORT_FILE_END_TAG) { DEBUGTRACE((LOG_WBEMCORE, "Block trailer has invalid contents.\n")); throw FAILURE_INVALID_TRAILER; } } } void CRepImporter::DecodeInstanceInt(CObjDbNS *pNs, const wchar_t *pszParentClass, CWbemObject *pClass, CWbemClass *pNewParentClass) { //Read the key and object size INT_PTR dwKey = 0; DWORD dwSize = 0; if ((ReadFile(m_hFile, &dwKey, sizeof(INT_PTR), &dwSize, NULL) == 0) || (dwSize != sizeof(INT_PTR))) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve instance key for class %S.\n", pszParentClass)); throw FAILURE_READ; } DWORD dwHeader; if ((ReadFile(m_hFile, &dwHeader, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve instance information for class %S.\n", pszParentClass)); throw FAILURE_READ; } char *pObjectBlob = new char[dwHeader]; if (pObjectBlob == 0) { throw FAILURE_OUT_OF_MEMORY; } CDeleteMe<char> delMe(pObjectBlob); //Read the blob if ((ReadFile(m_hFile, pObjectBlob, dwHeader, &dwSize, NULL) == 0) || (dwSize != dwHeader)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve instance information for class %S.\n", pszParentClass)); throw FAILURE_READ; } if (pNewParentClass == (CWbemClass *)-1) { //We are working with a class which has problems... we need to ignore this instance... return; } CWbemInstance *pThis = (CWbemInstance *) CWbemInstance::CreateFromBlob((CWbemClass *) pClass,(LPMEMORY) pObjectBlob); if (pThis == 0) throw FAILURE_OUT_OF_MEMORY; CMyRelMe<CWbemInstance*> relMe(pThis); if (pNewParentClass) { // The parent class changed (probably system class derivative), so we need to // reparent the instance.... CWbemInstance * pNewInstance = 0; //Now we need to merge the instance bits... HRESULT hRes = pThis->Reparent(pNewParentClass, &pNewInstance); if (hRes == WBEM_E_OUT_OF_MEMORY) throw FAILURE_OUT_OF_MEMORY; else if (hRes != WBEM_NO_ERROR) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create a new instance for a system class because the fixing up of the instance and class failed, %S.%d\n", pszParentClass, dwKey)); throw FAILURE_CANNOT_CREATE_INSTANCE; } CMyRelMe<CWbemObject*> relMe3(pNewInstance); //Now we need to write it... if (m_pDb->CreateObject(pNs, (CWbemObject*)pNewInstance, 0) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create instance %S.%d\n", pszParentClass, dwKey)); throw FAILURE_CANNOT_CREATE_INSTANCE; } } else if (m_pDb->CreateObject(pNs, (CWbemObject*)pThis, 0) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create instance %S.%d\n", pszParentClass, dwKey)); throw FAILURE_CANNOT_CREATE_INSTANCE; } } void CRepImporter::DecodeInstanceString(CObjDbNS *pNs, const wchar_t *pszParentClass, CWbemObject *pClass, CWbemClass *pNewParentClass ) { //Read the key and object size DWORD dwKeySize; DWORD dwSize = 0; if ((ReadFile(m_hFile, &dwKeySize, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve instance information for class %S.\n", pszParentClass)); throw FAILURE_READ; } wchar_t *wszKey = new wchar_t[dwKeySize]; if (wszKey == NULL) { throw FAILURE_OUT_OF_MEMORY; } CDeleteMe<wchar_t> delMe(wszKey); if ((ReadFile(m_hFile, wszKey, dwKeySize, &dwSize, NULL) == 0) || (dwSize != dwKeySize)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve instance information for class %S.\n", pszParentClass)); throw FAILURE_READ; } DWORD dwBlobSize; if ((ReadFile(m_hFile, &dwBlobSize, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve instance %S.%S from import file.\n", pszParentClass, wszKey)); throw FAILURE_READ; } char *pObjectBlob = new char[dwBlobSize]; if (pObjectBlob == NULL) { throw FAILURE_OUT_OF_MEMORY; } CDeleteMe<char> delMe2(pObjectBlob); //Read the blob if ((ReadFile(m_hFile, pObjectBlob, dwBlobSize, &dwSize, NULL) == 0) || (dwSize != dwBlobSize)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve instance %S.%S from import file.\n", pszParentClass, wszKey)); throw FAILURE_READ; } if (pNewParentClass == (CWbemClass *)-1) { //We are working with a class which has problems... we need to ignore this instance... return; } CWbemInstance *pThis = (CWbemInstance *) CWbemInstance::CreateFromBlob((CWbemClass *) pClass,(LPMEMORY) pObjectBlob); if (pThis == 0) throw FAILURE_OUT_OF_MEMORY; CMyRelMe<CWbemInstance*> relMe(pThis); //If this is a namespace we need to do something different! BSTR bstrClassName = SysAllocString(L"__namespace"); CSysFreeMe delMe3(bstrClassName); HRESULT hRes = pThis->InheritsFrom(bstrClassName); if (hRes == S_OK) { if (wbem_wcsicmp(wszKey, L"default") != 0 && wbem_wcsicmp(wszKey, L"security") != 0) { if (m_pDb->AddNamespace(pNs, wszKey, pThis) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create namespace %S.%S in repository.\n", pszParentClass, wszKey)); throw FAILURE_CANNOT_ADD_NAMESPACE; } } else { //WE don't need to do anything with the default or security namespace!!! } } else if (hRes == WBEM_E_OUT_OF_MEMORY) throw FAILURE_OUT_OF_MEMORY; else { if (pNewParentClass) { // The parent class changed (probably system class derivative), so we ned to // reparent the instance.... CWbemInstance * pNewInstance = 0; //Now we need to merge the instance bits... HRESULT hRes = pThis->Reparent(pNewParentClass, &pNewInstance); if (hRes == WBEM_E_OUT_OF_MEMORY) throw FAILURE_OUT_OF_MEMORY; else if (hRes != WBEM_NO_ERROR) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create a new instance for a system class because the fixing up of the instance and class failed, %S.%S\n", pszParentClass, wszKey)); throw FAILURE_CANNOT_CREATE_INSTANCE; } CMyRelMe<CWbemObject*> relMe3(pNewInstance); //Now we need to write it... if (m_pDb->CreateObject(pNs, (CWbemObject*)pNewInstance, 0) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create instance %S.%S\n", pszParentClass, wszKey)); throw FAILURE_CANNOT_CREATE_INSTANCE; } } else if (m_pDb->CreateObject(pNs, (CWbemObject*)pThis, 0)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create instance %S.%S in repository.\n", pszParentClass, wszKey)); throw FAILURE_CANNOT_CREATE_INSTANCE; } } } void CRepImporter::DecodeClass(CObjDbNS *pNs, const wchar_t *wszParentClass, CWbemObject *pParentClass, CWbemClass *pNewParentClass) { //Read our current class from the file... DWORD dwClassSize = 0; DWORD dwSize = 0; CWbemObject *pClass = 0; CMyRelMe<CWbemObject*> relMe(pClass); CWbemClass *pNewClass = 0; CMyRelMe<CWbemClass*> relMe2(pNewClass); if ((ReadFile(m_hFile, &dwClassSize, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve class information for class with parent class %S.\n", wszParentClass)); throw FAILURE_READ; } wchar_t *wszClass = new wchar_t[dwClassSize]; if (wszClass == NULL) { throw FAILURE_OUT_OF_MEMORY; } CDeleteMe<wchar_t> delMe(wszClass); if ((ReadFile(m_hFile, wszClass, dwClassSize, &dwSize, NULL) == 0) || (dwSize != dwClassSize)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve class information for class with parent class %S.\n", wszParentClass)); throw FAILURE_READ; } //Now we have the class blob... if ((ReadFile(m_hFile, &dwClassSize, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve class information for class %S.\n", wszClass)); throw FAILURE_READ; } if (dwClassSize) { char *pClassBlob = new char[dwClassSize]; if (pClassBlob == NULL) { throw FAILURE_OUT_OF_MEMORY; } CDeleteMe<char> delMe2(pClassBlob); if ((ReadFile(m_hFile, pClassBlob, dwClassSize, &dwSize, NULL) == 0) || (dwSize != dwClassSize)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve class information for class %S.\n", wszClass)); throw FAILURE_READ; } pClass = CWbemClass::CreateFromBlob((CWbemClass*)pParentClass,(LPMEMORY) pClassBlob); if (pClass == 0) throw FAILURE_OUT_OF_MEMORY; relMe.Set(pClass); //Is there a new parent class? If so we need to create a new class based on that... if (pNewParentClass && (pNewParentClass != (CWbemClass *)-1)) { if (FAILED(pNewParentClass->Update((CWbemClass*)pClass, WBEM_FLAG_UPDATE_FORCE_MODE, &pNewClass))) { DEBUGTRACE((LOG_WBEMCORE, "Failed to update the class based on an undated parent class, class %S.\n", wszClass)); } relMe2.Set(pNewClass); } else if ((pNewParentClass != (CWbemClass *)-1) && (wcsncmp(wszClass, L"__", 2) == 0)) { //This is a system class... see if this has changed... CWbemObject *pTmpNewClass = 0; if (m_pDb->GetObject(pNs, CObjectDatabase::flag_class, wszClass, &pTmpNewClass) == CObjectDatabase::no_error) { pNewClass = (CWbemClass*)pTmpNewClass; relMe2.Set(pNewClass); if (pNewClass->CompareMostDerivedClass((CWbemClass*)pClass)) { //These are the same, so we do not need to do anything with this. relMe2.Set(NULL); pNewClass->Release(); pNewClass = 0; } } else { //If this does not exist then it cannot be important! pNewClass = (CWbemClass *)-1; } } else if (pNewParentClass == (CWbemClass *)-1) { pNewClass = (CWbemClass *)-1; } //If the class is a system class then we do not write it... it may have changed for starters, //but also we create all system classes when a new database/namespace is created... bool bOldSecurityClass = false; if(m_bSecurityMode) { if(!_wcsicmp(wszClass, L"__SecurityRelatedClass")) bOldSecurityClass = true; else if(!_wcsicmp(wszClass, L"__Subject")) bOldSecurityClass = true; else if(!_wcsicmp(wszClass, L"__User")) bOldSecurityClass = true; else if(!_wcsicmp(wszClass, L"__NTLMUser")) bOldSecurityClass = true; else if(!_wcsicmp(wszClass, L"__Group")) bOldSecurityClass = true; else if(!_wcsicmp(wszClass, L"__NTLMGroup")) bOldSecurityClass = true; if(bOldSecurityClass) m_bSecurityClassesWritten = true; } if (_wcsnicmp(wszClass, L"__", 2) != 0) { if (pNewClass && (pNewClass != (CWbemClass *)-1)) { //Store new class... if (m_pDb->CreateObject(pNs, pNewClass, 0) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create class for class %S.\n", wszClass)); } //Once put, we need to re-get it as class comparisons may fail to see that //this class is in fact the same as the one in the database! pNewClass->Release(); pNewClass = 0; relMe2.Set(NULL); CWbemObject *pTmpClass = 0; if (m_pDb->GetObject(pNs, CObjectDatabase::flag_class, wszClass, &pTmpClass) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve class %S from the repository after creating it.\n", wszClass)); throw FAILURE_CANNOT_GET_PARENT_CLASS; } pNewClass = (CWbemClass*)pTmpClass; relMe2.Set(pNewClass); } else if (pNewClass != (CWbemClass *)-1) { //Store the old one... if (m_pDb->CreateObject(pNs, pClass, 0) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to create class for class %S.\n", wszClass)); } } } } else { if (m_pDb->GetObject(pNs, CObjectDatabase::flag_class, wszClass, &pClass) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve class %S from the repository.\n", wszClass)); throw FAILURE_CANNOT_GET_PARENT_CLASS; } relMe.Set(pClass); } //Now we iterate through all child classes and instances until we get //and end of class marker... while (1) { DWORD dwType = 0; if ((ReadFile(m_hFile, &dwType, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to next block type from import file.\n")); throw FAILURE_READ; } if (dwType == REP_EXPORT_CLASS_TAG) { DecodeClass(pNs, wszClass, pClass, pNewClass); } else if (dwType == REP_EXPORT_INST_INT_TAG) { DecodeInstanceInt(pNs, wszClass, pClass, pNewClass); } else if (dwType == REP_EXPORT_INST_STR_TAG) { DecodeInstanceString(pNs, wszClass, pClass, pNewClass); } else if (dwType == REP_EXPORT_CLASS_END_TAG) { //That's the end of this class... DecodeTrailer(); break; } else { DEBUGTRACE((LOG_WBEMCORE, "Next block type is invalid in import file.\n")); throw FAILURE_INVALID_TYPE; } } } void CRepImporter::DecodeNamespace(const wchar_t *wszParentNamespace) { //Read our current namespace from the file... DWORD dwNsSize = 0; DWORD dwSize = 0; if ((ReadFile(m_hFile, &dwNsSize, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve a namespace whose parent namespace is %S.\n", wszParentNamespace)); throw FAILURE_READ; } wchar_t *wszNs = new wchar_t[dwNsSize]; if (wszNs == NULL) { throw FAILURE_OUT_OF_MEMORY; } CDeleteMe<wchar_t> delMe(wszNs); if ((ReadFile(m_hFile, wszNs, dwNsSize, &dwSize, NULL) == 0) || (dwSize != dwNsSize)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve a namespace whose parent namespace is %S.\n", wszParentNamespace)); throw FAILURE_READ; } if (wbem_wcsicmp(wszNs, L"security") == 0) { m_bSecurityMode = true; } wchar_t *wszFullPath = new wchar_t[wcslen(wszParentNamespace) + 1 + wcslen(wszNs) + 1]; if (wszFullPath == NULL) { throw FAILURE_OUT_OF_MEMORY; } CDeleteMe<wchar_t> delMe2(wszFullPath); wcscpy(wszFullPath, wszParentNamespace); if (wcslen(wszParentNamespace) != 0) { wcscat(wszFullPath, L"\\"); } wcscat(wszFullPath, wszNs); CObjDbNS *pNs; if (m_pDb->GetNamespace(wszFullPath, &pNs) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve namespace %S from the repository.\n", wszFullPath)); throw FAILURE_CANNOT_FIND_NAMESPACE; } //Get and set the namespace security... DWORD dwBuffer[2]; if ((ReadFile(m_hFile, dwBuffer, 8, &dwSize, NULL) == 0) || (dwSize != 8)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve a namespace security header for namespace %S.\n", wszFullPath)); throw FAILURE_READ; } if (dwBuffer[0] != REP_EXPORT_NAMESPACE_SEC_TAG) { DEBUGTRACE((LOG_WBEMCORE, "Expecting a namespace security blob and did not find it.\n")); throw FAILURE_INVALID_TYPE; } if (dwBuffer[1] != 0) { char *pNsSecurity = new char[dwBuffer[1]]; if (pNsSecurity == NULL) { throw FAILURE_OUT_OF_MEMORY; } CDeleteMe<char> delMe(pNsSecurity); if ((ReadFile(m_hFile, pNsSecurity, dwBuffer[1], &dwSize, NULL) == 0) || (dwSize != dwBuffer[1])) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve a namespace security blob for namespace %S.\n", wszFullPath)); throw FAILURE_READ; } if (m_pDb->SetSecurityOnNamespace(pNs, pNsSecurity, dwBuffer[1]) != CObjectDatabase::no_error) { DEBUGTRACE((LOG_WBEMCORE, "Failed to add security to namespace %S.\n", wszFullPath)); throw FAILURE_CANNOT_ADD_NAMESPACE_SECURITY; } } //Now we need to iterate through the next set of blocks of namespace or class //until we get to and end of NS marker while (1) { DWORD dwType = 0; if ((ReadFile(m_hFile, &dwType, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to next block type from import file.\n")); throw FAILURE_READ; } if (dwType == REP_EXPORT_NAMESPACE_TAG) { DecodeNamespace(wszFullPath); } else if (dwType == REP_EXPORT_CLASS_TAG) { DecodeClass(pNs, L"", NULL, NULL); } else if (dwType == REP_EXPORT_NAMESPACE_END_TAG) { //That's the end of this namespace... DecodeTrailer(); break; } else { DEBUGTRACE((LOG_WBEMCORE, "Next block type is invalid in import file.\n")); throw FAILURE_INVALID_TYPE; } } m_pDb->CloseNamespace(pNs); m_bSecurityMode = false; } void CRepImporter::Decode() { char pszBuff[7]; DWORD dwSize = 0; if ((ReadFile(m_hFile, pszBuff, 7, &dwSize, NULL) == 0) || (dwSize != 7)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to retrieve the import file header information\n")); throw FAILURE_READ; } if (strncmp(pszBuff, REP_EXPORT_FILE_START_TAG, 7) != 0) { DEBUGTRACE((LOG_WBEMCORE, "The import file specified is not an import file.\n")); throw FAILURE_INVALID_FILE; } //We should have a tag for a namespace... DWORD dwType = 0; if ((ReadFile(m_hFile, &dwType, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to next block type from import file.\n")); throw FAILURE_READ; } if (dwType != REP_EXPORT_NAMESPACE_TAG) { DEBUGTRACE((LOG_WBEMCORE, "Next block type is invalid in import file.\n")); throw FAILURE_INVALID_TYPE; } DecodeNamespace(L""); //Now we should have the file trailer if ((ReadFile(m_hFile, &dwType, 4, &dwSize, NULL) == 0) || (dwSize != 4)) { DEBUGTRACE((LOG_WBEMCORE, "Failed to next block type from import file.\n")); throw FAILURE_READ; } if (dwType != REP_EXPORT_FILE_END_TAG) { DEBUGTRACE((LOG_WBEMCORE, "Next block type is invalid in import file.\n")); throw FAILURE_INVALID_TYPE; } DecodeTrailer(); } int CRepImporter::ImportRepository(const TCHAR *pszFromFile) { int nRet = CObjectDatabase::no_error; m_hFile = CreateFile(pszFromFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (m_hFile != INVALID_HANDLE_VALUE) { m_pDb = new CObjectDatabase(); if (m_pDb == NULL) { nRet = CObjectDatabase::out_of_memory; } else { m_pDb->Open(); try { Decode(); } catch (char nProblem) { switch (nProblem) { case FAILURE_READ: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Failed to read the required amount from the import file.\n")); break; case FAILURE_INVALID_FILE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: The file header is not correct.\n")); break; case FAILURE_INVALID_TYPE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: An invalid block type was found in the export file.\n")); break; case FAILURE_INVALID_TRAILER: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: An invalid block trailer was found in the export file.\n")); break; case FAILURE_CANNOT_FIND_NAMESPACE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Could not open a namespace in the repository.\n")); break; case FAILURE_CANNOT_GET_PARENT_CLASS: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Could not retrieve parent class from repository.\n")); break; case FAILURE_CANNOT_CREATE_INSTANCE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Could not create instance.\n")); break; case FAILURE_CANNOT_ADD_NAMESPACE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Could not add namespace.\n")); break; case FAILURE_OUT_OF_MEMORY: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Out of memory.\n")); break; default: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: An unknown problem happened while traversing the import file. Import file may be corrupt.\n")); break; } DEBUGTRACE((LOG_WBEMCORE, "The file may not be an exported repository file, or it may be corrupt.\n")); nRet = CObjectDatabase::failed; } catch (CX_MemoryException) { nRet = CObjectDatabase::out_of_memory; } catch (...) { DEBUGTRACE((LOG_WBEMCORE, "Traversal of import file failed. It may be corrupt.\n")); nRet = CObjectDatabase::critical_error; } m_pDb->Shutdown(TRUE); delete m_pDb; } CloseHandle(m_hFile); if (nRet == CObjectDatabase::no_error) DEBUGTRACE((LOG_WBEMCORE, "Import succeeded.\n")); else DEBUGTRACE((LOG_WBEMCORE, "Import failed.\n")); } else { DEBUGTRACE((LOG_WBEMCORE, "Could not open the import file \"%s\" for reading.\n", pszFromFile)); nRet = CObjectDatabase::critical_error; } return nRet; } int CRepImporter::RestoreRepository(const TCHAR *pszFromFile, CObjectDatabase *pDb) { int nRet = CObjectDatabase::no_error; m_hFile = CreateFile(pszFromFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (m_hFile != INVALID_HANDLE_VALUE) { m_pDb = pDb; try { Decode(); } catch (int nProblem) { nRet = CObjectDatabase::critical_error; switch (nProblem) { case FAILURE_READ: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Failed to read the required amount from the import file.\n")); break; case FAILURE_INVALID_FILE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: The file header is not correct.\n")); break; case FAILURE_INVALID_TYPE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: An invalid block type was found in the export file.\n")); break; case FAILURE_INVALID_TRAILER: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: An invalid block trailer was found in the export file.\n")); break; case FAILURE_CANNOT_FIND_NAMESPACE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Could not open a namespace in the repository.\n")); break; case FAILURE_CANNOT_GET_PARENT_CLASS: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Could not retrieve parent class from repository.\n")); break; case FAILURE_CANNOT_CREATE_INSTANCE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Could not create instance.\n")); break; case FAILURE_CANNOT_ADD_NAMESPACE: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Could not add namespace.\n")); break; case FAILURE_OUT_OF_MEMORY: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Out of memory.\n")); throw CX_MemoryException(); break; default: DEBUGTRACE((LOG_WBEMCORE, "IMPORT: An unknown problem happened while traversing the import file. Import file may be corrupt.\n")); break; } } catch (CX_MemoryException) { nRet = CObjectDatabase::out_of_memory; } catch (...) { DEBUGTRACE((LOG_WBEMCORE, "IMPORT: Traversal of import file failed. It may be corrupt.\n")); nRet =CObjectDatabase::critical_error; } CloseHandle(m_hFile); if (nRet == CObjectDatabase::no_error) DEBUGTRACE((LOG_WBEMCORE, "Import succeeded.\n")); else DEBUGTRACE((LOG_WBEMCORE, "Import failed.\n")); } else { DEBUGTRACE((LOG_WBEMCORE, "Could not open the import file \"%s\" for reading.\n", pszFromFile)); nRet = CObjectDatabase::critical_error; } return nRet; } CRepImporter::~CRepImporter() { // If there were some old security classes, set a registry flag so that they will be // converted to ACE entries later on by the security code if(m_bSecurityClassesWritten) { Registry r(WBEM_REG_WINMGMT); r.SetDWORDStr(__TEXT("OldSecurityClassesNeedConverting"), 4); } } #endif
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
44ae7a9a5ed445da82a56ca156dda86658af6834
dfc4d0ae87d50a34441c80a690955126001f36a4
/9948.cpp
3f732b2b524e9833c12f921e104cfad8682147df
[]
no_license
fakerainjw/ProblemSolving
48c2e83f414f3ea9a9b8e182ff94842b4f9453ae
402c06a1d64ee287e39a74282acc1f0c7714d8fe
refs/heads/master
2023-07-08T07:33:18.003061
2016-08-01T13:16:07
2016-08-01T13:16:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,469
cpp
#include <iostream> #include <cstdio> #include <cstring> using namespace std; char input_stream[101]; int accCal[14]={0,0,31,59,90,120,151,181,212,243,273,304,334,365}; int main(void) { int N; int standard = 4+accCal[8]; freopen("test.txt","r",stdin); while (true) { cin>>N>>input_stream; getchar(); int val = 0; if ( N==0 && (strcmp(input_stream,"#")==0) ) break; val = N; if ( N==29 && strcmp(input_stream,"February")==0 ) printf("Unlucky\n"); else { if ( strcmp(input_stream,"January")==0 ) val += accCal[1]; else if ( strcmp(input_stream,"February")==0 ) val += accCal[2]; else if ( strcmp(input_stream,"March")==0 ) val += accCal[3]; else if ( strcmp(input_stream,"April")==0 ) val += accCal[4]; else if ( strcmp(input_stream,"May")==0 ) val += accCal[5]; else if ( strcmp(input_stream,"June")==0 ) val += accCal[6]; else if ( strcmp(input_stream,"July")==0 ) val += accCal[7]; else if ( strcmp(input_stream,"August")==0 ) val += accCal[8]; else if ( strcmp(input_stream,"September")==0 ) val += accCal[9]; else if ( strcmp(input_stream,"October")==0 ) val += accCal[10]; else if ( strcmp(input_stream,"November")==0 ) val += accCal[11]; else if ( strcmp(input_stream,"December")==0 ) val += accCal[12]; if ( standard < val ) printf("No\n"); else if ( standard > val ) printf("Yes\n"); else printf("Happy birthday\n"); } } }
[ "jjim9417@naver.com" ]
jjim9417@naver.com
ea53bbf03a5ed6ab79faaa47e11dbeb6a2401f70
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/Network/UNIX_Network_ZOS.hxx
456459b6184da6082978f0c229df760aeb32bbea
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
108
hxx
#ifdef PEGASUS_OS_ZOS #ifndef __UNIX_NETWORK_PRIVATE_H #define __UNIX_NETWORK_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
585fb43db1e0c446d9ab8b7c9d779ce431ed8584
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testcaputime/src/tutime.cpp
2998c0bfcfd5972495f5b1beb261da130cd00e6e
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
cpp
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ #include "tutime.h" CTestutime::~CTestutime() { } CTestutime::CTestutime(const TDesC& aStepName) { // MANDATORY Call to base class method to set up the human readable name for logging. SetTestStepName(aStepName); } TVerdict CTestutime::doTestStepPreambleL() { __UHEAP_MARK; SetTestStepResult(EPass); return TestStepResult(); } TVerdict CTestutime::doTestStepPostambleL() { __UHEAP_MARKEND; return TestStepResult(); } TVerdict CTestutime::doTestStepL() { int err; //captest steps if(TestStepName() == Kutimesys) { INFO_PRINTF1(_L("utimesys():")); err = utimesys(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } else if(TestStepName() == Kutimeprivate) { INFO_PRINTF1(_L("utimeprivate():")); err = utimeprivate(); SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass); } return TestStepResult(); }
[ "none@none" ]
none@none
d0a7e253b3c38d1dac54f599e87332071a464dc0
4959f2669434a8f42f229e4d5f5f638f51a0ceec
/Exercise/algorithm_stl_intro/3_chapter_BST.cpp
4d782119aec54a71ae693db603c5a75d2c33e317
[]
no_license
bruce1408/Alogrithm_Datastruct
5425642afd6cdada6bd12968d832dcbf9dd526ab
04d94b5bbf6680f689d22d15134e9a870d6a452e
refs/heads/master
2023-07-08T03:27:13.051414
2023-06-24T13:00:51
2023-06-24T13:00:51
128,039,673
2
0
null
null
null
null
UTF-8
C++
false
false
4,074
cpp
#include <iostream> #include <vector> using namespace std; /** * 二叉查找树BST介绍 * 性质: * 左节点小于或者等于根节点 * 右节点大于根节点 * 按照二叉树中序遍历的话是一个有序的数组 * * 5 * / \ * 3 7 * / \ / \ * 2 4 6 8 * 节点的前驱和后继 * 二叉搜索树节点的前驱是比该节点权值小的最大节点,是该节点 左子树 的 最右节点 * 后继是比该节点权值大的最小节点,是该节点 右子树 的 最左节点 */ struct node { int val; node *left; node *right; node(int x) : val(x), left(NULL), right(NULL) {} }; /** * 二叉树的查找 */ void search(node *root, int x) { if (root == nullptr) return; if (x == root->val) { cout << "find :" << root->val << endl; } else if (x < root->val) // 小于根节点,那么在左边插入 { search(root->left, x); } else // 大于根节点,右边插入 { search(root->right, x); } } /** * 二叉查找树节点的插入,使用递归来插入新节点 * */ void insert(node *&root, int x) // 这里函数在二叉树中插入一个数据域为x的节点,root要加上引用 { if (root == nullptr) // 如果是空节点,查找失败,当前位置也是插入位置 { root = new node(x); return; } if (x == root->val) return; // 说明这个节点已经存在,不需要插入 else if (x > root->val) // 如果这个数大于根节点,说明应该在右节点插入 insert(root->right, x); else insert(root->left, x); } /** * 二叉查找树的建立 */ node *create(vector<int> &res) { node *root = nullptr; for (int i = 0; i < res.size(); i++) { insert(root, res[i]); } return root; } /** * 二叉查找树后继节点查找,查找的是最右子树节点 */ node *preNode(node *root) { while (root->right != nullptr) { root = root->right; // 不断往右,然后找到最后的那个节点 } return root; } /** * 二叉查找树前驱结点查找,找到的是最左子树节点 */ node *reaNode(node *root) { while (root->left != nullptr) { root = root->left; } return root; } /** * 二叉查找树的中序遍历; */ void inorder(node *root) { if (root == nullptr) return; inorder(root->left); cout << root->val << " "; inorder(root->right); } /** * 二叉查找树删除值为x的某个节点 */ void deleteNode(node *&root, int x) { if (root == nullptr) // 如果这节点空直接返回 return; if (root->val == x) // 找到要删除的节点 { if (root->left == NULL && root->right == nullptr) // 左右叶子节点都不存在,直接删除 root = nullptr; else if (root->left != nullptr) // 删除的这个节点的左子树不为空节点 { node *pre = preNode(root->left); // 找到这个节点的前驱节点,就是左子树的最右节点,比这个节点小的最大节点 root->val = pre->val; deleteNode(root->left, pre->val); // 这里删除的不再是原来的点,而是赋值之后,新的前驱节点的数值 } else // 如果右子树不为空的话,那么在右子树中删除左节点 { node *after = reaNode(root->right); root->val = after->val; deleteNode(root->right, after->val); } } else if (root->val > x) { deleteNode(root->left, x); } else { deleteNode(root->right, x); } } int main() { vector<int> res = {5, 3, 7, 4, 2, 8, 6}; node *root = create(res); cout << "中序遍历果: " << endl; inorder(root); cout << endl; cout << "找出根节点 5 的前驱节点和后继节点" << endl; cout << "前驱节点: " << preNode(root->left)->val << endl; cout << "后继节点: " << reaNode(root->right)->val << endl; }
[ "summer56567@163.com" ]
summer56567@163.com
a6b52354020731f2d48246ab21e11d1f63ed02c0
b912920999fb5bc518d0f1ef7205dbfbe857028b
/Data Structures & Algorithm/Sorting/insertion_sort.cpp
bfe9f2c198854b746710668777cd961d77a149fc
[ "MIT" ]
permissive
Abhishek0104/Competitive-Coding
d2f1907c4954fe64fddf8b970d5683f1f1a3e69a
c5900000bcea5aba55ea8ede2e505fb2ca2bcf36
refs/heads/master
2020-08-06T07:43:00.671863
2020-02-17T07:07:39
2020-02-17T07:07:39
212,895,480
0
0
null
null
null
null
UTF-8
C++
false
false
598
cpp
#include "iostream" #include "vector" using namespace std; int main() { vector<int> vec; int len, i, j; cout << "Enter the length of the array.\n"; cin >> len; for( i = 0; i < len; i++) { int temp; cin >> temp; vec.push_back(temp); } for(i = 1; i < len; i++) { int mi = vec[i]; j = i - 1; while(j >= 0 && vec[j] > mi) { vec[j+1] = vec[j]; j--; } vec[j+1] = mi; } cout << "Answer\n"; for( i = 0; i < len; i++) { cout << vec[i] << " "; } }
[ "abhishek.raut.0104@gmail.com" ]
abhishek.raut.0104@gmail.com
0388b0fa0c446eada6d8b35a28fb289e7c69e1fb
b2b17137ed57902d1d0a652d9d7e7cbf97c097fb
/fila_dinamica_sentinela.cpp
a96feaa1c17228c5739a4217f49ba6dd48ae7e1c
[]
no_license
Viniciusvcr/filas_ed
d3ac1ef5db82eba417f0d2b4dbacfa610439d6f7
348b89280a9dd1e1311aa28c61e525bc29053f92
refs/heads/master
2020-03-11T19:42:19.936973
2018-04-26T23:28:44
2018-04-26T23:28:44
130,215,426
1
0
null
null
null
null
UTF-8
C++
false
false
3,620
cpp
#include <iostream> #include <stdlib.h> #include <stdio.h> using namespace std; typedef struct tipo_item{ int chave; }item; typedef struct tipo_celula{ struct tipo_item item; struct tipo_celula *prox; }celula; typedef struct tipo_fila{ struct tipo_celula *primeiro; struct tipo_celula *ultimo; }fila; void inicializa(fila* f){ f->primeiro = (celula*)malloc(sizeof(celula)); f->ultimo = f->primeiro; f->ultimo->prox = NULL; } int vazia(fila* f){ return f->primeiro->prox == NULL; } void insere_fila(fila* f, item x){ celula *novo = (celula*)malloc(sizeof(celula)); novo->item = x; novo->prox = f->ultimo->prox; f->ultimo->prox = novo; f->ultimo = novo; } int remove_fila(fila* f, item* retorno){ celula *aux; if(!vazia(f)){ aux = f->primeiro->prox; *retorno = aux->item; f->primeiro->prox = aux->prox; if(vazia(f)) f->ultimo = f->primeiro; free(aux); return 1; } return 0; } void inverte(fila* f){ //exercício 1 item x; if(!vazia(f)){ remove_fila(f, &x); inverte(f); insere_fila(f, x); } } void escreve(fila* f){ celula *aux = f->primeiro->prox; while(aux != NULL){ cout << aux->item.chave << " "; aux = aux->prox; } cout << endl; } item* get_first(fila* f){ //exercício 2 if(!vazia(f)){ item *ret = &(f->primeiro->prox->item); return ret; }else return NULL; } int esvazia_fila(fila* f){ //exercício 5 item x; if(!vazia(f)){ remove_fila(f, &x); return esvazia_fila(f); }else return 1; } int campos_frente(celula* ptr, int campo, int cont){ //exercício 6 if(ptr == NULL) return -1; // Esse retorno indica que o campo buscado não existe na fila else if(ptr->item.chave == campo) return cont; else return campos_frente(ptr->prox, campo, ++cont); } void clear_screen(){ system("cls"); } void pause_screen(){ system("pause"); cout << endl; } int main(){ fila A; int opt, campos; item insere, retorno, *ret; inicializa(&A); do{ fflush(stdin); clear_screen(); cout << "[1] Vazia?" << endl; cout << "[2] Inserir na fila" << endl; cout << "[3] Remove fila" << endl; cout << "[4] Mostra fila" << endl; cout << "[5] Inverte fila" << endl; cout << "[6] Mostra primeiro" << endl; cout << "[7] Esvazia fila" << endl; cout << "[8] Campos a frente" << endl; cin >> opt; switch(opt){ case 1: if(vazia(&A)) cout << "LISTA VAZIA" << endl; else cout << "LISTA NAO VAZIA" << endl; pause_screen(); break; case 2: clear_screen(); cout << "Digite o elemento que quer inserir: "; cin >> insere.chave; insere_fila(&A, insere); cout << "ELEMENTO INSERIDO COM SUCESSO" << endl; pause_screen(); break; case 3: if(remove_fila(&A, &retorno)) cout << retorno.chave << " EXCLUIDO COM SUCESSO" << endl; else cout << "ERRO NA OPERACAO" << endl; pause_screen(); break; case 4: cout << "FILA COMPLETA: "; escreve(&A); pause_screen(); break; case 5: inverte(&A); cout << "FILA INVERTIDA!" << endl << "NOVA FILA: "; escreve(&A); pause_screen(); break; case 6: ret = get_first(&A); if(ret != NULL) cout << "PRIMEIRO ELEMENTO: " << ret->chave << endl; else cout << "LISTA VAZIA" << endl; pause_screen(); break; case 7: if(esvazia_fila(&A)) cout << "FILA ESVAZIADA" << endl; pause_screen(); break; case 8: clear_screen(); cout << "Digite o item que quer consultar: "; cin >> campos; cout << "Elementos na frente de " << campos << ": " << campos_frente(A.primeiro->prox, campos, 0) << endl; pause_screen(); break; } }while(opt != 0); }
[ "viniciusvcr@hotmail.com" ]
viniciusvcr@hotmail.com
590fc80da2d709becf45cf702443f1f7c364775a
d7c2f96b3614118281a6fa9f776c173550dd72f1
/RayTracer/src/camera/Camera.h
19a0aed10cde48d9a47ca722d061a7c20b045cc4
[ "MIT" ]
permissive
Markus28/RayTracer
4bca8330e57b2a4864f74d6ec1cb9cacf529b587
a24ec31069ae6a61a45d3df6c02f2dcbb772c9b6
refs/heads/master
2021-08-09T11:34:11.333002
2020-05-08T18:02:28
2020-05-08T18:02:28
175,484,015
0
0
null
null
null
null
UTF-8
C++
false
false
631
h
#ifndef RAYTRACER_CAMERA_H #define RAYTRACER_CAMERA_H #include <vector> #include <string> #include "../Ray.h" namespace camera { using Image = std::vector<std::vector<Vector3D>>; class Camera { public: void set_pixel(unsigned int i, const Vector3D &c); virtual Ray ray_at(unsigned int i) const = 0; void write_file(std::string file_name) const; unsigned int length() const; virtual ~Camera() = default; protected: std::vector<Vector3D> pixels; unsigned int size; virtual Image post_process() const = 0; }; } #endif //RAYTRACER_CAMERA_H
[ "montcyril@gmail.com" ]
montcyril@gmail.com
652dbb569e74936bbde3fcf4aeb76c36a93511fc
0d3875b31c1989c1bd3199a6dd21530309689e98
/opengl/01_3d_tuxingxue/源码69063/source/lesson300-纹理/Raster.h
6561b8e4feb93081ed10fbd09b11ccbee7d5fbf1
[]
no_license
wrzfeijianshen/TL
00c4cf44e7217bb4d0d228f2eb5c3fc5dbab2e74
12032d5cd16c30bd7376e375fb3b2450d9720180
refs/heads/master
2021-04-27T00:10:26.488055
2018-12-19T06:04:22
2018-12-19T06:04:22
123,762,083
3
1
null
null
null
null
UTF-8
C++
false
false
6,905
h
#pragma once #include "CELLMath.hpp" #include "Image.hpp" namespace CELL { enum DRAWMODE { DM_POINTS = 0, DM_LINES = 1, DM_LINE_LOOP = 2, DM_LINE_STRIP = 3, }; class Span { public: int _xStart; int _xEnd; Rgba _colorStart; Rgba _colorEnd; float2 _uvStart; float2 _uvEnd; int _y; public: Span(int xStart,int xEnd,int y,Rgba colorStart,Rgba colorEnd,float2 uvStart,float2 uvEnd) { if (xStart < xEnd) { _xStart = xStart; _xEnd = xEnd; _colorStart = colorStart; _colorEnd = colorEnd; _uvStart = uvStart; _uvEnd = uvEnd; _y = y; } else { _xStart = xEnd; _xEnd = xStart; _colorStart = colorEnd; _colorEnd = colorStart; _uvStart = uvEnd; _uvEnd = uvStart; _y = y; } } }; class Ege { public: int _x1; int _y1; float2 _uv1; Rgba _color1; int _x2; int _y2; float2 _uv2; Rgba _color2; Ege(int x1,int y1,Rgba color1,float2 uv1,int x2,int y2,Rgba color2,float2 uv2) { if (y1 < y2) { _x1 = x1; _y1 = y1; _uv1 = uv1; _color1 = color1; _x2 = x2; _y2 = y2; _uv2 = uv2; _color2 = color2; } else { _x1 = x2; _y1 = y2; _uv1 = uv2; _color1 = color2; _x2 = x1; _y2 = y1; _uv2 = uv1; _color2 = color1; } } }; class Raster { public: uint* _buffer; int _width; int _height; Rgba _color; public: Raster(int w,int h,void* buffer); ~Raster(void); void clear(); struct Vertex { int2 p0; float2 uv0; Rgba c0; int2 p1; float2 uv1; Rgba c1; int2 p2; float2 uv2; Rgba c2; }; void drawImage(int startX,int startY,const Image* image) { int left = tmax<int>(startX,0); int top = tmax<int>(startY,0); int right = tmin<int>(startX + image->width(),_width); int bottom = tmin<int>(startY + image->height(),_height); for (int x = left ; x < right ; ++ x) { for (int y = top ; y < bottom ; ++ y) { Rgba color = image->pixelAt(x - left,y - top); setPixelEx(x,y,color); } } } public: void drawTriangle(const Vertex& vertex) { Ege eges[3] = { Ege(vertex.p0.x,vertex.p0.y,vertex.c0, vertex.uv0, vertex.p1.x,vertex.p1.y,vertex.c1, vertex.uv1), Ege(vertex.p1.x,vertex.p1.y,vertex.c1, vertex.uv1, vertex.p2.x,vertex.p2.y,vertex.c2, vertex.uv2), Ege(vertex.p2.x,vertex.p2.y,vertex.c2, vertex.uv2, vertex.p0.x,vertex.p0.y,vertex.c0, vertex.uv2), }; int iMax = 0; int length = eges[0]._y2 - eges[0]._y1; for (int i = 1 ;i < 3 ; ++ i) { int len = eges[i]._y2 - eges[i]._y1; if (len > length) { length = i; } } int iShort1 = (iMax + 1)%3; int iShort2 = (iMax + 2)%3; drawEge(eges[iMax],eges[iShort1]); drawEge(eges[iMax],eges[iShort2]); } void drawEge(const Ege& e1,const Ege& e2) { float yOffset1 = e1._y2 - e1._y1; if (yOffset1 == 0) { return; } float yOffset = e2._y2 - e2._y1; if (yOffset == 0) { return; } float xOffset = e2._x2 - e2._x1; float scale = 0; float step = 1.0f/yOffset; float xOffset1 = e1._x2 - e1._x1; float scale1 = (float)(e2._y1 - e1._y1)/yOffset1; float step1 = 1.0f/yOffset1; for (int y = e2._y1 ; y < e2._y2 ; ++ y) { int x1 = e1._x1 + (int)(scale1 * xOffset1); int x2 = e2._x1 + (int)(scale * xOffset); Rgba color2 = colorLerp(e2._color1,e2._color2,scale); Rgba color1 = colorLerp(e1._color1,e1._color2,scale1); float2 uvStart = uvLerp(e1._uv1,e1._uv2,scale1); float2 uvEnd = uvLerp(e2._uv1,e2._uv2,scale); Span span(x1,x2,y,color1,color2,uvStart,uvEnd); drawSpan(span); scale += step; scale1 += step1; } } void drawSpan(const Span& span) { float length = span._xEnd - span._xStart; float scale = 0; float step = 1.0f/length; for (int x = span._xStart ; x < span._xEnd; ++ x) { Rgba color = colorLerp( span._colorStart ,span._colorEnd ,scale ); scale += step; setPixel(x,span._y,color); } } void drawLine(float2 pt1,float2 pt2,Rgba color1,Rgba color2); void drawPoints(float2 pt1,Rgba4Byte color) { } inline void setPixelEx(unsigned x,unsigned y,Rgba color) { _buffer[y * _width + x] = color._color; } inline Rgba getPixel(unsigned x,unsigned y) { return Rgba(_buffer[y * _width + x]); } inline void setPixel(unsigned x,unsigned y,Rgba color) { if (x >= _width || y >= _height) { return; } _buffer[y * _width + x] = color._color; } }; }
[ "wrzfeijianshen@126.com" ]
wrzfeijianshen@126.com
fc1bb80ae08a1c40939874bb3fbe1a7a127d6bc1
3c158d991b00ea19cd9a929846812a61034edfbb
/labs/lab1/Compare/Compare/Compare1.cpp
7ffa5a73076819f7146bf2e03977f28e8b0c00d2
[]
no_license
Endhovian/ooplabs
91d32a8086ab2288a330c2a03816e114d906de0a
7f23124b638108d738b929fda39acac0f38d3ceb
refs/heads/master
2020-04-21T21:30:17.664564
2019-02-21T18:30:34
2019-02-21T18:30:34
169,880,930
0
0
null
null
null
null
UTF-8
C++
false
false
943
cpp
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { // Считывание информации из файлов string file1, file2, s1, s2; cin >> file1 >> file2; ifstream i1(file1), i2(file2); if (!i1 || !i2) { cout << "\"File not found\""; return 1; } // Обработка и вывод результата сравнения int m = 0; while (!i1.eof() && !i2.eof()) { getline(i1, s1); getline(i2, s2); n++; //проверка строк на равность if (s1 != s2) { cout << "\"Files are different. Line number is " << n << "\""; return 1; } //проверка на то что один из файлов закончился if ((i1.eof() == 0 && i2.eof() != 0) || (i2.eof() == 0 && i1.eof() != 0)) { n++; cout << "\"Files are different. Line number is " << n << "\""; return 1; } } cout << "\"Files are equal\""; return 0; }
[ "User@WIN-S65G2BF50S5" ]
User@WIN-S65G2BF50S5
97635d4453d4228aa5f8725d5faa2df5674b99f2
6149561f6b2c00335e8d9d09a1aeffad49e59422
/studyC++/回溯.cpp
d1b6d6c2203d866dca7d103126a6085dc3be006e
[]
no_license
Smartuil/Study-CPP
3196405f107de0762c2900d0dac89917b2183902
f646eab0a11c1fc8750fe608ce9c8f2360f3cf34
refs/heads/master
2022-11-29T02:28:10.759993
2020-07-29T07:05:11
2020-07-29T07:05:11
259,013,860
0
0
null
null
null
null
UTF-8
C++
false
false
541
cpp
#include<iostream> #include<cstdio> #define N 10 using namespace std; int n=2, y=3, tsum = 0; int ans[N] = {}; int a[N] = {1, 2}; void retrack(int i) { int k; if (i == n) { for (k = 0; k < n; ++k) printf("%d ", ans[k]); //cout << ans[k] << " "; printf("\n"); return; } int l = y / a[i]; for (k = 0; k <= l; ++k) { int t = k * a[i]; if (tsum + t <= y && tsum + t >= 0) { tsum += t; ans[i] = k; retrack(i + 1); tsum -= t; } else break; } } int main() { retrack(0); //system("pause"); return 0; }
[ "563412673@qq.com" ]
563412673@qq.com
7b792da87d0a206431b401558407811d80f7937c
e18a51c1bd1425f22db15700a88e8c66f3552d93
/packages/lagrangian/intermediateNew/parcels/Templates/CollidingParcel/CollidingParcel.H
5d6f6ca3e0ee6c44dcc9beb5e365a389c7b6ee55
[]
no_license
trinath2rao/fireFoam-2.2.x
6253191db406405683e15da2263d19f4b16181ba
5f28904ffd7e82a9a55cb3f67fafb32f8f889d58
refs/heads/master
2020-12-29T01:42:16.305833
2014-11-24T21:53:39
2014-11-24T21:53:39
34,248,660
1
0
null
2015-04-20T08:37:28
2015-04-20T08:37:27
null
UTF-8
C++
false
false
6,656
h
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011-2012 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Class Foam::CollidingParcel Description Wrapper around kinematic parcel types to add collision modelling SourceFiles CollidingParcelI.H CollidingParcel.C CollidingParcelIO.C \*---------------------------------------------------------------------------*/ #ifndef CollidingParcel_H #define CollidingParcel_H #include "particle.H" #include "CollisionRecordList.H" #include "labelFieldIOField.H" #include "vectorFieldIOField.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { typedef CollisionRecordList<vector, vector> collisionRecordList; typedef vectorFieldCompactIOField pairDataFieldCompactIOField; typedef vectorFieldCompactIOField wallDataFieldCompactIOField; template<class ParcelType> class CollidingParcel; // Forward declaration of friend functions template<class ParcelType> Ostream& operator<< ( Ostream&, const CollidingParcel<ParcelType>& ); /*---------------------------------------------------------------------------*\ Class CollidingParcel Declaration \*---------------------------------------------------------------------------*/ template<class ParcelType> class CollidingParcel : public ParcelType { protected: // Protected data //- Particle collision records collisionRecordList collisionRecords_; public: // Static data members //- Runtime type information TypeName("CollidingParcel"); //- String representation of properties AddToPropertyList ( ParcelType, " collisionRecordsPairAccessed" + " collisionRecordsPairOrigProcOfOther" + " collisionRecordsPairOrigIdOfOther" + " (collisionRecordsPairData)" + " collisionRecordsWallAccessed" + " collisionRecordsWallPRel" + " (collisionRecordsWallData)" ); // Constructors //- Construct from owner, position, and cloud owner // Other properties initialised as null inline CollidingParcel ( const polyMesh& mesh, const vector& position, const label cellI, const label tetFaceI, const label tetPtI ); //- Construct from components inline CollidingParcel ( const polyMesh& mesh, const vector& position, const label cellI, const label tetFaceI, const label tetPtI, const label typeId, const scalar nParticle0, const scalar d0, const scalar dTarget0, const vector& U0, const vector& f0, const vector& angularMomentum0, const vector& torque0, const typename ParcelType::constantProperties& constProps ); //- Construct from Istream CollidingParcel ( const polyMesh& mesh, Istream& is, bool readFields = true ); //- Construct as a copy CollidingParcel(const CollidingParcel& p); //- Construct as a copy CollidingParcel(const CollidingParcel& p, const polyMesh& mesh); //- Construct and return a (basic particle) clone virtual autoPtr<particle> clone() const { return autoPtr<particle>(new CollidingParcel(*this)); } //- Construct and return a (basic particle) clone virtual autoPtr<particle> clone(const polyMesh& mesh) const { return autoPtr<particle>(new CollidingParcel(*this, mesh)); } //- Factory class to read-construct particles used for // parallel transfer class iNew { const polyMesh& mesh_; public: iNew(const polyMesh& mesh) : mesh_(mesh) {} autoPtr<CollidingParcel<ParcelType> > operator()(Istream& is) const { return autoPtr<CollidingParcel<ParcelType> > ( new CollidingParcel<ParcelType>(mesh_, is, true) ); } }; // Member Functions // Access //- Return const access to the collision records inline const collisionRecordList& collisionRecords() const; //- Return access to collision records inline collisionRecordList& collisionRecords(); // Tracking //- Move the parcel template<class TrackData> bool move(TrackData& td, const scalar trackTime); // I-O //- Read template<class CloudType> static void readFields(CloudType& c); //- Write template<class CloudType> static void writeFields(const CloudType& c); // Ostream Operator friend Ostream& operator<< <ParcelType> ( Ostream&, const CollidingParcel<ParcelType>& ); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "CollidingParcelI.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository #include "CollidingParcel.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
[ "karl.meredith@fmglobal.com" ]
karl.meredith@fmglobal.com
fbd73d71ebee44f2e146b20b3236a16f9cb519f5
9ae39413391ae9ca70530cf22938169f1e08b7ea
/screensaver/snsrplugins/snsrbigclockscreensaverplugin/src/snsranalogclockcontainer.cpp
4bb81669bde2288325cdbac0ecee77ebe0dc247a
[]
no_license
SymbianSource/oss.FCL.sf.app.homescreen
1bde9a48b6e676706eb136069226fa1a9a12ae9d
61d721e71cc55557a6ad9c5ae066f07302c87aa2
refs/heads/master
2020-12-20T19:11:40.431784
2010-10-20T12:25:39
2010-10-20T12:25:39
65,833,139
0
0
null
null
null
null
UTF-8
C++
false
false
5,216
cpp
/* * Copyright (c) 2009-2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Container for analog clock. * */ #include "snsranalogclockcontainer.h" #include <QDebug> #include <QTime> #include <QGraphicsLinearLayout> #include <HbExtendedLocale> #include <HbMainWindow> #include <HbPushButton> #include "snsranalogclockwidget.h" #include "snsrindicatorwidget.h" #include "snsrlabel.h" /*! \class SnsrAnalogClockContainer \ingroup group_snsrbigclockscreensaverplugin \brief Container used for preparing layout for analog clock. */ const char *gAnalogLayoutDocml = ":/xml/snsrbigclockscreensaveranalog.docml"; const char *gUnlockAnalogLayoutDocml = ":/xml/snsrbigclockscreensaveranalogunlockbutton.docml"; const char *gPortraitSectionName = "portrait"; const char *gLandscapeSectionName = "landscape"; const char *gMainViewName = "view"; const char *gMainContainerName = "mainContainer"; const char *gClockContainerName = "clockContainer"; const char *gDateLabelName = "dateLabel"; const char *gAnalogClockWidgetName = "analogClockWidget"; const char *gIndicatorWidgetName = "indicatorWidget"; const char *gUnlockButtonName = "unlockButton"; const char *gDateFormatStr = r_qtn_date_usual_with_zero; //"%E%,% %*D%*N%/0%4%/1%5"; /*! Constructs a new SnsrAnalogClockContainer. */ SnsrAnalogClockContainer::SnsrAnalogClockContainer() : SnsrBigClockContainer(), mDateLabel(0), mAnalogClockWidget(0), mUnlockButton(0) { SCREENSAVER_TEST_FUNC_ENTRY("SnsrAnalogClockContainer::SnsrAnalogClockContainer") SCREENSAVER_TEST_FUNC_EXIT("SnsrAnalogClockContainer::SnsrAnalogClockContainer") } /*! Destructs the class. */ SnsrAnalogClockContainer::~SnsrAnalogClockContainer() { resetIndicatorConnections(); //mDateLabel, mAnalogClockWidget - deleted by the parent } /*! Updates displayed time and date. */ void SnsrAnalogClockContainer::update() { SCREENSAVER_TEST_FUNC_ENTRY("SnsrAnalogClockContainer::update") // time mAnalogClockWidget->tick(); // date mDateLabel->setPlainText( HbExtendedLocale().format(QDate::currentDate(), gDateFormatStr) ); SCREENSAVER_TEST_FUNC_EXIT("SnsrAnalogClockContainer::update") } /*! @copydoc SnsrBigClockContainer::updateIntervalInMilliseconds() */ int SnsrAnalogClockContainer::updateIntervalInMilliseconds() { return 1000; } /*! @copydoc SnsrBigClockContainer::loadWidgets() */ void SnsrAnalogClockContainer::loadWidgets() { //if unlockbutton is used we load the docml file containing it if ( unlockButtonSupported() ) { loadWidgets(gUnlockAnalogLayoutDocml); Q_ASSERT_X( mUnlockButton, gUnlockAnalogLayoutDocml, "unlock button not found in DocML file."); mUnlockButton->setText("Unlock"); connect( mUnlockButton, SIGNAL(clicked()), SIGNAL(unlockRequested()) ); } else { loadWidgets(gAnalogLayoutDocml); } } /*! Instantiate widgets from the given docml file */ void SnsrAnalogClockContainer::loadWidgets(const char* docmlName) { bool ok(true); // reset widget pointers, any previous widgets are already deleted by now mMainView = 0; mDateLabel = 0; mAnalogClockWidget = 0; mIndicatorWidget = 0; mUnlockButton = 0; // load widgets from docml qDebug() << docmlName; mDocumentObjects = mDocumentLoader.load(docmlName, &ok); Q_ASSERT_X(ok, docmlName, "Invalid DocML file."); if (ok) { mMainView = mDocumentLoader.findWidget(gMainViewName); mDateLabel = qobject_cast<SnsrLabel *>( mDocumentLoader.findWidget(gDateLabelName)); mAnalogClockWidget = qobject_cast<SnsrAnalogClockWidget *>( mDocumentLoader.findWidget(gAnalogClockWidgetName)); mIndicatorWidget = qobject_cast<SnsrIndicatorWidget *>( mDocumentLoader.findWidget(gIndicatorWidgetName)); mUnlockButton = qobject_cast<HbPushButton *>( mDocumentLoader.findWidget(gUnlockButtonName)); Q_ASSERT_X( mMainView && mDateLabel && mAnalogClockWidget && mIndicatorWidget, docmlName, "Objects not found in DocML file." ); // In case of landscape layout, read also the landscape delta section if ( mCurrentOrientation == Qt::Horizontal ) { qDebug() << "loading: " << docmlName << ", section: " << gLandscapeSectionName; mDocumentLoader.load(docmlName, gLandscapeSectionName, &ok); Q_ASSERT_X(ok, docmlName, "Invalid section in DocML file."); } mIndicatorWidget->setIconColorType(SnsrIndicatorWidget::ThemedColorForActiveMode); connectIndicatorWidgetToModel(); mDateLabel->setTextColorType(SnsrLabel::ThemedColorForActiveMode); mBackgroundContainerLayout->addItem(mMainView); } }
[ "none@none" ]
none@none
c0de8bd6d355d8bfca763359c9ccfe7ccab1288c
9796cc92a203b4180a1e6de75f5b5160927deef3
/project/runcascade/rectangles.cpp
4aaa43fd2fa77bc05cf3b2a761f7670316fa62b8
[]
no_license
tejashah94/red_ninjas
208244cf1583f46032a2836b297506763ea5bc59
e035e708a5877a341d4d0e39cd1acfa079e408cd
refs/heads/master
2021-04-11T19:26:35.891961
2016-04-01T20:52:32
2016-04-01T20:52:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,065
cpp
#include "haar.h" int partition(std::vector<MyRect>& _vec, std::vector<int>& labels, float eps); int myMax(int a, int b) { if (a >= b) return a; else return b; } int myMin(int a, int b) { if (a <= b) return a; else return b; } inline int myRound( float value ) { return (int)(value + (value >= 0 ? 0.5 : -0.5)); } int myAbs(int n) { if (n >= 0) return n; else return -n; } int predicate(float eps, MyRect& r1, MyRect& r2) { float delta = eps*(myMin(r1.width, r2.width) + myMin(r1.height, r2.height))*0.5; return myAbs(r1.x - r2.x) <= delta && myAbs(r1.y - r2.y) <= delta && myAbs(r1.x + r1.width - r2.x - r2.width) <= delta && myAbs(r1.y + r1.height - r2.y - r2.height) <= delta; } void groupRectangles(std::vector<MyRect>& rectList, int groupThreshold, float eps) { if( groupThreshold <= 0 || rectList.empty() ) return; std::vector<int> labels; int nclasses = partition(rectList, labels, eps); std::vector<MyRect> rrects(nclasses); std::vector<int> rweights(nclasses); int i, j, nlabels = (int)labels.size(); for( i = 0; i < nlabels; i++ ) { int cls = labels[i]; rrects[cls].x += rectList[i].x; rrects[cls].y += rectList[i].y; rrects[cls].width += rectList[i].width; rrects[cls].height += rectList[i].height; rweights[cls]++; } for( i = 0; i < nclasses; i++ ) { MyRect r = rrects[i]; float s = 1.f/rweights[i]; rrects[i].x = myRound(r.x*s); rrects[i].y = myRound(r.y*s); rrects[i].width = myRound(r.width*s); rrects[i].height = myRound(r.height*s); } rectList.clear(); for( i = 0; i < nclasses; i++ ) { MyRect r1 = rrects[i]; int n1 = rweights[i]; if( n1 <= groupThreshold ) continue; /* filter out small face rectangles inside large rectangles */ for( j = 0; j < nclasses; j++ ) { int n2 = rweights[j]; /********************************* * if it is the same rectangle, * or the number of rectangles in class j is < group threshold, * do nothing ********************************/ if( j == i || n2 <= groupThreshold ) continue; MyRect r2 = rrects[j]; int dx = myRound( r2.width * eps ); int dy = myRound( r2.height * eps ); if( i != j && r1.x >= r2.x - dx && r1.y >= r2.y - dy && r1.x + r1.width <= r2.x + r2.width + dx && r1.y + r1.height <= r2.y + r2.height + dy && (n2 > myMax(3, n1) || n1 < 3) ) break; } if( j == nclasses ) { rectList.push_back(r1); // insert back r1 } } } int partition(std::vector<MyRect>& _vec, std::vector<int>& labels, float eps) { int i, j, N = (int)_vec.size(); MyRect* vec = &_vec[0]; const int PARENT=0; const int RANK=1; std::vector<int> _nodes(N*2); int (*nodes)[2] = (int(*)[2])&_nodes[0]; /* The first O(N) pass: create N single-vertex trees */ for(i = 0; i < N; i++) { nodes[i][PARENT]=-1; nodes[i][RANK] = 0; } /* The main O(N^2) pass: merge connected components */ for( i = 0; i < N; i++ ) { int root = i; /* find root */ while( nodes[root][PARENT] >= 0 ) root = nodes[root][PARENT]; for( j = 0; j < N; j++ ) { if( i == j || !predicate(eps, vec[i], vec[j])) continue; int root2 = j; while( nodes[root2][PARENT] >= 0 ) root2 = nodes[root2][PARENT]; if( root2 != root ) { /* unite both trees */ int rank = nodes[root][RANK], rank2 = nodes[root2][RANK]; if( rank > rank2 ) nodes[root2][PARENT] = root; else { nodes[root][PARENT] = root2; nodes[root2][RANK] += rank == rank2; root = root2; } int k = j, parent; /* compress the path from node2 to root */ while( (parent = nodes[k][PARENT]) >= 0 ) { nodes[k][PARENT] = root; k = parent; } /* compress the path from node to root */ k = i; while( (parent = nodes[k][PARENT]) >= 0 ) { nodes[k][PARENT] = root; k = parent; } } } } /* Final O(N) pass: enumerate classes */ labels.resize(N); int nclasses = 0; for( i = 0; i < N; i++ ) { int root = i; while( nodes[root][PARENT] >= 0 ) root = nodes[root][PARENT]; /* re-use the rank as the class label */ if( nodes[root][RANK] >= 0 ) nodes[root][RANK] = ~nclasses++; labels[i] = ~nodes[root][RANK]; } return nclasses; } /* draw white bounding boxes around detected faces */ void drawRectangle(MyImage* image, MyRect r) { int i; int col = image->width; for (i = 0; i < r.width; i++) { image->data[col*r.y + r.x + i] = 255; } for (i = 0; i < r.height; i++) { image->data[col*(r.y+i) + r.x + r.width] = 255; } for (i = 0; i < r.width; i++) { image->data[col*(r.y + r.height) + r.x + r.width - i] = 255; } for (i = 0; i < r.height; i++) { image->data[col*(r.y + r.height - i) + r.x] = 255; } }
[ "vinayg@euler.wacc.wisc.edu" ]
vinayg@euler.wacc.wisc.edu
0df648c2284705dcc80320176dd9f1f377074fa6
7e1107c4995489a26c4007e41b53ea8d00ab2134
/game/code/input/mapper.cpp
107749fbb55f5a337a999c00c302d297c2284fbf
[]
no_license
Svxy/The-Simpsons-Hit-and-Run
83837eb2bfb79d5ddb008346313aad42cd39f10d
eb4b3404aa00220d659e532151dab13d642c17a3
refs/heads/main
2023-07-14T07:19:13.324803
2023-05-31T21:31:32
2023-05-31T21:31:32
647,840,572
591
45
null
null
null
null
UTF-8
C++
false
false
752
cpp
#include <input/mapper.h> #include <input/mappable.h> Mapper::Mapper( void ) { ClearAssociations( ); } int Mapper::SetAssociation( int sourceButtonID, int destButtonID ) { buttonMap[sourceButtonID] = destButtonID; return 0; } int Mapper::GetLogicalIndex( int sourceButtonID ) const { return buttonMap[sourceButtonID]; } int Mapper::GetPhysicalIndex( int destButtonID ) const { for ( unsigned i = 0; i < Input::MaxLogicalButtons; i++ ) { if ( buttonMap[i] == destButtonID) { return i; } } return Input::INVALID_CONTROLLERID; } void Mapper::ClearAssociations( void ) { for( unsigned int i = 0; i < Input::MaxLogicalButtons; i++) { buttonMap[i] = Input::INVALID_CONTROLLERID; } }
[ "aidan61605@gmail.com" ]
aidan61605@gmail.com
55d1a9f3ed8b483fba32db6361a187603d3c5dc6
17e0b7775f3a1b429225a405a327d137710bec59
/TryoneTry/Intermediate/Build/Win64/TryoneTry/Development/MoviePlayer/Module.MoviePlayer.gen.cpp
4eb226441e07587e4ec9638d6182d85e2cf5ec8e
[]
no_license
JTY1997/Learning-UE4
923d2cbfe95dec25a9dfe6ca2f36bc67e6203bd3
ed5fcedf3aa35887e5bde1fe67fd4be0b1a7ce29
refs/heads/main
2023-01-31T22:32:04.289755
2020-12-17T15:32:55
2020-12-17T15:32:55
303,879,097
0
0
null
null
null
null
UTF-8
C++
false
false
456
cpp
// This file is automatically generated at compile-time to include some subset of the user-created cpp files. #include "D:/Unreal Projects/TryoneTry/Intermediate/Build/Win64/TryoneTry/Inc/MoviePlayer/MoviePlayer.gen.cpp" #include "D:/Unreal Projects/TryoneTry/Intermediate/Build/Win64/TryoneTry/Inc/MoviePlayer/MoviePlayer.init.gen.cpp" #include "D:/Unreal Projects/TryoneTry/Intermediate/Build/Win64/TryoneTry/Inc/MoviePlayer/MoviePlayerSettings.gen.cpp"
[ "52436054+JTY1997@users.noreply.github.com" ]
52436054+JTY1997@users.noreply.github.com
a3d1e890207af81042d03b4fa52fb4e9feaccf01
1b9ccb920c5ae5fbedb2fa06685da1f0bc88714f
/MCP23017/examples/Arduino/button.ino
1ffff28cde8cf06a5e88e6d50d9ab1fb7d7f72c9
[]
no_license
infusion/I2C
c4211466e0de87945411736d3ee9c0cbb7358e4e
75770fbeb4a6f075bcaddd203d1411e75ce6a179
refs/heads/master
2022-12-04T16:53:08.950187
2022-11-22T12:29:43
2022-11-22T12:29:43
90,730,527
0
0
null
null
null
null
UTF-8
C++
false
false
291
ino
#include <MCP23017.h> MCP23017 io; void setup() { io.init(); io.setPinMode(6, INPUT); io.setPullUpMode(6, HIGH); // turn on 100K pullup internally pinMode(13, OUTPUT); // use the board LED for debugging } void loop() { digitalWrite(13, io.isPinHigh(6)); delay(10); }
[ "robert@xarg.org" ]
robert@xarg.org
97fa654f2807c830bd91bc7eeeb0a72cfa35f8ed
9661cbc0f5165f8e1f531358202f522cf14de78e
/Activities_2_Solution/src/AA1_03/Sack.h
74e9b53a0c6cba9fbb03ba5bf9ce0f5f1114d1a5
[]
no_license
JoanMesalles/Activities_2ndo
f4e435ba023505d6b27747e53e3bcca22f7b8a14
ef84252611a2232fd03511eff5e5569c6676ed09
refs/heads/master
2023-02-16T13:32:14.274404
2021-01-14T17:14:09
2021-01-14T17:14:09
300,218,948
0
0
null
null
null
null
UTF-8
C++
false
false
393
h
#pragma once #include "Collisions.h" class Sack { Rect position; Rect frame; public: Sack(); Sack(int textWidth, int textHeight, int posx, int posy); const Rect* GetPosition() { return &position; }; const Rect* GetFrame() { return &frame; }; Vec2D GetPositionInVect() { return Vec2D(position.x, position.y); }; void SetPosition(Vec2D v) { position.x = v.x; position.y = v.y;}; };
[ "joan.mesalles@enti.cat" ]
joan.mesalles@enti.cat
938e24957180418b5f60d1d0848cfab68de7bdb2
94e76218c0a2184487dc2b9e07fdc0da8dc3cdcf
/XxharCs/Aimbot.cpp
7195f4e4c0a7699a5d1d9de4499005f5892079c2
[]
no_license
kingking888/6382
cb80016d897d47611c68122303406582e5f66144
f9cf2dfffad3a67b8fb5b921c034d4d9f63cea93
refs/heads/master
2022-01-06T18:29:31.190247
2018-06-17T03:04:06
2018-06-17T03:04:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,324
cpp
//============================================================================== // Aimbot.cpp //============================================================================== #define WIN32_LEAN_AND_MEAN #pragma warning(disable:4786) #pragma warning(disable:4305) #pragma warning(disable:4800) #pragma warning(disable:4244) #pragma warning(disable:4101) #pragma warning(disable:4715) #include <windows.h> #include <stdlib.h> #include <math.h> #undef NDEBUG #include <assert.h> #include <memory.h> #include <map> #include <vector> #include <fstream> #include "gamehooking.h" #include "aimbot.h" #include "cvars.h" #include "players.h" #include "weaponlist.h" #include "./drawing/drawing.h" using namespace std; typedef float TransformMatrix[MAXSTUDIOBONES][3][4]; #define M_PI 3.14159265358979323846 CAimbot Aimbot; float mainViewOrigin[3]; //=================================================================================== float predahead = 0.20; // Some default Values ;D int predback = 0; static void PredictTarget(int index,float *pred) { // if (cvar.pred) // { /* cl_entity_s* ent = gEngfuncs.GetEntityByIndex(index); int historyIndex = (ent->current_position+HISTORY_MAX-predback)%HISTORY_MAX; vec3_t vFromOrigin , vToOrigin , vDeltaOrigin,vPredictedOrigin; vFromOrigin = ent->ph[historyIndex].origin; vToOrigin = ent->ph[ent->current_position].origin; vDeltaOrigin = vToOrigin - vFromOrigin; vDeltaOrigin[0] *= predahead; vDeltaOrigin[1] *= predahead; vDeltaOrigin[2] *= predahead; vPredictedOrigin = ent->origin + vDeltaOrigin; VectorCopy(vPredictedOrigin,pred); */ cl_entity_s* ent = gEngfuncs.GetEntityByIndex(index); VectorCopy(ent->origin, pred); /* } else { VectorCopy(g_playerList[index].getEnt()->origin,pred); }*/ } //============================================================================== float vpreahead = 1.2; bool bSoonvisible(int iIndex) { float to[3], lastpred = predahead; predahead = vpreahead;// apply some leeb value here :) PredictTarget(iIndex,(float*)to); predahead = lastpred; pmtrace_t tr; gEngfuncs.pEventAPI->EV_SetTraceHull( 2 ); gEngfuncs.pEventAPI->EV_PlayerTrace( g_local.pmEyePos, to, PM_WORLD_ONLY, g_local.ent->index, &tr ); // return ( tr.fraction == 1.0 ); if (tr.fraction == 0.75 ) return true; return false; } //============================================================================== /* void VectorAngles( const float *forward, float *angles ) { float tmp, yaw, pitch; if( forward[1] == 0 && forward[0] == 0 ) { yaw = 0; if( forward[2] > 0 ) pitch = 90.0f; else pitch = 270.0f; } else { yaw = ( float )( ( atan2( forward[1], forward[0] ) * 180 / M_PI ) ); if( yaw < 0 ) yaw += 360.0f; tmp = sqrt( forward[0] * forward[0] + forward[1] * forward[1] ); pitch = ( float )( ( atan2( forward[2], tmp ) * 180 / M_PI ) ); } angles[0] = pitch; angles[1] = yaw; angles[2] = 0; } */ //============================================================================== int CanPenetrate( float *start, float *end, int power ) { pmtrace_t pmtrace; pmtrace_t * tr = (pmtrace_t*) &pmtrace; float view[3]; float dir[3]; view[0] = end[0] - start[0]; view[1] = end[1] - start[1]; view[2] = end[2] - start[2]; float length = VectorLength(view); dir[0] = view[0] / length; dir[1] = view[1] / length; dir[2] = view[2] / length; float position[3]; position[0] = start[0]; position[1] = start[1]; position[2] = start[2]; tr->startsolid = true; while( power ) { if( !tr->startsolid ) power--; tr = gEngfuncs.PM_TraceLine( position, end, PM_TRACELINE_PHYSENTSONLY, 2, -1); if( tr->fraction==1.0f ) return 1; if( tr->allsolid ) return 0; position[0] = tr->endpos[0] + dir[0] * 8.0f; position[1] = tr->endpos[1] + dir[1] * 8.0f; position[2] = tr->endpos[2] + dir[2] * 8.0f; } return 0; } //============================================================================== void VectorTransform (float *in1, float in2[3][4], float *out) { out[0] = DotProduct(in1, in2[0]) + in2[0][3]; out[1] = DotProduct(in1, in2[1]) + in2[1][3]; out[2] = DotProduct(in1, in2[2]) + in2[2][3]; } //============================================================================== void CAimbot::DrawAimSpot(void) { //if(!cvar.avdraw) return; for(int i = 0; i < 32; i++) { if(!g_playerList[i].bDrawn || !g_playerList[i].isUpdatedAddEnt()) continue; float fVecScreen[2]; vec3_t vecEnd, up, right, forward, EntViewOrg, playerAngles; if (!g_playerList[i].fixHbAim) {VectorCopy(g_playerList[i].vHitbox,EntViewOrg);} else {VectorCopy(g_playerList[i].origin(),EntViewOrg);} // calculate angle vectors playerAngles[0]=0; playerAngles[1]=g_playerList[iTarget].getEnt()->angles[1]; playerAngles[2]=0; gEngfuncs.pfnAngleVectors (playerAngles, forward, right, up); forward[2] = -forward[2]; EntViewOrg = EntViewOrg + forward * 0.5; EntViewOrg = EntViewOrg + up * 2.5; EntViewOrg = EntViewOrg + right * 0.0; if(!CalcScreen(EntViewOrg, fVecScreen)) continue; tintArea(fVecScreen[0], fVecScreen[1], 2, 2, 255, 255, 255, 255); } } void CAimbot::CalculateHitbox( cl_entity_s *pEnt ) { /*if( !cvar.aimingmethod ) return;*/ /*if(cvar.aimingmethod == 1) {*/ if( !g_playerList[pEnt->index].bGotHead ) { int iIndex = pEnt->index; model_s *pModel = pStudio->SetupPlayerModel( iIndex ); studiohdr_t *pStudioHeader = ( studiohdr_t* )pStudio->Mod_Extradata( pModel ); mstudiobbox_t *pStudioBox; TransformMatrix *pBoneTransform = ( TransformMatrix* )pStudio->StudioGetBoneTransform( ); vec3_t vMin, vMax; pStudioBox = ( mstudiobbox_t* )( ( byte* )pStudioHeader + pStudioHeader->hitboxindex ); //Head 11 bone 7 | Low Head 9 bone 5 | Chest 8 bone 4 | Stomach 7 bone 3 int i = 11; VectorTransform(pStudioBox[i].bbmin, (*pBoneTransform)[pStudioBox[i].bone], vMin); VectorTransform(pStudioBox[i].bbmax, (*pBoneTransform)[pStudioBox[i].bone], vMax); g_playerList[iIndex].vHitbox = ( vMin + vMax ) * 0.5f; g_playerList[iIndex].bGotHead = true; } /*}*/ /*if(cvar.aimingmethod == 2) { int ax = pEnt->index; if(!g_playerList[ax].bGotHead) { vec3_t pos; // studiohdr_t* pStudioHeader = (studiohdr_t*)oEngStudio.Mod_Extradata( pEnt->model ); TransformMatrix* pbonetransform = (TransformMatrix*)pStudio->StudioGetBoneTransform(); //Head 11 bone 7 | Low Head 9 bone 5 | Chest 8 bone 4 | Stomach 7 bone 3 int i = 7; if (cvar.aimspot == 1) i = 7; else if (cvar.aimspot == 2) i = 5; else if (cvar.aimspot == 3) i = 4; pos[ 0 ] = (*pbonetransform)[ i ][ 0 ][ 3 ]; pos[ 1 ] = (*pbonetransform)[ i ][ 1 ][ 3 ]; pos[ 2 ] = (*pbonetransform)[ i ][ 2 ][ 3 ]; VectorCopy(pos, g_playerList[ax].vHitbox); g_playerList[ax].bGotHead = true; } }*/ } //============================================================================== void CAimbot::CalculateAimingView( void ) { float view[3]; vec3_t vecEnd, up, right, forward, EntViewOrg, playerAngles; if (!g_playerList[iTarget].fixHbAim) {VectorCopy(g_playerList[iTarget].vHitbox,EntViewOrg);} else {VectorCopy(g_playerList[iTarget].origin(),EntViewOrg);} // calculate angle vectors playerAngles[0]=0; playerAngles[1]=g_playerList[iTarget].getEnt()->angles[1]; playerAngles[2]=0; gEngfuncs.pfnAngleVectors (playerAngles, forward, right, up); forward[2] = -forward[2]; EntViewOrg = EntViewOrg + forward * 0.5; EntViewOrg = EntViewOrg + up * 2.5; EntViewOrg = EntViewOrg + right * 0.0; view[0] = EntViewOrg[0] - g_local.pmEyePos[0]; view[1] = EntViewOrg[1] - g_local.pmEyePos[1]; view[2] = EntViewOrg[2] - g_local.pmEyePos[2]; VectorAngles(view,aim_viewangles); aim_viewangles[0] *= -1; if (aim_viewangles[0]>180) aim_viewangles[0]-=360; if (aim_viewangles[1]>180) aim_viewangles[1]-=360; } //============================================================================== int CorrectGunX() { int currentWeaponID = GetCurWeaponID(); if (currentWeaponID == WEAPONLIST_SG550 || currentWeaponID == WEAPONLIST_G3SG1 || currentWeaponID == WEAPONLIST_SCOUT || currentWeaponID == WEAPONLIST_AWP) { return 3; } if (currentWeaponID == WEAPONLIST_AUG || currentWeaponID == WEAPONLIST_UNKNOWN1 || currentWeaponID == WEAPONLIST_UNKNOWN2 || currentWeaponID == WEAPONLIST_DEAGLE || currentWeaponID == WEAPONLIST_SG552 || currentWeaponID == WEAPONLIST_AK47) { return 2; } { return 1; } } //==================================================================================== bool CAimbot::pathFree(float* xfrom,float* xto) { int pathtest; pmtrace_t tr; gEngfuncs.pEventAPI->EV_SetTraceHull( 2 ); gEngfuncs.pEventAPI->EV_PlayerTrace( xfrom, xto, PM_GLASS_IGNORE, g_local.ent->index, &tr ); pathtest = (tr.fraction == 1.0); if (!pathtest && CorrectGunX()) { pathtest = CanPenetrate(xfrom, xto, CorrectGunX()); } return pathtest; } //==================================================================================== bool CAimbot::TargetRegion(int ax) { vec3_t vecEnd, up, right, forward, EntViewOrg,playerAngles; cl_entity_s* ent = g_playerList[ax].getEnt(); // calculate angle vectors playerAngles[0]=0; playerAngles[1]=ent->angles[1]; playerAngles[2]=0; gEngfuncs.pfnAngleVectors (playerAngles, forward, right, up); forward[2] = -forward[2]; if (g_playerList[ax].bGotHead) {VectorCopy(g_playerList[ax].vHitbox,EntViewOrg);g_playerList[ax].fixHbAim=false;} else {VectorCopy(g_playerList[ax].origin(),EntViewOrg);g_playerList[ax].fixHbAim=true;} EntViewOrg = EntViewOrg + forward * 0.5; EntViewOrg = EntViewOrg + up * 2.5; EntViewOrg = EntViewOrg + right * 0.0; if(pathFree(g_local.pmEyePos,EntViewOrg) || pathFree(g_local.pmEyePos, ent->origin)) return true; return false; } //============================================================================== /* bool isValidEnt(cl_entity_s *ent) { if(ent && (ent != gEngfuncs.GetLocalPlayer()) && ent->player && !ent->curstate.spectator && ent->curstate.solid && !(ent->curstate.messagenum < gEngfuncs.GetLocalPlayer()->curstate.messagenum)) return true; else return false; }*/ //============================================================================== void CAimbot::FindTarget( void ) { if (!g_local.alive) return; SetTarget(-1); for (int ax=0;ax<MAX_VPLAYERS;ax++) { if ( g_playerList[ax].isUpdatedAddEnt() && g_playerList[ax].canAim && g_playerList[ax].isAlive()) // No Dead People { if( !HasTarget() ) { SetTarget(ax); continue; } if( g_playerList[ax].fovangle < g_playerList[iTarget].fovangle ) { SetTarget(ax); } } } } //============================================================================== float CAimbot::calcFovAngle(const float* origin_viewer, const float* angle_viewer, const float* origin_target) { double vec[3], view[3]; double dot; view[0] = origin_target[0] - origin_viewer[0]; view[1] = origin_target[1] - origin_viewer[1]; view[2] = origin_target[2] - origin_viewer[2]; dot = sqrt(view[0] * view[0] + view[1] * view[1] + view[2] * view[2]); dot = 1/dot; vec[0] = view[0] * dot; vec[1] = view[1] * dot; vec[2] = view[2] * dot; view[0] = sin((angle_viewer[1] + 90) * (M_PI / 180)); view[1] = -cos((angle_viewer[1] + 90) * (M_PI / 180)); view[2] = -sin( angle_viewer[0] * (M_PI / 180)); dot = view[0] * vec[0] + view[1] * vec[1] + view[2] * vec[2]; // dot to angle: return (float)((1.0-dot)*180.0); } //============================================================================== bool CAimbot::CheckTeam(int ax) { if (g_local.team != g_playerList[ax].team) return true; return false; } bool bAim = false; char* gGetWeaponName( int weaponmodel ); int DoHLHAiming(int eventcode) { char *szWeapon; UpdateMe(); szWeapon = gGetWeaponName(g_local.ent->curstate.weaponmodel); if(strstr(szWeapon, "nade") || strstr(szWeapon, "c4") || strstr(szWeapon, "flashbang")) return 1; if (eventcode == 1) { bAim = true; gEngfuncs.pfnClientCmd("+attack"); return 0; } else { bAim = false; gEngfuncs.pfnClientCmd("-attack"); return 1; } } //============================================================================== /*extern float gSpeed; int DoSpeed(int eventcode) { if (eventcode == 1) { if (cvar.knivespeed && IsCurWeaponKnife()) gSpeed = 20.0f; else gSpeed = cvar.speed; } else gSpeed = 0.0; return 0; }*/ //============================================================================== int getSeqInfo(int ax); bool CAimbot::IsShielded(int ax) { int seqinfo = getSeqInfo(ax); if (seqinfo & SEQUENCE_RELOAD) return false; if (seqinfo & SEQUENCE_SHIELD) return true; return false; } //============================================================================== void CAimbot::calcFovangleAndVisibility(int ax) { PlayerInfo& r = g_playerList[ax]; r.fovangle = calcFovAngle(g_local.pmEyePos, g_local.viewAngles, r.origin() ); if(r.updateType() == 0 || r.updateType() == 2 || !r.isAlive()) { r.visible = false; return; } float fov = 90; //1=10 , 2=30 , 3=90 , 4=360 r.visible = TargetRegion(ax); if(0) {} else if (!CheckTeam(ax)) { r.canAim = 0; } else if (IsShielded(ax)) { r.canAim = 0; } else if (r.fovangle>fov) { r.canAim = 0; } else if (bSoonvisible(ax)) { r.canAim = 1; } /*else if (cvar.autowall) { int damage = GetDamageVec(ax, true); if (damage) { r.canAim = 2; } else { damage = GetDamageVec(ax, false); if (damage) r.canAim = 1; else r.canAim = 0; } }*/ else { r.canAim = r.visible; } } //============================================================================== int CAimbot::GetDamageVec(int ax, bool onlyvis) { int hitdamage, penetration = WALL_PEN0; vec3_t vecEnd, up, right, forward, EntViewOrg, PlayerOrigin, playerAngles, targetspot; VectorCopy(g_playerList[ax].vHitbox,PlayerOrigin); playerAngles[0]=0; playerAngles[1]=g_playerList[ax].getEnt()->angles[1]; playerAngles[2]=0; gEngfuncs.pfnAngleVectors(playerAngles, forward, right, up); forward[2] = -forward[2]; if (!onlyvis) penetration = CorrectGunX(); targetspot[0] = PlayerOrigin[0] + up[0] * 2.5 + forward[0] * 0.5 + right[0] * 0.0; targetspot[1] = PlayerOrigin[1] + up[1] * 2.5 + forward[1] * 0.5 + right[1] * 0.0; targetspot[2] = PlayerOrigin[2] + up[2] * 2.5 + forward[2] * 0.5 + right[2] * 0.0; hitdamage = CanPenetrate(g_local.pmEyePos, targetspot, penetration); if (hitdamage > 0) return hitdamage; return 0; } //============================================================================== #define SPIN_REVS_PER_SECOND 6.0f // adjust to taste void CAimbot::FixupAngleDifference(usercmd_t *usercmd) { // thanks tetsuo for this copy/paste cl_entity_t *pLocal; Vector viewforward, viewright, viewup, aimforward, aimright, aimup, vTemp; float newforward, newright, newup, newmagnitude, fTime; float forward = g_Originalcmd.forwardmove; float right = g_Originalcmd.sidemove; float up = g_Originalcmd.upmove; pLocal = gEngfuncs.GetLocalPlayer(); if(!pLocal) return; // this branch makes sure your horizontal velocity is not affected when fixing up the movement angles -- it isn't specific to spinning and you can use it with the source tetsuo posted in his forum too if(pLocal->curstate.movetype == MOVETYPE_WALK) { gEngfuncs.pfnAngleVectors(Vector(0.0f, g_Originalcmd.viewangles.y, 0.0f), viewforward, viewright, viewup); } else { gEngfuncs.pfnAngleVectors(g_Originalcmd.viewangles, viewforward, viewright, viewup); } // SPIN!!! int iHasShiftHeld = GetAsyncKeyState(VK_LSHIFT); if(pLocal->curstate.movetype == MOVETYPE_WALK && !iHasShiftHeld && !(usercmd->buttons & IN_ATTACK) && !(usercmd->buttons & IN_USE)) { fTime = gEngfuncs.GetClientTime(); usercmd->viewangles.y = fmod(fTime * SPIN_REVS_PER_SECOND * 360.0f, 360.0f); } // this branch makes sure your horizontal velocity is not affected when fixing up the movement angles -- it isn't specific to spinning and you can use it with the source tetsuo posted in his forum too if(pLocal->curstate.movetype == MOVETYPE_WALK) { gEngfuncs.pfnAngleVectors(Vector(0.0f, usercmd->viewangles.y, 0.0f), aimforward, aimright, aimup); } else { gEngfuncs.pfnAngleVectors(usercmd->viewangles, aimforward, aimright, aimup); } newforward = DotProduct(forward * viewforward.Normalize(), aimforward) + DotProduct(right * viewright.Normalize(), aimforward) + DotProduct(up * viewup.Normalize(), aimforward); newright = DotProduct(forward * viewforward.Normalize(), aimright) + DotProduct(right * viewright.Normalize(), aimright) + DotProduct(up * viewup.Normalize(), aimright); newup = DotProduct(forward * viewforward.Normalize(), aimup) + DotProduct(right * viewright.Normalize(), aimup) + DotProduct(up * viewup.Normalize(), aimup); usercmd->forwardmove = newforward; usercmd->sidemove = newright; usercmd->upmove = newup; }
[ "zonrex@live.cn" ]
zonrex@live.cn
c70f42e86d4b2446bb61f68deb7e3f0121b49a8a
c7a7326ccf0fed00bd00bfd501738095d3c3fe61
/TECH_3/CPP/CPP_rtype_2019/include/SFML/IGame.hpp
77970e166aa8cede31dde362736203d3f5574410
[]
no_license
Di-KaZ/EPITECH
c7acf24bfac077d5526c3f2bbb31804ab8c8f5ad
52dd5cefd89f0be732178996b3c6e31d5a401ca4
refs/heads/master
2020-07-31T09:22:32.790577
2020-01-13T15:32:54
2020-01-13T15:32:54
210,557,825
0
0
null
null
null
null
UTF-8
C++
false
false
232
hpp
#pragma once #include <string> #include "UDPClient.hpp" class IGame { public: virtual void init(unsigned int width, unsigned int height, std::string title, UDPClient *udp_client) = 0; virtual void run() = 0; };
[ "moussa.fofana@epitech.eu" ]
moussa.fofana@epitech.eu
1136beec207a2f373ab07bcc38c30a0d48a1c9a2
15f2b9ba958fe457f1c213254c5ca25d0b863a33
/HackerRank/cpp/ExpcetionServer.cpp
8607ab20944e8ac6e3c973a4aa58dc215eac97c5
[]
no_license
adinathraut20/CompetitiveCode
9efefa574e5795e08f6268888d17e1a74380ab80
f760f75342b2fa14baf4fa249557425f54089f46
refs/heads/master
2023-04-20T22:32:11.523753
2021-05-15T18:49:31
2021-05-15T18:49:31
367,709,517
0
0
null
null
null
null
UTF-8
C++
false
false
1,052
cpp
include <iostream> #include <exception> #include <string> #include <stdexcept> #include <vector> #include <cmath> using namespace std; class Server { private: static int load; public: static int compute(long long A, long long B) { load += 1; if(A < 0) { throw std::invalid_argument("A is negative"); } vector<int> v(A, 0); int real = -1, cmplx = sqrt(-1); if(B == 0) throw 0; real = (A/B)*real; int ans = v.at(B); return real + A - B*ans; } static int getLoad() { return load; } }; int Server::load = 0; int main() { int T; cin >> T; while(T--) { long long A, B; cin >> A >> B; /* Enter your code here. */ try { cout << Server::compute(A, B) << endl; } catch (std::bad_alloc& error) { cout << "Not enough memory" << endl; } catch (std::exception& error) { cout << "Exception: " << error.what() << endl; } catch (...) { cout << "Other Exception" << endl; } } cout << Server::getLoad() << endl; return 0; }
[ "adinathraut20@gmail.com" ]
adinathraut20@gmail.com
4d6cb57489b6fc369441e5c4ffaaa9d60ab473fa
d7db098f4b1d1cd7d32952ebde8106e1f297252e
/AOJ/2330.cpp
f8eabe867dc06c8b2c4f2f3322af6f54f07b86d3
[]
no_license
monman53/online_judge
d1d3ce50f5a8a3364a259a78bb89980ce05b9419
dec972d2b2b3922227d9eecaad607f1d9cc94434
refs/heads/master
2021-01-16T18:36:27.455888
2019-05-26T14:03:14
2019-05-26T14:03:14
25,679,069
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
#include <iostream> using namespace std; typedef long long int ll; int main(){ ll n, ans=0; cin >> n; for(ll i=1;i<n;i*=3){ ans++; } cout << ans << endl; return 0; }
[ "tetsuro53@gmail.com" ]
tetsuro53@gmail.com
1ae24fde07b0483f37a0d70d1fbce8e39e1ea12b
735b350420fc3290cb0957f9b90c84be74638a09
/KattisPractices/James/pivot.cpp
ab5769d7e28a0a207d9425599e9d2574982b822e
[]
no_license
kronicler/cs2040_DSnA
20e4b2f9d2bcc937f96648229370ef3d7c368afc
cd372f1e5fc80ac62f0e1b80b34a7a72468fd80a
refs/heads/master
2021-03-28T18:18:04.113424
2018-10-21T02:54:01
2018-10-21T02:54:01
117,228,925
0
1
null
2018-10-21T02:54:02
2018-01-12T10:39:57
C++
UTF-8
C++
false
false
849
cpp
#include <iostream> #include <vector> using namespace std; int main () { int elements; int count = 0; long min, max; cin >> elements; long input[elements], rightMin[elements], leftMax[elements]; for (int i = 0; i < elements; i++) { cin >> input[i]; } max = input[0]; for (int i = 0; i < elements; i++) { if (!i) leftMax[i] = input[i]; else { if (input[i-1] > max) max = input[i-1]; leftMax[i] = max; } } min = input[elements-1]; for (int i = elements-1; i >= 0; i--) { if (i == elements-1) rightMin[i] = input[i]; else { if (input[i+1] < min) min = input[i+1]; rightMin[i] = min; } } for (int i = 0; i < elements; i++) { if ((input[i] >= leftMax[i] && input[i] < rightMin[i]) || (i == elements-1 && input[i] <= rightMin[i] && input[i] >= leftMax[i])) count++; } cout << count << endl; return 0; }
[ "jamesyaputra1704@gmail.com" ]
jamesyaputra1704@gmail.com
7a4f11acf3967442ac2ca7edd2e6a89dbd9ce8bc
a1505a734508e01f4a62ad7cf67988a2c6a5b027
/include/Zia/API/ServerConfig.hpp
f17a2b3f91a7148fb6c645ef053d8941a3cf208c
[]
no_license
demaisj/ZiaModuleAPISpec
90490d8c4840ec5a1716b20b14bd7171c4e2cb77
73c9651683bacd13026f41aa2b2e83b8d31d8a8c
refs/heads/master
2020-04-22T12:40:01.480273
2019-02-27T12:49:57
2019-02-27T12:49:57
170,380,141
6
1
null
2019-02-27T12:49:58
2019-02-12T19:43:53
C++
UTF-8
C++
false
false
1,274
hpp
/* ** EPITECH PROJECT, 2019 ** ZiaModuleAPISpec ** File description: ** Server config spec */ #pragma once #include <string> #include <unordered_map> #include "Definitions.hpp" namespace Zia { namespace API { /* * SERVER CONFIGURATION: * * This struct contains all configuration needed to initialize a module. * The user-provided config is transmitted in a string map. */ struct ServerConfig { enum class Platform { Linux, Windows, Macos }; /* * Server name: * can be set to system's hostname */ std::string name; /* * Server version: * can be used to require specific version from module */ std::string version; /* * Server platform: * which platform the server is running on */ Platform platform; /* * Server config: * A map of config values provided by the user. * The config cannot have depth. Instead, it should be "emulated" using * dot notation. for example "this.is.deep" */ std::unordered_map<std::string, std::string> config; /* * API spec version: * Do not touch this, it is already set by default. */ std::string apispec_version = Definitions::VERSION; }; } }
[ "Jordan.Demaison@gmail.com" ]
Jordan.Demaison@gmail.com
a4be18fec3f89d4e9364ec73c5cee6981f393cd1
0a47465d69b936289704560c736444e71923496e
/server/src/common/NetworkConnection.cpp
df93b16936514bf9f6f66ee7ff4fd5905782e574
[]
no_license
HeYuHan/ntcp
e5c7b0e75cd57dba67c1826c7085054b59b68d03
0f9967370b1d8e0c57d266186d1a55d3f46423d9
refs/heads/master
2021-04-03T09:35:17.060824
2018-07-26T12:40:37
2018-07-26T12:40:37
124,967,106
0
0
null
null
null
null
UTF-8
C++
false
false
7,662
cpp
#include "NetworkConnection.h" #include<string.h> #include "log.h" #include "WebSocket.h" #define FLOAT_RATE 100.0f NetworkStream::NetworkStream(int send_buff_size, int read_buff_size):web_frame(NULL) { read_buff = new char[read_buff_size]; write_buff = new char[send_buff_size]; write_position = write_buff; write_buff_end = write_buff + send_buff_size; write_end = write_buff; read_offset = read_buff; read_end = read_buff; read_position = read_buff; read_buff_end = read_buff + send_buff_size; } NetworkStream::~NetworkStream() { delete[] read_buff; delete[] write_buff; read_buff = NULL; write_buff = NULL; } void NetworkStream::OnRevcMessage() { if (NULL == connection)return; try { int empty_size = read_buff_end - read_offset; int revc_size = connection->Read(read_offset, empty_size); if (revc_size == 0) { //log_info("revc_size is zero closed %s", "OnRevcMessage"); connection->Disconnect(); return; } read_offset += revc_size; int size = read_offset - read_position; if (connection->m_Type == TCP_SOCKET) { while (size > 4) { int data_len = 0; memcpy(&data_len, read_position, 4); if (size - 4 < data_len)break; read_position += 4; read_end = read_position + data_len; OnMessage(); read_position = read_end; size = read_offset - read_position; } } else if (connection->m_Type == WEB_SOCKET) { if (web_frame == NULL)web_frame = read_position; size = read_offset - web_frame; while (size>1) { WebSokcetParser parser; int outHead = 0; int outSize = 0; int ret = parser.DecodeFrame(web_frame, size, outHead, outSize); if (ret == WS_PARSE_RESULT_ERROR) { log_info("websocket closed %s", "WS_PARSE_RESULT_ERROR"); connection->Disconnect(); return; } else if (ret == WS_PARSE_RESULT_SKIP) { int skip_len = outHead + outSize; size = size - skip_len; memmove(web_frame, web_frame + skip_len, size); read_offset = web_frame + size; } else if (ret == WS_PARSE_RESULT_WAIT_NEXT_DATA) { log_info("WS_PARSE_RESULT_WAIT_NEXT_DATA=>next size : %d", size); web_frame = NULL; return; } else if (ret == WS_PARSE_RESULT_WAIT_NETX_FRAME) { int skip_len = outHead; size = size - skip_len; memmove(web_frame, web_frame + skip_len, size); read_offset = web_frame + size; web_frame += outSize; size = size - outSize; } else if (ret == WS_PARSE_RESULT_OK) { int skip_len = outHead; size = size - skip_len; memmove(web_frame, web_frame + skip_len, size); read_offset = web_frame + size; read_end = web_frame + outSize; OnMessage(); read_position = read_end; size = read_offset - read_position; web_frame = read_position; if (size > 0)log_info("WS_PARSE_RESULT_OK=>next size : %d", size); else web_frame = NULL; } } } size = read_offset - read_position; if ((read_position - read_buff) > 0 && size > 0) { memcpy(read_buff, read_position, size); } read_offset = read_buff + size; read_position = read_end = read_buff; } catch (...) { log_error("%s", "parse message error"); if (connection)connection->Disconnect(); } } void NetworkStream::Reset() { write_position = write_buff; write_end = write_buff; read_offset = read_buff; read_end = read_buff; read_position = read_buff; web_frame = NULL; } void NetworkStream::WriteBool(bool b) { byte value = b ? 1 : 0; WriteByte(value); } ////////////////////////////////////////////////////////////// //write data void NetworkStream::WriteByte(byte data) { WriteData(&data, sizeof(byte)); } void NetworkStream::WriteChar(char data) { WriteData(&data, sizeof(char)); } void NetworkStream::WriteShort(short data) { WriteData(&data, sizeof(short)); } void NetworkStream::WriteUShort(ushort data) { WriteData(&data, sizeof(ushort)); } void NetworkStream::WriteInt(int data) { WriteData(&data, sizeof(int)); } void NetworkStream::WriteUInt(uint data) { WriteData(&data, sizeof(uint)); } void NetworkStream::WriteFloat(float data) { int int_data = (int)(data*FLOAT_RATE); WriteData(&int_data, sizeof(int)); } void NetworkStream::WriteLong(long data) { WriteData(&data, sizeof(long)); } void NetworkStream::WriteULong(ulong data) { WriteData(&data, sizeof(ulong)); } void NetworkStream::WriteString(const char* str) { int len = strlen(str); WriteInt(len); WriteData(str, len); } void NetworkStream::WriteData(const void* data, int count) { if (write_buff == NULL || count < 0 || write_end + count > write_buff_end) { throw WRITEERROR; } if (count > 0) { memcpy(write_end, data, count); write_end += count; } } void NetworkStream::WriteVector3(Vector3 & v3) { WriteFloat(v3.x); WriteFloat(v3.y); WriteFloat(v3.z); } void NetworkStream::WriteShortQuaternion(Quaternion & rot) { short x = rot.x * 1000; short y = rot.y * 1000; short z = rot.z * 1000; short w = rot.w * 1000; WriteShort(x); WriteShort(y); WriteShort(z); WriteShort(w); } void NetworkStream::BeginWrite() { write_position = write_buff; write_end = write_buff; if (connection->m_Type == UDP_SOCKET) { write_end = write_buff + 5; } else if(connection->m_Type == TCP_SOCKET) { write_end = write_buff + 4; } } void NetworkStream::EndWrite() { int head_len = connection->m_Type == UDP_SOCKET ? 5 : 4; int data_len = write_end - write_position - head_len; if (connection->m_Type == UDP_SOCKET) { write_position[0] = GAME_MSG; memcpy(write_position+1, &data_len, 4); } else if(connection->m_Type == TCP_SOCKET) { memcpy(write_position, &data_len, 4); } else { head_len = 0; data_len = write_end - write_position; WebSokcetParser parser; int outSize = 0; parser.EncodeFrame(write_position, data_len, write_buff_end-write_end, outSize); if (outSize > 0) { data_len = outSize; } } if (connection&&data_len>0)connection->Send(write_position, data_len+head_len); } ////////////////////////////////////////////////////////////// //read data void NetworkStream::ReadByte(byte &data) { ReadData(&data, sizeof(byte)); } void NetworkStream::ReadByte(char &data) { ReadData(&data, sizeof(char)); } void NetworkStream::ReadShort(short &data) { ReadData(&data, sizeof(short)); } void NetworkStream::ReadUShort(ushort &data) { ReadData(&data, sizeof(ushort)); } void NetworkStream::ReadInt(int &data) { ReadData(&data, sizeof(int)); } void NetworkStream::ReadUInt(uint &data) { ReadData(&data, sizeof(uint)); } void NetworkStream::ReadFloat(float &data) { int ret = 0; ReadInt(ret); data = ret / FLOAT_RATE; } void NetworkStream::ReadLong(long &data) { ReadData(&data, sizeof(long)); } void NetworkStream::ReadULong(ulong &data) { ReadData(&data, sizeof(ulong)); } int NetworkStream::ReadString(char* str, int size) { int len = 0; ReadInt(len); if (len < 0 || size<len) { throw READERROR; } str[len] = 0; ReadData(str, len); return len; } void NetworkStream::ReadData(void* data, int count) { if (read_buff == NULL || count < 0 || read_position + count > read_end) { throw READERROR; } if (count > 0) { memcpy(data, read_position, count); read_position += count; } } void NetworkStream::ReadVector3(Vector3 & v3) { ReadFloat(v3.x); ReadFloat(v3.y); ReadFloat(v3.z); } void NetworkStream::ReadShortQuaternion(Quaternion & rot) { short x, y, z, w; ReadShort(x); ReadShort(y); ReadShort(z); ReadShort(w); rot = Quaternion(x / 1000.0f, y / 1000.0f, z / 1000.0f, w / 1000.0f); } NetworkConnection::NetworkConnection(): stream(NULL) { } NetworkConnection::~NetworkConnection() { stream = NULL; }
[ "435481457@qq.com" ]
435481457@qq.com
a8e7ea69a8797bb23f5a62f247a1939e858a30fb
467a5eec8488b665eb2ddc9b2084b8ac04a983ae
/MasteringMCU/Resources/Arduino/i2c/003I2CMasterRxString/003I2CMasterRxString.ino
b8f4487325d59e1a3679baa46ccde0f84f334985
[]
no_license
Jeanmi3166/STM32
37e02de6305a2f8ecd2fb689ce957c684f20c984
26f08f6969b906d89eb058b2079f646e42bebba1
refs/heads/main
2023-04-17T18:44:25.933666
2021-05-07T07:10:20
2021-05-07T07:10:20
354,021,962
0
0
null
null
null
null
UTF-8
C++
false
false
1,533
ino
// Wire Master Transmitter and Receiver //Uno, Ethernet A4 (SDA), A5 (SCL) #include <Wire.h> // Include the required Wire library for I2C<br>#include <Wire.h> int LED = 13; uint8_t rcv_buf[32]; int data_len=0; #define SLAVE_ADDR 0x68 void setup() { Serial.begin(9600); // Define the LED pin as Output pinMode (LED, OUTPUT); // join i2c bus (address optional for master) Wire.begin(); } void loop() { Serial.println("Arduino Master"); Serial.println("Send character \"s\" to begin"); Serial.println("-----------------------------"); while(!Serial.available()); char in_read=Serial.read(); while(in_read != 's'); Serial.println("Starting.."); Wire.beginTransmission(SLAVE_ADDR); Wire.write(0X51); //Send this command to read the length Wire.endTransmission(); Wire.requestFrom(SLAVE_ADDR,1); // Request the transmitted two bytes from the two registers if(Wire.available()) { // data_len = Wire.read(); // Reads the data } Serial.print("Data Length:"); Serial.println(String(data_len,DEC)); Wire.beginTransmission(SLAVE_ADDR); Wire.write(0X52); //Send this command to ask data Wire.endTransmission(); Wire.requestFrom(SLAVE_ADDR,data_len); uint32_t i=0; for( i =0; i <= data_len ; i++) { if(Wire.available()) { // rcv_buf[i] = Wire.read(); // Reads the data } } rcv_buf[i] = '\0'; Serial.print("Data:"); Serial.println((char*)rcv_buf); Serial.println("*********************END*********************"); }
[ "jeanmichel3166@yahoo.fr" ]
jeanmichel3166@yahoo.fr
d60b67fc8f281696ee1e3b467e62ed7e2dc90cab
c3f715589f5d83e3ba92baaa309414eb253ca962
/C++/round-2/161-180/169.h
3940ad4b17d491074777008b5cd764ee8c0f7aed
[]
no_license
kophy/Leetcode
4b22272de78c213c4ad42c488df6cffa3b8ba785
7763dc71fd2f34b28d5e006a1824ca7157cec224
refs/heads/master
2021-06-11T05:06:41.144210
2021-03-09T08:25:15
2021-03-09T08:25:15
62,117,739
13
1
null
null
null
null
UTF-8
C++
false
false
476
h
class Solution { public: /* reservoir pooling */ int majorityElement(vector<int>& nums) { if (nums.size() == 0) return -1; int num = nums[0], count = 1; for (int i = 1; i < nums.size(); ++i) { if (nums[i] == num) ++count; else --count; if (count == 0) { num = nums[i]; count = 1; } } return num; } };
[ "w1tao@yahoo.com" ]
w1tao@yahoo.com
c4f43612cf2c95bd76cc792bca5fa819dc28ea48
5286798f369775a6607636a7c97c87d2a4380967
/thirdparty/instant-meshes/instant-meshes-dust3d/src/bvh.h
ee4ea23b25c6bb29a094171272604475eb86aca8
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
MelvinG24/dust3d
d03e9091c1368985302bd69e00f59fa031297037
c4936fd900a9a48220ebb811dfeaea0effbae3ee
refs/heads/master
2023-08-24T20:33:06.967388
2021-08-10T10:44:24
2021-08-10T10:44:24
293,045,595
0
0
MIT
2020-09-05T09:38:30
2020-09-05T09:38:29
null
UTF-8
C++
false
false
3,171
h
/* bvh.h -- bounding volume hierarchy for fast ray-intersection queries This file is part of the implementation of Instant Field-Aligned Meshes Wenzel Jakob, Daniele Panozzo, Marco Tarini, and Olga Sorkine-Hornung In ACM Transactions on Graphics (Proc. SIGGRAPH Asia 2015) All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE.txt file. */ #pragma once #include "aabb.h" /* BVH node in 32 bytes */ struct BVHNode { union { struct { unsigned flag : 1; uint32_t size : 31; uint32_t start; } leaf; struct { uint32_t unused; uint32_t rightChild; } inner; }; AABB aabb; inline bool isLeaf() const { return leaf.flag == 1; } inline bool isInner() const { return leaf.flag == 0; } inline bool isUnused() const { return inner.unused == 0 && inner.rightChild == 0; } inline uint32_t start() const { return leaf.start; } inline uint32_t end() const { return leaf.start + leaf.size; } }; class BVH { friend struct BVHBuildTask; /* Cost values for BVH surface area heuristic */ enum { T_aabb = 1, T_tri = 1 }; public: BVH(const MatrixXu *F, const MatrixXf *V, const MatrixXf *N, const AABB &aabb); ~BVH(); void setData(const MatrixXu *F, const MatrixXf *V, const MatrixXf *N) { mF = F; mV = V; mN = N; } const MatrixXu *F() const { return mF; } const MatrixXf *V() const { return mV; } const MatrixXf *N() const { return mN; } Float diskRadius() const { return mDiskRadius; } void build(const ProgressCallback &progress = ProgressCallback()); void printStatistics() const; bool rayIntersect(Ray ray) const; bool rayIntersect(Ray ray, uint32_t &idx, Float &t, Vector2f *uv = nullptr) const; void findNearestWithRadius(const Vector3f &p, Float radius, std::vector<uint32_t> &result, bool includeSelf = false) const; uint32_t findNearest(const Vector3f &p, Float &radius, bool includeSelf = false) const; void findKNearest(const Vector3f &p, uint32_t k, Float &radius, std::vector<std::pair<Float, uint32_t> > &result, bool includeSelf = false) const; void findKNearest(const Vector3f &p, const Vector3f &N, uint32_t k, Float &radius, std::vector<std::pair<Float, uint32_t> > &result, Float angleThresh = 30, bool includeSelf = false) const; protected: bool rayIntersectTri(const Ray &ray, uint32_t i, Float &t, Vector2f &uv) const; bool rayIntersectDisk(const Ray &ray, uint32_t i, Float &t) const; void refitBoundingBoxes(uint32_t node_idx = 0); std::pair<Float, uint32_t> statistics(uint32_t node_idx = 0) const; protected: std::vector<BVHNode> mNodes; uint32_t *mIndices; const MatrixXu *mF; const MatrixXf *mV, *mN; ProgressCallback mProgress; Float mDiskRadius; };
[ "huxingyi@msn.com" ]
huxingyi@msn.com
2e35b69891307139e7019a0a942ee5fd8820abf2
63ab36bb32c2e412d0af8d32e3bb3c755f1078a6
/3A.cpp
6d16a852e24151284618c9436f484a5ceef23560
[]
no_license
cedricoode/codeforces.
2414a6a609396394aba96df34f8e95c64f3f5f41
10cdd34c0ad9a3dff94d3ff0914cdd6839afc85c
refs/heads/master
2020-04-07T14:43:00.637494
2018-11-20T22:14:24
2018-11-20T22:14:24
158,458,130
0
0
null
null
null
null
UTF-8
C++
false
false
1,966
cpp
#include <iostream> #include <cmath> using namespace std; bool is_paralle(int start[], int end[]); bool move_paralle(int start[], int end[]); void move_vertex(int start[], int end[]); int compute_distance(int start[], int end[]); int main(void) { int start[2]; int end[2]; char a; int b; cin >> a >> b; start[0] = a - 'a'; start[1] = b; cin >> a>> b; end[0] = a - 'a'; end[1] = b; compute_distance(start, end); if (is_paralle(start, end)) { move_paralle(start, end); } else { move_vertex(start, end); move_paralle(start, end); } } int sign(int x) { return x / abs(x); } int compute_distance(int start[], int end[]) { int offx = end[0] - start[0]; int offy = end[1] - start[1]; int d1 = min(abs(offx), abs(offy)); int newstart[2] = {start[0] + d1 * sign(offx) , start[1] + d1 * sign(offy)}; offx = end[0] - newstart[0]; offy = end[1] - newstart[1]; int d2 = max(abs(offx), abs(offy)); cout << d1 + d2 << endl; } bool is_paralle(int start[], int end[]) { return (start[0] == end[0] || start[1] == end[1]); } bool move_paralle(int start[], int end[]) { if (start[0] == end[0]) { if (start[1] < end[1]) { for (int i = 0; i < end[1] - start[1]; i++) { cout << 'U' << endl; } } else { for (int i = 0; i < start[1] - end[1]; i++) { cout << 'D' << endl; } } } else { if (start[0] < end[0]) { for (int i = 0; i < (end[0] - start[0]); i++) { cout << 'R' << endl; } } else { for (int i = 0; i < start[0] - end[0]; i++) { cout << 'L' << endl; } } } } void move_vertex(int start[], int end[]) { if (is_paralle(start, end)) { return; } if (start[0] > end[0]) { cout << 'L'; start[0] = start[0] - 1; } else if (start[0] < end[0]) { cout << 'R'; start[0] = start[0] + 1; } if (start[1] > end[1]) { cout << 'D'; start[1] = start[1] - 1; } else if (start[1] < end[1]) { cout << 'U'; start[1] = start[1] + 1; } cout << endl; move_vertex(start, end); }
[ "cedric.yang@ihealthlabs.com" ]
cedric.yang@ihealthlabs.com
684a52bb87e8ea769e993f068b4f60a68fb4c71b
7b46f4140b078c5cb7954b6735fff6a31e2e7751
/torch/csrc/jit/fusers/cuda/resource_strings.h
49a47cd85d18dcefa32f8c20be3bab20fafa7a84
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "BSD-2-Clause" ]
permissive
jcjohnson/pytorch
f704a5a602f54f6074f6b49d1696f30e05dea429
ab253c2bf17747a396c12929eaee9d379bb116c4
refs/heads/master
2020-04-02T15:36:09.877841
2018-10-24T21:57:42
2018-10-24T22:02:40
101,438,891
8
2
NOASSERTION
2018-10-24T21:55:49
2017-08-25T20:13:19
Python
UTF-8
C++
false
false
5,809
h
#include "torch/csrc/jit/fusers/Config.h" #if USE_CUDA_FUSER #pragma once #include "torch/csrc/jit/code_template.h" namespace torch { namespace jit { namespace cudafuser { /*with type_as not checking type of its input, a fusion group can have non-fp32 tensor as input. Correct code for this case is generated, however, nvrtc does not know how to handle int*_t integer types, so typedefs help it handle those cases*/ auto type_declarations_template = CodeTemplate(R"( typedef unsigned char uint8_t; typedef signed char int8_t; typedef short int int16_t; typedef long long int int64_t; ${HalfHeader} ${RandHeader} #define NAN __int_as_float(0x7fffffff) #define POS_INFINITY __int_as_float(0x7f800000) #define NEG_INFINITY __int_as_float(0xff800000) typedef ${IndexType} IndexType; template<typename T, size_t N> struct TensorInfo { T* data; IndexType sizes[N]; IndexType strides[N]; }; template<typename T> struct TensorInfo<T, 0> { T * data; }; )"); // We rewrite the code for philox RNG from curand as nvrtc couldn't resolve the // curand header correctly. constexpr auto rand_support_literal = R"( class Philox { public: __device__ inline Philox(unsigned long long seed, unsigned long long subsequence, unsigned long long offset) { key.x = (unsigned int)seed; key.y = (unsigned int)(seed >> 32); counter = make_uint4(0, 0, 0, 0); counter.z = (unsigned int)(subsequence); counter.w = (unsigned int)(subsequence >> 32); STATE = 0; incr_n(offset / 4); } __device__ inline unsigned long operator()() { if(STATE == 0) { uint4 counter_ = counter; uint2 key_ = key; for(int i = 0; i < 9; i++) { counter_ = single_round(counter_, key_); key_.x += (kPhilox10A); key_.y += (kPhilox10B); } output = single_round(counter_, key_); incr(); } unsigned long ret; switch(STATE) { case 0: ret = output.x; break; case 1: ret = output.y; break; case 2: ret = output.z; break; case 3: ret = output.w; break; } STATE = (STATE + 1) % 4; return ret; } private: uint4 counter; uint4 output; uint2 key; unsigned int STATE; __device__ inline void incr_n(unsigned long long n) { unsigned int nlo = (unsigned int)(n); unsigned int nhi = (unsigned int)(n >> 32); counter.x += nlo; if (counter.x < nlo) nhi++; counter.y += nhi; if (nhi <= counter.y) return; if (++counter.z) return; ++counter.w; } __device__ inline void incr() { if (++counter.x) return; if (++counter.y) return; if (++counter.z) return; ++counter.w; } __device__ unsigned int mulhilo32(unsigned int a, unsigned int b, unsigned int *result_high) { *result_high = __umulhi(a, b); return a*b; } __device__ inline uint4 single_round(uint4 ctr, uint2 key) { unsigned int hi0; unsigned int hi1; unsigned int lo0 = mulhilo32(kPhiloxSA, ctr.x, &hi0); unsigned int lo1 = mulhilo32(kPhiloxSB, ctr.z, &hi1); uint4 ret = {hi1 ^ ctr.y ^ key.x, lo1, hi0 ^ ctr.w ^ key.y, lo0}; return ret; } static const unsigned long kPhilox10A = 0x9E3779B9; static const unsigned long kPhilox10B = 0xBB67AE85; static const unsigned long kPhiloxSA = 0xD2511F53; static const unsigned long kPhiloxSB = 0xCD9E8D57; }; // Inverse of 2^32. #define M_RAN_INVM32 2.3283064e-10f __device__ __inline__ float uniform(unsigned int x) { return x * M_RAN_INVM32; } )"; constexpr auto rand_param = ",unsigned long long seed, unsigned long long offset"; constexpr auto rand_init = R"( int idx = blockIdx.x*blockDim.x + threadIdx.x; Philox rnd(seed, idx, offset); )"; auto cuda_compilation_unit_template = CodeTemplate(R"( ${type_declarations} extern "C" __global__ void ${kernelName}(IndexType totalElements, ${formals} ${RandParam}) { ${RandInit} for (IndexType linearIndex = blockIdx.x * blockDim.x + threadIdx.x; linearIndex < totalElements; linearIndex += gridDim.x * blockDim.x) { // Convert `linearIndex` into an offset of tensor: ${tensorOffsets} // calculate the results ${kernelBody} } } )"); // This snippet enables half support in the jit. Following the pattern for // reductions, fp16 input data is immediately upconverted to float // with __half2float(). All mathematical operations are done on float // values, and if needed the intermediate float representation is // converted to half with __float2half() when writing to a half tensor. constexpr auto half_support_literal = R"( #define __HALF_TO_US(var) *(reinterpret_cast<unsigned short *>(&(var))) #define __HALF_TO_CUS(var) *(reinterpret_cast<const unsigned short *>(&(var))) #if defined(__cplusplus) struct __align__(2) __half { __host__ __device__ __half() { } protected: unsigned short __x; }; /* All intrinsic functions are only available to nvcc compilers */ #if defined(__CUDACC__) /* Definitions of intrinsics */ __device__ __half __float2half(const float f) { __half val; asm("{ cvt.rn.f16.f32 %0, %1;}\n" : "=h"(__HALF_TO_US(val)) : "f"(f)); return val; } __device__ float __half2float(const __half h) { float val; asm("{ cvt.f32.f16 %0, %1;}\n" : "=f"(val) : "h"(__HALF_TO_CUS(h))); return val; } #endif /* defined(__CUDACC__) */ #endif /* defined(__cplusplus) */ #undef __HALF_TO_US #undef __HALF_TO_CUS typedef __half half; )"; } // namespace cudafuser } // namespace jit } // namespace torch #endif // USE_CUDA_FUSER
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
68629f301648d30914d8eb4973d7a3c0dce7cd74
cd1aa2c1b545b9e35e399077d5281c9b07941b81
/Arduino_reference/Distance.ino
76c84a01fb4d13a58569e974970c5d0df2162623
[ "MIT" ]
permissive
windust7/AIM_Drone
9ec89496f19637e406b41f45947026e84cc05af2
706c51d770f590777c64b16169d26c29fa4c31cc
refs/heads/main
2023-03-29T19:47:51.217513
2021-04-07T06:01:27
2021-04-07T06:01:27
308,322,516
0
1
null
null
null
null
UTF-8
C++
false
false
705
ino
int trigPin=6; int echoPin=7; void setup() { Serial.begin(9600); //시리얼 Baudrate 9600으로 설정 pinMode(trigPin, OUTPUT); //trig를 출력모드로 설정 pinMode(echoPin, INPUT); //echo를 입력모드로 설정 } void loop() { float duration, distance; digitalWrite(trigPin, HIGH); //초음파를 보내고 대기 delay(10); //0.01초 대기 digitalWrite(trigPin, LOW); duration=pulseIn(echoPin, HIGH); //echoPin이 HIGH를 유지한 시간 저장(1,000,000s^(-1)단위) distance=((float)(340*duration)/10000)/2; //초음파를 보내고 다시 돌아온 시간을 측정해 거리 계산(1m=100cm, duration 시간 단위) Serial.print(distance); Serial.println(“cm”) Delay(500); }
[ "62916482+windust7@users.noreply.github.com" ]
62916482+windust7@users.noreply.github.com
20380ae3a9f6ab39ee73482eaba55cf30a74f908
0a0b0e63cd578581982efe338c13eee229d838a4
/examples/apps/mstc/public/base/Utf.h
544746c8977c339f27ba1ee7a4d1084606488925
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause" ]
permissive
jjlee3/openthread
0e0ddec03f3afaf5689a7360f03342a2e8d6620e
abba21bca6e1b07ca76b0241dfaf045e57396818
refs/heads/master
2021-01-20T12:12:35.074196
2017-03-12T15:36:02
2017-03-12T15:36:02
76,529,371
0
0
null
null
null
null
UTF-8
C++
false
false
7,026
h
#pragma once #include <iterator> #include <base/Exception.h> namespace mstc { namespace base { class Utf { public: EXCEPT_BASE (Failure); EXCEPT_DERIVED(OutOfUtf16Range , Failure); EXCEPT_DERIVED(Utf8Length5 , Failure); EXCEPT_DERIVED(Utf8Length6 , Failure); EXCEPT_DERIVED(Utf8Length7 , Failure); EXCEPT_DERIVED(IncompleteUtf8Sequence , Failure); EXCEPT_DERIVED(InvalidUtf8Sequence , Failure); EXCEPT_DERIVED(EndOfUtf16 , Failure); EXCEPT_DERIVED(IncompleteUtf16Surrogates , Failure); EXCEPT_DERIVED(InvalidUtf16TrailingSurrogates, Failure); EXCEPT_DERIVED(InvalidUtf16LeadingSurrogates , Failure); EXCEPT_DERIVED(InvalidUtf16 , Failure); template <typename IIt, typename OIt> static OIt utf8to16(IIt first, IIt last, OIt dest) { for (; first != last;) { detail::utf8to16(first, last, dest); } return dest; } static void utf8to16(const std::string& utf8, std::wstring& utf16) { utf8to16(utf8.cbegin(), utf8.cend(), std::back_inserter(utf16)); } // utf8to16 static std::wstring utf8to16(const std::string& utf8) { std::wstring utf16; utf8to16(utf8.cbegin(), utf8.cend(), std::back_inserter(utf16)); return utf16; } // utf8to16 template <typename IIt, typename OIt> static OIt utf16to8(IIt first, IIt last, OIt dest) { for (; first != last;) { detail::utf16to8(first, last, dest); } return dest; } static void utf16to8(const std::wstring& utf16, std::string& utf8) { utf16to8(utf16.cbegin(), utf16.cend(), std::back_inserter(utf8)); } // utf16to8 static std::string utf16to8(const std::wstring& utf16) { std::string utf8; utf16to8(utf16.cbegin(), utf16.cend(), std::back_inserter(utf8)); return utf8; } // utf16to8 protected: struct detail // one code point { template <typename IIt, typename OIt> static void utf8to16(IIt& it, IIt last, OIt& dest) { auto curr = *it++; if ((curr & 0x80) == 0) { *dest++ = curr; } else if ((curr & 0xe0) == 0xc0) { // two fields uint16_t field1 = curr & 0x1f; uint16_t field2 = utf8to16_mb(it, last); *dest++ = (field1 << 6) | field2; } else if ((curr & 0xf0) == 0xe0) { // three fields uint16_t field1 = curr & 0x0f; uint16_t field2 = utf8to16_mb(it, last); uint16_t field3 = utf8to16_mb(it, last); *dest++ = (field1 << 12) | (field2 << 6) | field3; } else if ((curr & 0xf8) == 0xf0) { // four fields - jjlee uint16_t field1 = curr & 0x07; uint16_t field2 = utf8to16_mb(it, last); uint16_t field3 = utf8to16_mb(it, last); uint16_t field4 = utf8to16_mb(it, last); uint32_t cp = (static_cast<uint32_t>(field1) << 18) | (static_cast<uint32_t>(field2) << 12) | (static_cast<uint32_t>(field3) << 6) | static_cast<uint32_t>(field4); if (cp > 0x10FFFF) { MSTC_THROW_EXCEPTION(OutOfUtf16Range{}); } cp -= 0x10000; *dest++ = 0xD800 + static_cast<uint16_t>(cp >> 10); *dest++ = 0xDC00 + static_cast<uint16_t>(cp & 0x03FF); } else if ((curr & 0xfc) == 0xf8) { // five fields - jjlee it += 4; MSTC_THROW_EXCEPTION(Utf8Length5{}); } else if ((curr & 0xfe) == 0xfc) { // six fields - jjlee it += 5; MSTC_THROW_EXCEPTION(Utf8Length6{}); } else { // unknown fields - jjlee it += 6; MSTC_THROW_EXCEPTION(Utf8Length7{}); } } // utf8to16 template <typename IIt> static uint16_t utf8to16_mb(IIt& it, IIt last) { if (it == last) { MSTC_THROW_EXCEPTION(IncompleteUtf8Sequence{}); } auto curr = *it++; if ((curr & 0xc0) != 0x80) { MSTC_THROW_EXCEPTION(InvalidUtf8Sequence{}); } return curr & 0x3f; } // utf8to16_mb template <typename IIt, typename OIt> static void utf16to8(IIt& it, IIt last, OIt& dest) { if (it == last) { MSTC_THROW_EXCEPTION(EndOfUtf16{}); } auto curr = *it++; if (curr <= 0x007F) { *dest++ = static_cast<char>(curr); } else if (curr <= 0x07FF) { *dest++ = 0xC0 | static_cast<char>((curr & 0x07C0) >> 6); *dest++ = 0x80 | static_cast<char>(curr & 0x003F); } else if (curr <= 0xD7FF) { *dest++ = 0xE0 | static_cast<char>((curr & 0xF000) >> 12); *dest++ = 0x80 | static_cast<char>((curr & 0x0FC0) >> 6); *dest++ = 0x80 | static_cast<char>(curr & 0x003F); } else if (curr <= 0xDBFF) { uint32_t cp = (curr - 0xD800) * 0x0400 + 0x10000; if (it == last) { MSTC_THROW_EXCEPTION(IncompleteUtf16Surrogates{}); } uint16_t trail = *it++; if (trail <= 0xDBFF) { MSTC_THROW_EXCEPTION(InvalidUtf16TrailingSurrogates{}); } else if (trail <= 0xDFFF) { cp |= (trail - 0xDC00); } else { MSTC_THROW_EXCEPTION(InvalidUtf16TrailingSurrogates{}); } *dest++ = 0xF0 | static_cast<char>((cp & 0x1C0000) >> 18); *dest++ = 0x80 | static_cast<char>((cp & 0x3F000) >> 12); *dest++ = 0x80 | static_cast<char>((cp & 0x0FC0) >> 6); *dest++ = 0x80 | static_cast<char>(cp & 0x003F); } else if (curr <= 0xDFFF) { MSTC_THROW_EXCEPTION(InvalidUtf16LeadingSurrogates{}); } else if (curr <= 0xFFFF) { *dest++ = 0xE0 | static_cast<char>((curr & 0xF000) >> 12); *dest++ = 0x80 | static_cast<char>((curr & 0x0FC0) >> 6); *dest++ = 0x80 | static_cast<char>(curr & 0x003F); } else { MSTC_THROW_EXCEPTION(InvalidUtf16{}); } } // utf16to8 }; // detail }; // Utf } // namespace mstc } // namespace base
[ "jjlee3@hotmail.com" ]
jjlee3@hotmail.com
7f0e58e06b7ccc34447b5b65671e0548dde21ef3
53f60171a0b50238126aa4cbe4280327c5744ef3
/details.h
88c1d2587af2a6660d28321cdcedc5712723cbee
[]
no_license
ldyz/MyProject
0525f07a94eac4c302fdd1ac621838be1a524eba
14e17bdf0157f5cfa16ddd5371381965313f1528
refs/heads/master
2020-06-23T03:16:49.859354
2016-11-24T11:37:49
2016-11-24T11:37:49
74,667,544
0
0
null
null
null
null
UTF-8
C++
false
false
663
h
#ifndef DETAILS_H #define DETAILS_H #include <QWidget> #include <QDebug> #include <QtScript/QScriptEngine> #include<QtNetwork> #include<QTableWidgetItem> #include<QTextDocument> #include <QPrinter> #include <QPainter> #include <QPrintDialog> #include <QNetworkReply> namespace Ui { class Details; } class Details : public QWidget { Q_OBJECT public: explicit Details(QWidget *parent = 0); ~Details(); QJsonDocument json_document; QJsonArray items; QString html; QString orderNo; void init(int i,QByteArray bytes); public slots: void printDetail(); private slots: private: Ui::Details *ui; }; #endif // DETAILS_H
[ "lei_ju@126.com" ]
lei_ju@126.com
91bc8f965419140493c235a9ab1182969b1ccd4d
f6ee126d221bd065dfe843b6a92ca597051ad3e7
/sample_common/src/avc_bitstream.cpp
bca72b781522474c4f511ac3f67dcb719db2e581
[ "BSD-3-Clause" ]
permissive
intel-iot-devkit/intelligent-kiosk-analytics-cpp
fc8e330ea2da1af1e1a308266319f1b3ff7b8be4
174d7c090b5cae9bfd6e9c2c8e8135326d48ab51
refs/heads/master
2023-01-12T15:15:20.795873
2023-01-03T22:56:42
2023-01-03T22:56:42
168,045,072
10
11
null
2020-03-04T10:27:49
2019-01-28T22:02:06
C++
UTF-8
C++
false
false
75,284
cpp
/******************************************************************************\ Copyright (c) 2005-2018, Intel 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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This sample was distributed or derived from the Intel's Media Samples package. The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio or https://software.intel.com/en-us/media-client-solutions-support. \**********************************************************************************/ #include "avc_bitstream.h" #include "sample_defs.h" namespace ProtectedLibrary { mfxStatus DecodeExpGolombOne(mfxU32 **ppBitStream, mfxI32 *pBitOffset, mfxI32 *pDst, mfxI32 isSigned); enum { SCLFLAT16 = 0, SCLDEFAULT = 1, SCLREDEFINED = 2 }; const mfxU32 bits_data[] = { (((mfxU32)0x01 << (0)) - 1), (((mfxU32)0x01 << (1)) - 1), (((mfxU32)0x01 << (2)) - 1), (((mfxU32)0x01 << (3)) - 1), (((mfxU32)0x01 << (4)) - 1), (((mfxU32)0x01 << (5)) - 1), (((mfxU32)0x01 << (6)) - 1), (((mfxU32)0x01 << (7)) - 1), (((mfxU32)0x01 << (8)) - 1), (((mfxU32)0x01 << (9)) - 1), (((mfxU32)0x01 << (10)) - 1), (((mfxU32)0x01 << (11)) - 1), (((mfxU32)0x01 << (12)) - 1), (((mfxU32)0x01 << (13)) - 1), (((mfxU32)0x01 << (14)) - 1), (((mfxU32)0x01 << (15)) - 1), (((mfxU32)0x01 << (16)) - 1), (((mfxU32)0x01 << (17)) - 1), (((mfxU32)0x01 << (18)) - 1), (((mfxU32)0x01 << (19)) - 1), (((mfxU32)0x01 << (20)) - 1), (((mfxU32)0x01 << (21)) - 1), (((mfxU32)0x01 << (22)) - 1), (((mfxU32)0x01 << (23)) - 1), (((mfxU32)0x01 << (24)) - 1), (((mfxU32)0x01 << (25)) - 1), (((mfxU32)0x01 << (26)) - 1), (((mfxU32)0x01 << (27)) - 1), (((mfxU32)0x01 << (28)) - 1), (((mfxU32)0x01 << (29)) - 1), (((mfxU32)0x01 << (30)) - 1), (((mfxU32)0x01 << (31)) - 1), ((mfxU32)0xFFFFFFFF), }; const mfxU8 default_intra_scaling_list4x4[16]= { 6, 13, 20, 28, 13, 20, 28, 32, 20, 28, 32, 37, 28, 32, 37, 42 }; const mfxU8 default_inter_scaling_list4x4[16]= { 10, 14, 20, 24, 14, 20, 24, 27, 20, 24, 27, 30, 24, 27, 30, 34 }; const mfxU8 default_intra_scaling_list8x8[64]= { 6, 10, 13, 16, 18, 23, 25, 27, 10, 11, 16, 18, 23, 25, 27, 29, 13, 16, 18, 23, 25, 27, 29, 31, 16, 18, 23, 25, 27, 29, 31, 33, 18, 23, 25, 27, 29, 31, 33, 36, 23, 25, 27, 29, 31, 33, 36, 38, 25, 27, 29, 31, 33, 36, 38, 40, 27, 29, 31, 33, 36, 38, 40, 42 }; const mfxU8 default_inter_scaling_list8x8[64]= { 9, 13, 15, 17, 19, 21, 22, 24, 13, 13, 17, 19, 21, 22, 24, 25, 15, 17, 19, 21, 22, 24, 25, 27, 17, 19, 21, 22, 24, 25, 27, 28, 19, 21, 22, 24, 25, 27, 28, 30, 21, 22, 24, 25, 27, 28, 30, 32, 22, 24, 25, 27, 28, 30, 32, 33, 24, 25, 27, 28, 30, 32, 33, 35 }; const mfxI32 pre_norm_adjust_index4x4[16] = {// 0 1 2 3 0,2,0,2,//0 2,1,2,1,//1 0,2,0,2,//2 2,1,2,1 //3 }; const mfxI32 pre_norm_adjust4x4[6][3] = { {10,16,13}, {11,18,14}, {13,20,16}, {14,23,18}, {16,25,20}, {18,29,23} }; const mfxI32 pre_norm_adjust8x8[6][6] = { {20, 18, 32, 19, 25, 24}, {22, 19, 35, 21, 28, 26}, {26, 23, 42, 24, 33, 31}, {28, 25, 45, 26, 35, 33}, {32, 28, 51, 30, 40, 38}, {36, 32, 58, 34, 46, 43} }; const mfxI32 pre_norm_adjust_index8x8[64] = {// 0 1 2 3 4 5 6 7 0,3,4,3,0,3,4,3,//0 3,1,5,1,3,1,5,1,//1 4,5,2,5,4,5,2,5,//2 3,1,5,1,3,1,5,1,//3 0,3,4,3,0,3,4,3,//4 3,1,5,1,3,1,5,1,//5 4,5,2,5,4,5,2,5,//6 3,1,5,1,3,1,5,1 //7 }; const mfxI32 mp_scan4x4[2][16] = { { 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15 }, { 0, 4, 1, 8, 12, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15 } }; const mfxI32 hp_scan4x4[2][4][16] = { { { 0, 1, 8,16, 9, 2, 3,10, 17,24,25,18, 11,19,26,27 }, { 4, 5,12,20, 13, 6, 7,14, 21,28,29,22, 15,23,30,31 }, { 32,33,40,48, 41,34,35,42, 49,56,57,50, 43,51,58,59 }, { 36,37,44,52, 45,38,39,46, 53,60,61,54, 47,55,62,63 }, }, { { 0, 8, 1,16, 24, 9,17,25, 2,10,18,26, 3,11,19,27 }, { 4,12, 5,20, 28,13,21,29, 6,14,22,30, 7,15,23,31 }, { 32,40,33,48, 56,41,49,57, 34,42,50,58, 35,43,51,59 }, { 36,44,37,52, 60,45,53,61, 38,46,54,62, 39,47,55,63 } } }; const mfxI32 hp_scan8x8[2][64] = { //8x8 zigzag scan { 0, 1, 8,16, 9, 2, 3,10, 17,24,32,25,18,11, 4, 5, 12,19,26,33,40,48,41,34, 27,20,13, 6, 7,14,21,28, 35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51, 58,59,52,45,38,31,39,46, 53,60,61,54,47,55,62,63 }, //8x8 field scan { 0, 8,16, 1, 9,24,32,17, 2,25,40,48,56,33,10, 3, 18,41,49,57,26,11, 4,19, 34,42,50,58,27,12, 5,20, 35,43,51,59,28,13, 6,21, 36,44,52,60,29,14,22,37, 45,53,61,30, 7,15,38,46, 54,62,23,31,39,47,55,63 } }; #define avcSkipNBits(current_data, offset, nbits) \ { \ /* check error(s) */ \ SAMPLE_ASSERT((nbits) > 0 && (nbits) <= 32); \ SAMPLE_ASSERT(offset >= 0 && offset <= 31); \ /* decrease number of available bits */ \ offset -= (nbits); \ /* normalize bitstream pointer */ \ if (0 > offset) \ { \ offset += 32; \ current_data++; \ } \ /* check error(s) again */ \ SAMPLE_ASSERT(offset >= 0 && offset <= 31); \ } #define avcGetBits8( current_data, offset, data) \ _avcGetBits(current_data, offset, 8, data); #define avcUngetNBits(current_data, offset, nbits) \ { \ SAMPLE_ASSERT(offset >= 0 && offset <= 31); \ \ offset += (nbits); \ if (offset > 31) \ { \ offset -= 32; \ current_data--; \ } \ \ SAMPLE_ASSERT(offset >= 0 && offset <= 31); \ } #define avcUngetBits32(current_data, offset) \ SAMPLE_ASSERT(offset >= 0 && offset <= 31); \ current_data--; #define avcAlignBSPointerRight(current_data, offset) \ { \ if ((offset & 0x07) != 0x07) \ { \ offset = (offset | 0x07) - 8; \ if (offset == -1) \ { \ offset = 31; \ current_data++; \ } \ } \ } #define avcNextBits(current_data, bp, nbits, data) \ { \ mfxU32 x; \ \ SAMPLE_ASSERT((nbits) > 0 && (nbits) <= 32); \ SAMPLE_ASSERT(nbits >= 0 && nbits <= 31); \ \ mfxI32 offset = bp - (nbits); \ \ if (offset >= 0) \ { \ x = current_data[0] >> (offset + 1); \ } \ else \ { \ offset += 32; \ \ x = current_data[1] >> (offset); \ x >>= 1; \ x += current_data[0] << (31 - offset); \ } \ \ SAMPLE_ASSERT(offset >= 0 && offset <= 31); \ \ (data) = x & bits_data[nbits]; \ } inline void FillFlatScalingList4x4(AVCScalingList4x4 *scl) { for (mfxI32 i=0;i<16;i++) scl->ScalingListCoeffs[i] = 16; } inline void FillFlatScalingList8x8(AVCScalingList8x8 *scl) { for (mfxI32 i=0;i<64;i++) scl->ScalingListCoeffs[i] = 16; } inline void FillScalingList4x4(AVCScalingList4x4 *scl_dst,mfxU8 *coefs_src) { for (mfxI32 i=0;i<16;i++) scl_dst->ScalingListCoeffs[i] = coefs_src[i]; } inline void FillScalingList8x8(AVCScalingList8x8 *scl_dst,mfxU8 *coefs_src) { for (mfxI32 i=0;i<64;i++) scl_dst->ScalingListCoeffs[i] = coefs_src[i]; } AVCBaseBitstream::AVCBaseBitstream() { Reset(0, 0); } AVCBaseBitstream::AVCBaseBitstream(mfxU8 * const pb, const mfxU32 maxsize) { Reset(pb, maxsize); } AVCBaseBitstream::~AVCBaseBitstream() { } void AVCBaseBitstream::Reset(mfxU8 * const pb, const mfxU32 maxsize) { m_pbs = (mfxU32*)pb; m_pbsBase = (mfxU32*)pb; m_bitOffset = 31; m_maxBsSize = maxsize; } // void Reset(mfxU8 * const pb, const mfxU32 maxsize) void AVCBaseBitstream::Reset(mfxU8 * const pb, mfxI32 offset, const mfxU32 maxsize) { m_pbs = (mfxU32*)pb; m_pbsBase = (mfxU32*)pb; m_bitOffset = offset; m_maxBsSize = maxsize; } // void Reset(mfxU8 * const pb, mfxI32 offset, const mfxU32 maxsize) mfxStatus AVCBaseBitstream::GetNALUnitType( NAL_Unit_Type &uNALUnitType,mfxU8 &uNALStorageIDC) { mfxU32 code; avcGetBits8(m_pbs, m_bitOffset, code); uNALStorageIDC = (mfxU8)((code & NAL_STORAGE_IDC_BITS)>>5); uNALUnitType = (NAL_Unit_Type)(code & NAL_UNITTYPE_BITS); return MFX_ERR_NONE; } // GetNALUnitType mfxI32 AVCBaseBitstream::GetVLCElement(bool bIsSigned) { mfxI32 sval = 0; mfxStatus ippRes = DecodeExpGolombOne(&m_pbs, &m_bitOffset, &sval, bIsSigned); if (ippRes < MFX_ERR_NONE) throw AVC_exception(MFX_ERR_UNDEFINED_BEHAVIOR); return sval; } void AVCBaseBitstream::AlignPointerRight(void) { avcAlignBSPointerRight(m_pbs, m_bitOffset); } // void AVCBitstream::AlignPointerRight(void) bool AVCBaseBitstream::More_RBSP_Data() { mfxI32 code, tmp; mfxU32* ptr_state = m_pbs; mfxI32 bit_state = m_bitOffset; SAMPLE_ASSERT(m_bitOffset >= 0 && m_bitOffset <= 31); mfxI32 remaining_bytes = (mfxI32)BytesLeft(); if (remaining_bytes <= 0) return false; // get top bit, it can be "rbsp stop" bit avcGetNBits(m_pbs, m_bitOffset, 1, code); // get remain bits, which is less then byte tmp = (m_bitOffset + 1) % 8; if(tmp) { avcGetNBits(m_pbs, m_bitOffset, tmp, code); if ((code << (8 - tmp)) & 0x7f) // most sig bit could be rbsp stop bit { m_pbs = ptr_state; m_bitOffset = bit_state; // there are more data return true; } } remaining_bytes = (mfxI32)BytesLeft(); // run through remain bytes while (0 < remaining_bytes) { avcGetBits8(m_pbs, m_bitOffset, code); if (code) { m_pbs = ptr_state; m_bitOffset = bit_state; // there are more data return true; } remaining_bytes -= 1; } return false; } AVCHeadersBitstream::AVCHeadersBitstream() : AVCBaseBitstream() { } AVCHeadersBitstream::AVCHeadersBitstream(mfxU8 * const pb, const mfxU32 maxsize) : AVCBaseBitstream(pb, maxsize) { } // --------------------------------------------------------------------------- // AVCBitstream::GetSequenceParamSet() // Read sequence parameter set data from bitstream. // --------------------------------------------------------------------------- mfxStatus AVCHeadersBitstream::GetSequenceParamSet(AVCSeqParamSet *sps) { // Not all members of the seq param set structure are contained in all // seq param sets. So start by init all to zero. mfxStatus ps = MFX_ERR_NONE; sps->Reset(); // profile sps->profile_idc = (mfxU8)GetBits(8); switch (sps->profile_idc) { case AVC_PROFILE_BASELINE: case AVC_PROFILE_MAIN: case AVC_PROFILE_SCALABLE_BASELINE: case AVC_PROFILE_SCALABLE_HIGH: case AVC_PROFILE_EXTENDED: case AVC_PROFILE_HIGH: case AVC_PROFILE_HIGH10: case AVC_PROFILE_MULTIVIEW_HIGH: case AVC_PROFILE_HIGH422: case AVC_PROFILE_STEREO_HIGH: case AVC_PROFILE_HIGH444: case AVC_PROFILE_ADVANCED444_INTRA: case AVC_PROFILE_ADVANCED444: break; default: return MFX_ERR_UNDEFINED_BEHAVIOR; } sps->constrained_set0_flag = (mfxU8)Get1Bit(); sps->constrained_set1_flag = (mfxU8)Get1Bit(); sps->constrained_set2_flag = (mfxU8)Get1Bit(); sps->constrained_set3_flag = (mfxU8)Get1Bit(); // skip 4 zero bits GetBits(4); sps->level_idc = (mfxU8)GetBits(8); switch(sps->level_idc) { case AVC_LEVEL_1: case AVC_LEVEL_11: case AVC_LEVEL_12: case AVC_LEVEL_13: case AVC_LEVEL_2: case AVC_LEVEL_21: case AVC_LEVEL_22: case AVC_LEVEL_3: case AVC_LEVEL_31: case AVC_LEVEL_32: case AVC_LEVEL_4: case AVC_LEVEL_41: case AVC_LEVEL_42: case AVC_LEVEL_5: case AVC_LEVEL_51: break; default: return MFX_ERR_UNDEFINED_BEHAVIOR; } // id mfxI32 sps_id = GetVLCElement(false); if (sps_id > MAX_NUM_SEQ_PARAM_SETS - 1) { return MFX_ERR_UNDEFINED_BEHAVIOR; } sps->seq_parameter_set_id = (mfxU8)sps_id; // see 7.3.2.1.1 "Sequence parameter set data syntax" // chapter of H264 standard for full list of profiles with chrominance if ((AVC_PROFILE_SCALABLE_BASELINE == sps->profile_idc) || (AVC_PROFILE_SCALABLE_HIGH == sps->profile_idc) || (AVC_PROFILE_HIGH == sps->profile_idc) || (AVC_PROFILE_HIGH10 == sps->profile_idc) || (AVC_PROFILE_MULTIVIEW_HIGH == sps->profile_idc) || (AVC_PROFILE_HIGH422 == sps->profile_idc) || (AVC_PROFILE_STEREO_HIGH == sps->profile_idc) || (244 == sps->profile_idc) || (44 == sps->profile_idc)) { mfxU32 chroma_format_idc = GetVLCElement(false); if (chroma_format_idc > 3) return MFX_ERR_UNDEFINED_BEHAVIOR; sps->chroma_format_idc = (mfxU8)chroma_format_idc; if (sps->chroma_format_idc==3) { sps->residual_colour_transform_flag = (mfxU8) Get1Bit(); } mfxU32 bit_depth_luma = GetVLCElement(false) + 8; mfxU32 bit_depth_chroma = GetVLCElement(false) + 8; if (bit_depth_luma > 16 || bit_depth_chroma > 16) return MFX_ERR_UNDEFINED_BEHAVIOR; sps->bit_depth_luma = (mfxU8)bit_depth_luma; sps->bit_depth_chroma = (mfxU8)bit_depth_chroma; if (!chroma_format_idc) sps->bit_depth_chroma = sps->bit_depth_luma; SAMPLE_ASSERT(!sps->residual_colour_transform_flag); if (sps->residual_colour_transform_flag == 1) { return MFX_ERR_UNDEFINED_BEHAVIOR; } sps->qpprime_y_zero_transform_bypass_flag = (mfxU8)Get1Bit(); sps->seq_scaling_matrix_present_flag = (mfxU8)Get1Bit(); if(sps->seq_scaling_matrix_present_flag) { // 0 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[0],(mfxU8*)default_intra_scaling_list4x4,&sps->type_of_scaling_list_used[0]); } else { FillScalingList4x4(&sps->ScalingLists4x4[0],(mfxU8*) default_intra_scaling_list4x4); sps->type_of_scaling_list_used[0] = SCLDEFAULT; } // 1 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[1],(mfxU8*) default_intra_scaling_list4x4,&sps->type_of_scaling_list_used[1]); } else { FillScalingList4x4(&sps->ScalingLists4x4[1],(mfxU8*) sps->ScalingLists4x4[0].ScalingListCoeffs); sps->type_of_scaling_list_used[1] = SCLDEFAULT; } // 2 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[2],(mfxU8*) default_intra_scaling_list4x4,&sps->type_of_scaling_list_used[2]); } else { FillScalingList4x4(&sps->ScalingLists4x4[2],(mfxU8*) sps->ScalingLists4x4[1].ScalingListCoeffs); sps->type_of_scaling_list_used[2] = SCLDEFAULT; } // 3 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[3],(mfxU8*)default_inter_scaling_list4x4,&sps->type_of_scaling_list_used[3]); } else { FillScalingList4x4(&sps->ScalingLists4x4[3],(mfxU8*) default_inter_scaling_list4x4); sps->type_of_scaling_list_used[3] = SCLDEFAULT; } // 4 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[4],(mfxU8*) default_inter_scaling_list4x4,&sps->type_of_scaling_list_used[4]); } else { FillScalingList4x4(&sps->ScalingLists4x4[4],(mfxU8*) sps->ScalingLists4x4[3].ScalingListCoeffs); sps->type_of_scaling_list_used[4] = SCLDEFAULT; } // 5 if(Get1Bit()) { GetScalingList4x4(&sps->ScalingLists4x4[5],(mfxU8*) default_inter_scaling_list4x4,&sps->type_of_scaling_list_used[5]); } else { FillScalingList4x4(&sps->ScalingLists4x4[5],(mfxU8*) sps->ScalingLists4x4[4].ScalingListCoeffs); sps->type_of_scaling_list_used[5] = SCLDEFAULT; } // 0 if(Get1Bit()) { GetScalingList8x8(&sps->ScalingLists8x8[0],(mfxU8*)default_intra_scaling_list8x8,&sps->type_of_scaling_list_used[6]); } else { FillScalingList8x8(&sps->ScalingLists8x8[0],(mfxU8*) default_intra_scaling_list8x8); sps->type_of_scaling_list_used[6] = SCLDEFAULT; } // 1 if(Get1Bit()) { GetScalingList8x8(&sps->ScalingLists8x8[1],(mfxU8*) default_inter_scaling_list8x8,&sps->type_of_scaling_list_used[7]); } else { FillScalingList8x8(&sps->ScalingLists8x8[1],(mfxU8*) default_inter_scaling_list8x8); sps->type_of_scaling_list_used[7] = SCLDEFAULT; } } else { mfxI32 i; for (i = 0; i < 6; i += 1) { FillFlatScalingList4x4(&sps->ScalingLists4x4[i]); } for (i = 0; i < 2; i += 1) { FillFlatScalingList8x8(&sps->ScalingLists8x8[i]); } } } else { sps->chroma_format_idc = 1; sps->bit_depth_luma = 8; sps->bit_depth_chroma = 8; SetDefaultScalingLists(sps); } // log2 max frame num (bitstream contains value - 4) mfxU32 log2_max_frame_num = GetVLCElement(false) + 4; sps->log2_max_frame_num = (mfxU8)log2_max_frame_num; if (log2_max_frame_num > 16 || log2_max_frame_num < 4) return MFX_ERR_UNDEFINED_BEHAVIOR; // pic order cnt type (0..2) mfxU32 pic_order_cnt_type = GetVLCElement(false); sps->pic_order_cnt_type = (mfxU8)pic_order_cnt_type; if (pic_order_cnt_type > 2) { return MFX_ERR_UNDEFINED_BEHAVIOR; } if (sps->pic_order_cnt_type == 0) { // log2 max pic order count lsb (bitstream contains value - 4) mfxU32 log2_max_pic_order_cnt_lsb = GetVLCElement(false) + 4; sps->log2_max_pic_order_cnt_lsb = (mfxU8)log2_max_pic_order_cnt_lsb; if (log2_max_pic_order_cnt_lsb > 16 || log2_max_pic_order_cnt_lsb < 4) return MFX_ERR_UNDEFINED_BEHAVIOR; sps->MaxPicOrderCntLsb = (1 << sps->log2_max_pic_order_cnt_lsb); } else if (sps->pic_order_cnt_type == 1) { sps->delta_pic_order_always_zero_flag = (mfxU8)Get1Bit(); sps->offset_for_non_ref_pic = GetVLCElement(true); sps->offset_for_top_to_bottom_field = GetVLCElement(true); sps->num_ref_frames_in_pic_order_cnt_cycle = GetVLCElement(false); if (sps->num_ref_frames_in_pic_order_cnt_cycle > 255) return MFX_ERR_UNDEFINED_BEHAVIOR; // get offsets for (mfxU32 i = 0; i < sps->num_ref_frames_in_pic_order_cnt_cycle; i++) { sps->poffset_for_ref_frame[i] = GetVLCElement(true); } } // pic order count type 1 // num ref frames sps->num_ref_frames = GetVLCElement(false); if (sps->num_ref_frames > 16) return MFX_ERR_UNDEFINED_BEHAVIOR; sps->gaps_in_frame_num_value_allowed_flag = (mfxU8)Get1Bit(); // picture width in MBs (bitstream contains value - 1) sps->frame_width_in_mbs = GetVLCElement(false) + 1; // picture height in MBs (bitstream contains value - 1) sps->frame_height_in_mbs = GetVLCElement(false) + 1; sps->frame_mbs_only_flag = (mfxU8)Get1Bit(); sps->frame_height_in_mbs = (2-sps->frame_mbs_only_flag)*sps->frame_height_in_mbs; if (sps->frame_mbs_only_flag == 0) { sps->mb_adaptive_frame_field_flag = (mfxU8)Get1Bit(); } sps->direct_8x8_inference_flag = (mfxU8)Get1Bit(); if (sps->frame_mbs_only_flag==0) { sps->direct_8x8_inference_flag = 1; } sps->frame_cropping_flag = (mfxU8)Get1Bit(); if (sps->frame_cropping_flag) { sps->frame_cropping_rect_left_offset = GetVLCElement(false); sps->frame_cropping_rect_right_offset = GetVLCElement(false); sps->frame_cropping_rect_top_offset = GetVLCElement(false); sps->frame_cropping_rect_bottom_offset = GetVLCElement(false); } // don't need else because we zeroid structure sps->vui_parameters_present_flag = (mfxU8)Get1Bit(); if (sps->vui_parameters_present_flag) { if (ps == MFX_ERR_NONE) ps = GetVUIParam(sps); } return ps; } // GetSequenceParamSet mfxStatus AVCHeadersBitstream::GetVUIParam(AVCSeqParamSet *sps) { mfxStatus ps=MFX_ERR_NONE; sps->aspect_ratio_info_present_flag = (mfxU8) Get1Bit(); sps->sar_width = 1; // default values sps->sar_height = 1; if (sps->aspect_ratio_info_present_flag) { sps->aspect_ratio_idc = (mfxU8) GetBits(8); if (sps->aspect_ratio_idc == 255) { sps->sar_width = (mfxU16) GetBits(16); sps->sar_height = (mfxU16) GetBits(16); } } sps->overscan_info_present_flag = (mfxU8) Get1Bit(); if( sps->overscan_info_present_flag ) sps->overscan_appropriate_flag = (mfxU8) Get1Bit(); sps->video_signal_type_present_flag = (mfxU8) Get1Bit(); if( sps->video_signal_type_present_flag ) { sps->video_format = (mfxU8) GetBits(3); sps->video_full_range_flag = (mfxU8) Get1Bit(); sps->colour_description_present_flag = (mfxU8) Get1Bit(); if( sps->colour_description_present_flag ) { sps->colour_primaries = (mfxU8) GetBits(8); sps->transfer_characteristics = (mfxU8) GetBits(8); sps->matrix_coefficients = (mfxU8) GetBits(8); } } sps->chroma_loc_info_present_flag = (mfxU8) Get1Bit(); if( sps->chroma_loc_info_present_flag ) { sps->chroma_sample_loc_type_top_field = (mfxU8) GetVLCElement(false); sps->chroma_sample_loc_type_bottom_field = (mfxU8) GetVLCElement(false); } sps->timing_info_present_flag = (mfxU8) Get1Bit(); if (sps->timing_info_present_flag) { sps->num_units_in_tick = GetBits(32); sps->time_scale = GetBits(32); sps->fixed_frame_rate_flag = (mfxU8) Get1Bit(); if (!sps->num_units_in_tick || !sps->time_scale) sps->timing_info_present_flag = 0; } sps->nal_hrd_parameters_present_flag = (mfxU8) Get1Bit(); if( sps->nal_hrd_parameters_present_flag ) ps=GetHRDParam(sps); sps->vcl_hrd_parameters_present_flag = (mfxU8) Get1Bit(); if( sps->vcl_hrd_parameters_present_flag ) ps=GetHRDParam(sps); if( sps->nal_hrd_parameters_present_flag || sps->vcl_hrd_parameters_present_flag ) sps->low_delay_hrd_flag = (mfxU8) Get1Bit(); sps->pic_struct_present_flag = (mfxU8) Get1Bit(); sps->bitstream_restriction_flag = (mfxU8) Get1Bit(); if( sps->bitstream_restriction_flag ) { sps->motion_vectors_over_pic_boundaries_flag = (mfxU8) Get1Bit(); sps->max_bytes_per_pic_denom = (mfxU8) GetVLCElement(false); sps->max_bits_per_mb_denom = (mfxU8) GetVLCElement(false); sps->log2_max_mv_length_horizontal = (mfxU8) GetVLCElement(false); sps->log2_max_mv_length_vertical = (mfxU8) GetVLCElement(false); sps->num_reorder_frames = (mfxU8) GetVLCElement(false); mfxI32 value = GetVLCElement(false); if (value < (mfxI32)sps->num_ref_frames || value < 0) { return MFX_ERR_UNDEFINED_BEHAVIOR; } sps->max_dec_frame_buffering = (mfxU8) GetVLCElement(false); } return ps; } mfxStatus AVCHeadersBitstream::GetHRDParam(AVCSeqParamSet *sps) { mfxStatus ps=MFX_ERR_NONE; mfxI32 cpb_cnt = GetVLCElement(false) + 1; if (cpb_cnt >= 32) { return MFX_ERR_UNDEFINED_BEHAVIOR; } sps->cpb_cnt = (mfxU8)cpb_cnt; sps->bit_rate_scale = (mfxU8) GetBits(4); sps->cpb_size_scale = (mfxU8) GetBits(4); for( mfxI32 idx= 0; idx < sps->cpb_cnt; idx++ ) { sps->bit_rate_value[ idx ] = (mfxU32) (GetVLCElement(false)+1); sps->cpb_size_value[ idx ] = (mfxU32) ((GetVLCElement(false)+1)); sps->cbr_flag[ idx ] = (mfxU8) Get1Bit(); } sps->initial_cpb_removal_delay_length = (mfxU8)(GetBits(5)+1); sps->cpb_removal_delay_length = (mfxU8)(GetBits(5)+1); sps->dpb_output_delay_length = (mfxU8) (GetBits(5)+1); sps->time_offset_length = (mfxU8) GetBits(5); return ps; } // --------------------------------------------------------------------------- // Read sequence parameter set extension data from bitstream. // --------------------------------------------------------------------------- mfxStatus AVCHeadersBitstream::GetSequenceParamSetExtension(AVCSeqParamSetExtension *sps_ex) { // Not all members of the seq param set structure are contained in all // seq param sets. So start by init all to zero. mfxStatus ps = MFX_ERR_NONE; sps_ex->Reset(); mfxU32 seq_parameter_set_id = GetVLCElement(false); sps_ex->seq_parameter_set_id = (mfxU8)seq_parameter_set_id; if (seq_parameter_set_id > MAX_NUM_SEQ_PARAM_SETS-1) { return MFX_ERR_UNDEFINED_BEHAVIOR; } mfxU32 aux_format_idc = GetVLCElement(false); sps_ex->aux_format_idc = (mfxU8)aux_format_idc; if (aux_format_idc > 3) { return MFX_ERR_UNDEFINED_BEHAVIOR; } if (sps_ex->aux_format_idc != 1 && sps_ex->aux_format_idc != 2) sps_ex->aux_format_idc = 0; if (sps_ex->aux_format_idc) { mfxU32 bit_depth_aux = GetVLCElement(false) + 8; sps_ex->bit_depth_aux = (mfxU8)bit_depth_aux; if (bit_depth_aux > 12) { return MFX_ERR_UNDEFINED_BEHAVIOR; } sps_ex->alpha_incr_flag = (mfxU8)Get1Bit(); sps_ex->alpha_opaque_value = (mfxU8)GetBits(sps_ex->bit_depth_aux + 1); sps_ex->alpha_transparent_value = (mfxU8)GetBits(sps_ex->bit_depth_aux + 1); } sps_ex->additional_extension_flag = (mfxU8)Get1Bit(); return ps; } // GetSequenceParamSetExtension mfxStatus AVCHeadersBitstream::GetPictureParamSetPart1(AVCPicParamSet *pps) { // Not all members of the pic param set structure are contained in all // pic param sets. So start by init all to zero. pps->Reset(); // id mfxU32 pic_parameter_set_id = GetVLCElement(false); pps->pic_parameter_set_id = (mfxU16)pic_parameter_set_id; if (pic_parameter_set_id > MAX_NUM_PIC_PARAM_SETS-1) { return MFX_ERR_UNDEFINED_BEHAVIOR; } // seq param set referred to by this pic param set mfxU32 seq_parameter_set_id = GetVLCElement(false); pps->seq_parameter_set_id = (mfxU8)seq_parameter_set_id; if (seq_parameter_set_id > MAX_NUM_SEQ_PARAM_SETS-1) { return MFX_ERR_UNDEFINED_BEHAVIOR; } return MFX_ERR_NONE; } // GetPictureParamSetPart1 // Number of bits required to code slice group ID, index is num_slice_groups - 2 static const mfxU8 SGIdBits[7] = {1,2,2,3,3,3,3}; // --------------------------------------------------------------------------- // Read picture parameter set data from bitstream. // --------------------------------------------------------------------------- mfxStatus AVCHeadersBitstream::GetPictureParamSetPart2(AVCPicParamSet *pps, const AVCSeqParamSet *sps) { pps->entropy_coding_mode = (mfxU8)Get1Bit(); pps->pic_order_present_flag = (mfxU8)Get1Bit(); // number of slice groups, bitstream has value - 1 pps->num_slice_groups = GetVLCElement(false) + 1; if (pps->num_slice_groups != 1) { mfxU32 slice_group; mfxU32 PicSizeInMapUnits; // for range checks PicSizeInMapUnits = sps->frame_width_in_mbs * sps->frame_height_in_mbs; // TBD: needs adjust for fields if (pps->num_slice_groups > MAX_NUM_SLICE_GROUPS) { return MFX_ERR_UNDEFINED_BEHAVIOR; } mfxU32 slice_group_map_type = GetVLCElement(false); pps->SliceGroupInfo.slice_group_map_type = (mfxU8)slice_group_map_type; if (slice_group_map_type > 6) return MFX_ERR_UNDEFINED_BEHAVIOR; // Get additional, map type dependent slice group data switch (pps->SliceGroupInfo.slice_group_map_type) { case 0: for (slice_group=0; slice_group<pps->num_slice_groups; slice_group++) { // run length, bitstream has value - 1 pps->SliceGroupInfo.run_length[slice_group] = GetVLCElement(false) + 1; if (pps->SliceGroupInfo.run_length[slice_group] > PicSizeInMapUnits) { return MFX_ERR_UNDEFINED_BEHAVIOR; } } break; case 1: // no additional info break; case 2: for (slice_group=0; slice_group<(mfxU32)(pps->num_slice_groups-1); slice_group++) { pps->SliceGroupInfo.t1.top_left[slice_group] = GetVLCElement(false); pps->SliceGroupInfo.t1.bottom_right[slice_group] = GetVLCElement(false); // check for legal values if (pps->SliceGroupInfo.t1.top_left[slice_group] > pps->SliceGroupInfo.t1.bottom_right[slice_group]) { return MFX_ERR_UNDEFINED_BEHAVIOR; } if (pps->SliceGroupInfo.t1.bottom_right[slice_group] >= PicSizeInMapUnits) { return MFX_ERR_UNDEFINED_BEHAVIOR; } if ((pps->SliceGroupInfo.t1.top_left[slice_group] % sps->frame_width_in_mbs) > (pps->SliceGroupInfo.t1.bottom_right[slice_group] % sps->frame_width_in_mbs)) { return MFX_ERR_UNDEFINED_BEHAVIOR; } } break; case 3: case 4: case 5: // For map types 3..5, number of slice groups must be 2 if (pps->num_slice_groups != 2) { return MFX_ERR_UNDEFINED_BEHAVIOR; } pps->SliceGroupInfo.t2.slice_group_change_direction_flag = (mfxU8)Get1Bit(); pps->SliceGroupInfo.t2.slice_group_change_rate = GetVLCElement(false) + 1; if (pps->SliceGroupInfo.t2.slice_group_change_rate > PicSizeInMapUnits) { return MFX_ERR_UNDEFINED_BEHAVIOR; } break; case 6: // mapping of slice group to map unit (macroblock if not fields) is // per map unit, read from bitstream { mfxU32 map_unit; mfxU32 num_bits; // number of bits used to code each slice group id // number of map units, bitstream has value - 1 pps->SliceGroupInfo.t3.pic_size_in_map_units = GetVLCElement(false) + 1; if (pps->SliceGroupInfo.t3.pic_size_in_map_units != PicSizeInMapUnits) { return MFX_ERR_UNDEFINED_BEHAVIOR; } mfxI32 len = MSDK_MAX(1, pps->SliceGroupInfo.t3.pic_size_in_map_units); pps->SliceGroupInfo.pSliceGroupIDMap.resize(len); // num_bits is Ceil(log2(num_groups)) num_bits = SGIdBits[pps->num_slice_groups - 2]; for (map_unit = 0; map_unit < pps->SliceGroupInfo.t3.pic_size_in_map_units; map_unit++) { pps->SliceGroupInfo.pSliceGroupIDMap[map_unit] = (mfxU8)GetBits(num_bits); if (pps->SliceGroupInfo.pSliceGroupIDMap[map_unit] > pps->num_slice_groups - 1) { return MFX_ERR_UNDEFINED_BEHAVIOR; } } } break; default: return MFX_ERR_UNDEFINED_BEHAVIOR; } // switch } // slice group info // number of list 0 ref pics used to decode picture, bitstream has value - 1 pps->num_ref_idx_l0_active = GetVLCElement(false) + 1; // number of list 1 ref pics used to decode picture, bitstream has value - 1 pps->num_ref_idx_l1_active = GetVLCElement(false) + 1; if (pps->num_ref_idx_l1_active > MAX_NUM_REF_FRAMES || pps->num_ref_idx_l0_active > MAX_NUM_REF_FRAMES) return MFX_ERR_UNDEFINED_BEHAVIOR; // weighted pediction pps->weighted_pred_flag = (mfxU8)Get1Bit(); pps->weighted_bipred_idc = (mfxU8)GetBits(2); // default slice QP, bitstream has value - 26 mfxI32 pic_init_qp = GetVLCElement(true) + 26; pps->pic_init_qp = (mfxI8)pic_init_qp; // default SP/SI slice QP, bitstream has value - 26 pps->pic_init_qs = (mfxU8)(GetVLCElement(true) + 26); pps->chroma_qp_index_offset[0] = (mfxI8)GetVLCElement(true); pps->deblocking_filter_variables_present_flag = (mfxU8)Get1Bit(); pps->constrained_intra_pred_flag = (mfxU8)Get1Bit(); pps->redundant_pic_cnt_present_flag = (mfxU8)Get1Bit(); if (More_RBSP_Data()) { pps->transform_8x8_mode_flag = (mfxU8) Get1Bit(); if(sps->seq_scaling_matrix_present_flag) { //fall-back set rule B if(Get1Bit()) { // 0 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[0],(mfxU8*)default_intra_scaling_list4x4,&pps->type_of_scaling_list_used[0]); } else { FillScalingList4x4(&pps->ScalingLists4x4[0],(mfxU8*) sps->ScalingLists4x4[0].ScalingListCoeffs); pps->type_of_scaling_list_used[0] = SCLDEFAULT; } // 1 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[1],(mfxU8*) default_intra_scaling_list4x4,&pps->type_of_scaling_list_used[1]); } else { FillScalingList4x4(&pps->ScalingLists4x4[1],(mfxU8*) pps->ScalingLists4x4[0].ScalingListCoeffs); pps->type_of_scaling_list_used[1] = SCLDEFAULT; } // 2 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[2],(mfxU8*) default_intra_scaling_list4x4,&pps->type_of_scaling_list_used[2]); } else { FillScalingList4x4(&pps->ScalingLists4x4[2],(mfxU8*) pps->ScalingLists4x4[1].ScalingListCoeffs); pps->type_of_scaling_list_used[2] = SCLDEFAULT; } // 3 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[3],(mfxU8*) default_inter_scaling_list4x4,&pps->type_of_scaling_list_used[3]); } else { FillScalingList4x4(&pps->ScalingLists4x4[3],(mfxU8*) sps->ScalingLists4x4[3].ScalingListCoeffs); pps->type_of_scaling_list_used[3] = SCLDEFAULT; } // 4 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[4],(mfxU8*) default_inter_scaling_list4x4,&pps->type_of_scaling_list_used[4]); } else { FillScalingList4x4(&pps->ScalingLists4x4[4],(mfxU8*) pps->ScalingLists4x4[3].ScalingListCoeffs); pps->type_of_scaling_list_used[4] = SCLDEFAULT; } // 5 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[5],(mfxU8*) default_inter_scaling_list4x4,&pps->type_of_scaling_list_used[5]); } else { FillScalingList4x4(&pps->ScalingLists4x4[5],(mfxU8*) pps->ScalingLists4x4[4].ScalingListCoeffs); pps->type_of_scaling_list_used[5] = SCLDEFAULT; } if (pps->transform_8x8_mode_flag) { // 0 if(Get1Bit()) { GetScalingList8x8(&pps->ScalingLists8x8[0],(mfxU8*)default_intra_scaling_list8x8,&pps->type_of_scaling_list_used[6]); } else { FillScalingList8x8(&pps->ScalingLists8x8[0],(mfxU8*) sps->ScalingLists8x8[0].ScalingListCoeffs); pps->type_of_scaling_list_used[6] = SCLDEFAULT; } // 1 if(Get1Bit()) { GetScalingList8x8(&pps->ScalingLists8x8[1],(mfxU8*) default_inter_scaling_list8x8,&pps->type_of_scaling_list_used[7]); } else { FillScalingList8x8(&pps->ScalingLists8x8[1],(mfxU8*) sps->ScalingLists8x8[1].ScalingListCoeffs); pps->type_of_scaling_list_used[7] = SCLDEFAULT; } } } else { mfxI32 i; for(i=0; i<6; i++) { FillScalingList4x4(&pps->ScalingLists4x4[i],(mfxU8 *)sps->ScalingLists4x4[i].ScalingListCoeffs); pps->type_of_scaling_list_used[i] = sps->type_of_scaling_list_used[i]; } if (pps->transform_8x8_mode_flag) { for(i=0; i<2; i++) { FillScalingList8x8(&pps->ScalingLists8x8[i],(mfxU8 *)sps->ScalingLists8x8[i].ScalingListCoeffs); pps->type_of_scaling_list_used[i] = sps->type_of_scaling_list_used[i]; } } } } else { //fall-back set rule A if(Get1Bit()) { // 0 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[0],(mfxU8*)default_intra_scaling_list4x4,&pps->type_of_scaling_list_used[0]); } else { FillScalingList4x4(&pps->ScalingLists4x4[0],(mfxU8*) default_intra_scaling_list4x4); pps->type_of_scaling_list_used[0] = SCLDEFAULT; } // 1 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[1],(mfxU8*) default_intra_scaling_list4x4,&pps->type_of_scaling_list_used[1]); } else { FillScalingList4x4(&pps->ScalingLists4x4[1],(mfxU8*) pps->ScalingLists4x4[0].ScalingListCoeffs); pps->type_of_scaling_list_used[1] = SCLDEFAULT; } // 2 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[2],(mfxU8*) default_intra_scaling_list4x4,&pps->type_of_scaling_list_used[2]); } else { FillScalingList4x4(&pps->ScalingLists4x4[2],(mfxU8*) pps->ScalingLists4x4[1].ScalingListCoeffs); pps->type_of_scaling_list_used[2] = SCLDEFAULT; } // 3 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[3],(mfxU8*)default_inter_scaling_list4x4,&pps->type_of_scaling_list_used[3]); } else { FillScalingList4x4(&pps->ScalingLists4x4[3],(mfxU8*) default_inter_scaling_list4x4); pps->type_of_scaling_list_used[3] = SCLDEFAULT; } // 4 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[4],(mfxU8*) default_inter_scaling_list4x4,&pps->type_of_scaling_list_used[4]); } else { FillScalingList4x4(&pps->ScalingLists4x4[4],(mfxU8*) pps->ScalingLists4x4[3].ScalingListCoeffs); pps->type_of_scaling_list_used[4] = SCLDEFAULT; } // 5 if(Get1Bit()) { GetScalingList4x4(&pps->ScalingLists4x4[5],(mfxU8*) default_inter_scaling_list4x4,&pps->type_of_scaling_list_used[5]); } else { FillScalingList4x4(&pps->ScalingLists4x4[5],(mfxU8*) pps->ScalingLists4x4[4].ScalingListCoeffs); pps->type_of_scaling_list_used[5] = SCLDEFAULT; } if (pps->transform_8x8_mode_flag) { // 0 if(Get1Bit()) { GetScalingList8x8(&pps->ScalingLists8x8[0],(mfxU8*)default_intra_scaling_list8x8,&pps->type_of_scaling_list_used[6]); } else { FillScalingList8x8(&pps->ScalingLists8x8[0],(mfxU8*) default_intra_scaling_list8x8); pps->type_of_scaling_list_used[6] = SCLDEFAULT; } // 1 if(Get1Bit()) { GetScalingList8x8(&pps->ScalingLists8x8[1],(mfxU8*) default_inter_scaling_list8x8,&pps->type_of_scaling_list_used[7]); } else { FillScalingList8x8(&pps->ScalingLists8x8[1],(mfxU8*) default_inter_scaling_list8x8); pps->type_of_scaling_list_used[7] = SCLDEFAULT; } } } else { mfxI32 i; for(i=0; i<6; i++) { FillScalingList4x4(&pps->ScalingLists4x4[i],(mfxU8 *)sps->ScalingLists4x4[i].ScalingListCoeffs); pps->type_of_scaling_list_used[i] = sps->type_of_scaling_list_used[i]; } if (pps->transform_8x8_mode_flag) { for(i=0; i<2; i++) { FillScalingList8x8(&pps->ScalingLists8x8[i],(mfxU8 *)sps->ScalingLists8x8[i].ScalingListCoeffs); pps->type_of_scaling_list_used[i] = sps->type_of_scaling_list_used[i]; } } } } pps->chroma_qp_index_offset[1] = (mfxI8)GetVLCElement(true); } else { pps->chroma_qp_index_offset[1] = pps->chroma_qp_index_offset[0]; mfxI32 i; for(i=0; i<6; i++) { FillScalingList4x4(&pps->ScalingLists4x4[i],(mfxU8 *)sps->ScalingLists4x4[i].ScalingListCoeffs); pps->type_of_scaling_list_used[i] = sps->type_of_scaling_list_used[i]; } if (pps->transform_8x8_mode_flag) { for(i=0; i<2; i++) { FillScalingList8x8(&pps->ScalingLists8x8[i],(mfxU8 *)sps->ScalingLists8x8[i].ScalingListCoeffs); pps->type_of_scaling_list_used[i] = sps->type_of_scaling_list_used[i]; } } } // calculate level scale matrices //start DC first //to do: reduce the number of matrices (in fact 1 is enough) mfxI32 i; // now process other 4x4 matrices for (i = 0; i < 6; i++) { for (mfxI32 j = 0; j < 88; j++) for (mfxI32 k = 0; k < 16; k++) { mfxU32 level_scale = pps->ScalingLists4x4[i].ScalingListCoeffs[k]*pre_norm_adjust4x4[j%6][pre_norm_adjust_index4x4[k]]; pps->m_LevelScale4x4[i].LevelScaleCoeffs[j][k] = (mfxI16) level_scale; } } // process remaining 8x8 matrices for (i = 0; i < 2; i++) { for (mfxI32 j = 0; j < 88; j++) for (mfxI32 k = 0; k < 64; k++) { mfxU32 level_scale = pps->ScalingLists8x8[i].ScalingListCoeffs[k]*pre_norm_adjust8x8[j%6][pre_norm_adjust_index8x8[k]]; pps->m_LevelScale8x8[i].LevelScaleCoeffs[j][k] = (mfxI16) level_scale; } } return MFX_ERR_NONE; } // GetPictureParamSet mfxStatus AVCHeadersBitstream::GetNalUnitPrefix(AVCNalExtension *pExt, mfxU32 ) { mfxStatus ps = MFX_ERR_NONE; ps = GetNalUnitExtension(pExt); if (ps != MFX_ERR_NONE || !pExt->svc_extension_flag) return ps; return ps; } mfxStatus AVCHeadersBitstream::GetNalUnitExtension(AVCNalExtension *pExt) { pExt->extension_present = 1; // decode the type of the extension pExt->svc_extension_flag = (mfxU8) GetBits(1); // decode SVC extension if (pExt->svc_extension_flag) { pExt->svc.idr_flag = (mfxU8) Get1Bit(); pExt->svc.priority_id = (mfxU8) GetBits(6); pExt->svc.no_inter_layer_pred_flag = (mfxU8) Get1Bit(); pExt->svc.dependency_id = (mfxU8) GetBits(3); pExt->svc.quality_id = (mfxU8) GetBits(4); pExt->svc.temporal_id = (mfxU8) GetBits(3); pExt->svc.use_ref_base_pic_flag = (mfxU8) Get1Bit(); pExt->svc.discardable_flag = (mfxU8) Get1Bit(); pExt->svc.output_flag = (mfxU8) Get1Bit(); GetBits(2); } // decode MVC extension else { pExt->mvc.non_idr_flag = (mfxU8) Get1Bit(); pExt->mvc.priority_id = (mfxU16) GetBits(6); pExt->mvc.view_id = (mfxU16) GetBits(10); pExt->mvc.temporal_id = (mfxU8) GetBits(3); pExt->mvc.anchor_pic_flag = (mfxU8) Get1Bit(); pExt->mvc.inter_view_flag = (mfxU8) Get1Bit(); GetBits(1); } return MFX_ERR_NONE; } // --------------------------------------------------------------------------- // Read H.264 first part of slice header // // Reading the rest of the header requires info in the picture and sequence // parameter sets referred to by this slice header. // // Do not print debug messages when IsSearch is true. In that case the function // is being used to find the next compressed frame, errors may occur and should // not be reported. // // --------------------------------------------------------------------------- mfxStatus AVCHeadersBitstream::GetSliceHeaderPart1(AVCSliceHeader *hdr) { mfxU32 val; // decode NAL extension if (NAL_UT_CODED_SLICE_EXTENSION == hdr->nal_unit_type) { GetNalUnitExtension(&hdr->nal_ext); // set the IDR flag if (hdr->nal_ext.svc_extension_flag) { hdr->IdrPicFlag = hdr->nal_ext.svc.idr_flag; } else { hdr->view_id = hdr->nal_ext.mvc.view_id; hdr->IdrPicFlag = hdr->nal_ext.mvc.non_idr_flag ^ 1; } } else { hdr->IdrPicFlag = (NAL_UT_IDR_SLICE == hdr->nal_unit_type) ? (1) : (0); hdr->nal_ext.mvc.anchor_pic_flag = (mfxU8) hdr->IdrPicFlag ? 1 : 0; hdr->nal_ext.mvc.inter_view_flag = (mfxU8) 1; } hdr->first_mb_in_slice = GetVLCElement(false); if (0 > hdr->first_mb_in_slice) // upper bound is checked in AVCSlice return MFX_ERR_UNDEFINED_BEHAVIOR; // slice type val = GetVLCElement(false); if (val > S_INTRASLICE) { if (val > S_INTRASLICE + S_INTRASLICE + 1) { return MFX_ERR_UNDEFINED_BEHAVIOR; } else { // Slice type is specifying type of not only this but all remaining // slices in the picture. Since slice type is always present, this bit // of info is not used in our implementation. Adjust (just shift range) // and return type without this extra info. val -= (S_INTRASLICE + 1); } } if (val > INTRASLICE) // all other doesn't support return MFX_ERR_UNDEFINED_BEHAVIOR; hdr->slice_type = (EnumSliceCodType)val; mfxU32 pic_parameter_set_id = GetVLCElement(false); hdr->pic_parameter_set_id = (mfxU16)pic_parameter_set_id; if (pic_parameter_set_id > MAX_NUM_PIC_PARAM_SETS - 1) { return MFX_ERR_UNDEFINED_BEHAVIOR; } return MFX_ERR_NONE; } // mfxStatus GetSliceHeaderPart1(AVCSliceHeader *pSliceHeader) mfxStatus AVCHeadersBitstream::GetSliceHeaderPart2( AVCSliceHeader *hdr, // slice header read goes here const AVCPicParamSet *pps, const AVCSeqParamSet *sps) // from slice header NAL unit { hdr->frame_num = GetBits(sps->log2_max_frame_num); hdr->bottom_field_flag = 0; if (sps->frame_mbs_only_flag == 0) { hdr->field_pic_flag = (mfxU8)Get1Bit(); hdr->MbaffFrameFlag = !hdr->field_pic_flag && sps->mb_adaptive_frame_field_flag; if (hdr->field_pic_flag != 0) { hdr->bottom_field_flag = (mfxU8)Get1Bit(); } } // correct frst_mb_in_slice in order to handle MBAFF if (hdr->MbaffFrameFlag && hdr->first_mb_in_slice) hdr->first_mb_in_slice <<= 1; if (hdr->IdrPicFlag) { mfxI32 pic_id = hdr->idr_pic_id = GetVLCElement(false); if (pic_id < 0 || pic_id > 65535) return MFX_ERR_UNDEFINED_BEHAVIOR; } if (sps->pic_order_cnt_type == 0) { hdr->pic_order_cnt_lsb = GetBits(sps->log2_max_pic_order_cnt_lsb); if (pps->pic_order_present_flag && (!hdr->field_pic_flag)) hdr->delta_pic_order_cnt_bottom = GetVLCElement(true); } if ((sps->pic_order_cnt_type == 1) && (sps->delta_pic_order_always_zero_flag == 0)) { hdr->delta_pic_order_cnt[0] = GetVLCElement(true); if (pps->pic_order_present_flag && (!hdr->field_pic_flag)) hdr->delta_pic_order_cnt[1] = GetVLCElement(true); } if (pps->redundant_pic_cnt_present_flag) { // redundant pic count hdr->redundant_pic_cnt = GetVLCElement(false); if (hdr->redundant_pic_cnt > 127) return MFX_ERR_UNDEFINED_BEHAVIOR; } return MFX_ERR_NONE; } // --------------------------------------------------------------------------- // Read H.264 second part of slice header // // Do not print debug messages when IsSearch is true. In that case the function // is being used to find the next compressed frame, errors may occur and should // not be reported. // --------------------------------------------------------------------------- mfxStatus AVCHeadersBitstream::GetSliceHeaderPart3( AVCSliceHeader *hdr, // slice header read goes here PredWeightTable *pPredWeight_L0, // L0 weight table goes here PredWeightTable *pPredWeight_L1, // L1 weight table goes here RefPicListReorderInfo *pReorderInfo_L0, RefPicListReorderInfo *pReorderInfo_L1, AdaptiveMarkingInfo *pAdaptiveMarkingInfo, const AVCPicParamSet *pps, const AVCSeqParamSet *sps, mfxU8 NALRef_idc) // from slice header NAL unit { mfxU8 ref_pic_list_reordering_flag_l0 = 0; mfxU8 ref_pic_list_reordering_flag_l1 = 0; if (BPREDSLICE == hdr->slice_type) { // direct mode prediction method hdr->direct_spatial_mv_pred_flag = (mfxU8)Get1Bit(); } if (PREDSLICE == hdr->slice_type || S_PREDSLICE == hdr->slice_type || BPREDSLICE == hdr->slice_type) { hdr->num_ref_idx_active_override_flag = (mfxU8)Get1Bit(); if (hdr->num_ref_idx_active_override_flag != 0) // ref idx active l0 and l1 { hdr->num_ref_idx_l0_active = GetVLCElement(false) + 1; if (BPREDSLICE == hdr->slice_type) hdr->num_ref_idx_l1_active = GetVLCElement(false) + 1; } else { // no overide, use num active from pic param set hdr->num_ref_idx_l0_active = pps->num_ref_idx_l0_active; if (BPREDSLICE == hdr->slice_type) hdr->num_ref_idx_l1_active = pps->num_ref_idx_l1_active; else hdr->num_ref_idx_l1_active = 0; } } // ref idx override if (hdr->num_ref_idx_l1_active > MAX_NUM_REF_FRAMES || hdr->num_ref_idx_l0_active > MAX_NUM_REF_FRAMES) return MFX_ERR_UNDEFINED_BEHAVIOR; if (hdr->slice_type != INTRASLICE && hdr->slice_type != S_INTRASLICE) { mfxU32 reordering_of_pic_nums_idc; mfxU32 reorder_idx; // Reference picture list reordering ref_pic_list_reordering_flag_l0 = (mfxU8)Get1Bit(); if (ref_pic_list_reordering_flag_l0) { bool bOk = true; reorder_idx = 0; reordering_of_pic_nums_idc = 0; // Get reorder idc,pic_num pairs until idc==3 while (bOk) { reordering_of_pic_nums_idc = (mfxU8)GetVLCElement(false); if (reordering_of_pic_nums_idc > 5) return MFX_ERR_UNDEFINED_BEHAVIOR; if (reordering_of_pic_nums_idc == 3) break; if (reorder_idx >= MAX_NUM_REF_FRAMES) { return MFX_ERR_UNDEFINED_BEHAVIOR; } pReorderInfo_L0->reordering_of_pic_nums_idc[reorder_idx] = (mfxU8)reordering_of_pic_nums_idc; pReorderInfo_L0->reorder_value[reorder_idx] = GetVLCElement(false); if (reordering_of_pic_nums_idc != 2) // abs_diff_pic_num is coded minus 1 pReorderInfo_L0->reorder_value[reorder_idx]++; reorder_idx++; } // while pReorderInfo_L0->num_entries = reorder_idx; } // L0 reordering info else pReorderInfo_L0->num_entries = 0; if (BPREDSLICE == hdr->slice_type) { ref_pic_list_reordering_flag_l1 = (mfxU8)Get1Bit(); if (ref_pic_list_reordering_flag_l1) { bool bOk = true; // Get reorder idc,pic_num pairs until idc==3 reorder_idx = 0; reordering_of_pic_nums_idc = 0; while (bOk) { reordering_of_pic_nums_idc = GetVLCElement(false); if (reordering_of_pic_nums_idc > 5) return MFX_ERR_UNDEFINED_BEHAVIOR; if (reordering_of_pic_nums_idc == 3) break; if (reorder_idx >= MAX_NUM_REF_FRAMES) { return MFX_ERR_UNDEFINED_BEHAVIOR; } pReorderInfo_L1->reordering_of_pic_nums_idc[reorder_idx] = (mfxU8)reordering_of_pic_nums_idc; pReorderInfo_L1->reorder_value[reorder_idx] = GetVLCElement(false); if (reordering_of_pic_nums_idc != 2) // abs_diff_pic_num is coded minus 1 pReorderInfo_L1->reorder_value[reorder_idx]++; reorder_idx++; } // while pReorderInfo_L1->num_entries = reorder_idx; } // L1 reordering info else pReorderInfo_L1->num_entries = 0; } // B slice } // reordering info // prediction weight table if ( (pps->weighted_pred_flag && ((PREDSLICE == hdr->slice_type) || (S_PREDSLICE == hdr->slice_type))) || ((pps->weighted_bipred_idc == 1) && (BPREDSLICE == hdr->slice_type))) { hdr->luma_log2_weight_denom = (mfxU8)GetVLCElement(false); if (sps->chroma_format_idc != 0) hdr->chroma_log2_weight_denom = (mfxU8)GetVLCElement(false); for (mfxI32 refindex = 0; refindex < hdr->num_ref_idx_l0_active; refindex++) { pPredWeight_L0[refindex].luma_weight_flag = (mfxU8)Get1Bit(); if (pPredWeight_L0[refindex].luma_weight_flag) { pPredWeight_L0[refindex].luma_weight = (mfxI8)GetVLCElement(true); pPredWeight_L0[refindex].luma_offset = (mfxI8)GetVLCElement(true); } else { pPredWeight_L0[refindex].luma_weight = (mfxI8)(1 << hdr->luma_log2_weight_denom); pPredWeight_L0[refindex].luma_offset = 0; } if (sps->chroma_format_idc != 0) { pPredWeight_L0[refindex].chroma_weight_flag = (mfxU8)Get1Bit(); if (pPredWeight_L0[refindex].chroma_weight_flag) { pPredWeight_L0[refindex].chroma_weight[0] = (mfxI8)GetVLCElement(true); pPredWeight_L0[refindex].chroma_offset[0] = (mfxI8)GetVLCElement(true); pPredWeight_L0[refindex].chroma_weight[1] = (mfxI8)GetVLCElement(true); pPredWeight_L0[refindex].chroma_offset[1] = (mfxI8)GetVLCElement(true); } else { pPredWeight_L0[refindex].chroma_weight[0] = (mfxI8)(1 << hdr->chroma_log2_weight_denom); pPredWeight_L0[refindex].chroma_weight[1] = (mfxI8)(1 << hdr->chroma_log2_weight_denom); pPredWeight_L0[refindex].chroma_offset[0] = 0; pPredWeight_L0[refindex].chroma_offset[1] = 0; } } } if (BPREDSLICE == hdr->slice_type) { for (mfxI32 refindex = 0; refindex < hdr->num_ref_idx_l1_active; refindex++) { pPredWeight_L1[refindex].luma_weight_flag = (mfxU8)Get1Bit(); if (pPredWeight_L1[refindex].luma_weight_flag) { pPredWeight_L1[refindex].luma_weight = (mfxI8)GetVLCElement(true); pPredWeight_L1[refindex].luma_offset = (mfxI8)GetVLCElement(true); } else { pPredWeight_L1[refindex].luma_weight = (mfxI8)(1 << hdr->luma_log2_weight_denom); pPredWeight_L1[refindex].luma_offset = 0; } if (sps->chroma_format_idc != 0) { pPredWeight_L1[refindex].chroma_weight_flag = (mfxU8)Get1Bit(); if (pPredWeight_L1[refindex].chroma_weight_flag) { pPredWeight_L1[refindex].chroma_weight[0] = (mfxI8)GetVLCElement(true); pPredWeight_L1[refindex].chroma_offset[0] = (mfxI8)GetVLCElement(true); pPredWeight_L1[refindex].chroma_weight[1] = (mfxI8)GetVLCElement(true); pPredWeight_L1[refindex].chroma_offset[1] = (mfxI8)GetVLCElement(true); } else { pPredWeight_L1[refindex].chroma_weight[0] = (mfxI8)(1 << hdr->chroma_log2_weight_denom); pPredWeight_L1[refindex].chroma_weight[1] = (mfxI8)(1 << hdr->chroma_log2_weight_denom); pPredWeight_L1[refindex].chroma_offset[0] = 0; pPredWeight_L1[refindex].chroma_offset[1] = 0; } } } } // B slice } // prediction weight table else { hdr->luma_log2_weight_denom = 0; hdr->chroma_log2_weight_denom = 0; } // dec_ref_pic_marking pAdaptiveMarkingInfo->num_entries = 0; if (NALRef_idc) { if (hdr->IdrPicFlag) { hdr->no_output_of_prior_pics_flag = (mfxU8)Get1Bit(); hdr->long_term_reference_flag = (mfxU8)Get1Bit(); } else { mfxU32 memory_management_control_operation; mfxU32 num_entries = 0; hdr->adaptive_ref_pic_marking_mode_flag = (mfxU8)Get1Bit(); while (hdr->adaptive_ref_pic_marking_mode_flag != 0) { memory_management_control_operation = (mfxU8)GetVLCElement(false); if (memory_management_control_operation == 0) break; if (memory_management_control_operation > 6) return MFX_ERR_UNDEFINED_BEHAVIOR; pAdaptiveMarkingInfo->mmco[num_entries] = (mfxU8)memory_management_control_operation; if (memory_management_control_operation != 5) pAdaptiveMarkingInfo->value[num_entries*2] = GetVLCElement(false); // Only mmco 3 requires 2 values if (memory_management_control_operation == 3) pAdaptiveMarkingInfo->value[num_entries*2+1] = GetVLCElement(false); num_entries++; if (num_entries >= MAX_NUM_REF_FRAMES) { return MFX_ERR_UNDEFINED_BEHAVIOR; } } // while pAdaptiveMarkingInfo->num_entries = num_entries; } } // def_ref_pic_marking if (pps->entropy_coding_mode == 1 && // CABAC (hdr->slice_type != INTRASLICE && hdr->slice_type != S_INTRASLICE)) hdr->cabac_init_idc = GetVLCElement(false); else hdr->cabac_init_idc = 0; if (hdr->cabac_init_idc > 2) return MFX_ERR_UNDEFINED_BEHAVIOR; hdr->slice_qp_delta = GetVLCElement(true); if (S_PREDSLICE == hdr->slice_type || S_INTRASLICE == hdr->slice_type) { if (S_PREDSLICE == hdr->slice_type) hdr->sp_for_switch_flag = (mfxU8)Get1Bit(); hdr->slice_qs_delta = GetVLCElement(true); } if (pps->deblocking_filter_variables_present_flag != 0) { // deblock filter flag and offsets hdr->disable_deblocking_filter_idc = GetVLCElement(false); if (hdr->disable_deblocking_filter_idc > 2) return MFX_ERR_UNDEFINED_BEHAVIOR; if (hdr->disable_deblocking_filter_idc != 1) { hdr->slice_alpha_c0_offset = GetVLCElement(true)<<1; hdr->slice_beta_offset = GetVLCElement(true)<<1; if (hdr->slice_alpha_c0_offset < -12 || hdr->slice_alpha_c0_offset > 12) { return MFX_ERR_UNDEFINED_BEHAVIOR; } if (hdr->slice_beta_offset < -12 || hdr->slice_beta_offset > 12) { return MFX_ERR_UNDEFINED_BEHAVIOR; } } else { // set filter offsets to max values to disable filter hdr->slice_alpha_c0_offset = (mfxI8)(0 - AVC_QP_MAX); hdr->slice_beta_offset = (mfxI8)(0 - AVC_QP_MAX); } } if (pps->num_slice_groups > 1 && pps->SliceGroupInfo.slice_group_map_type >= 3 && pps->SliceGroupInfo.slice_group_map_type <= 5) { mfxU32 num_bits; // number of bits used to code slice_group_change_cycle mfxU32 val; mfxU32 pic_size_in_map_units; mfxU32 max_slice_group_change_cycle=0; // num_bits is Ceil(log2(picsizeinmapunits/slicegroupchangerate + 1)) pic_size_in_map_units = sps->frame_width_in_mbs * sps->frame_height_in_mbs; max_slice_group_change_cycle = pic_size_in_map_units / pps->SliceGroupInfo.t2.slice_group_change_rate; if (pic_size_in_map_units % pps->SliceGroupInfo.t2.slice_group_change_rate) max_slice_group_change_cycle++; val = max_slice_group_change_cycle; num_bits = 0; while (val) { num_bits++; val >>= 1; } hdr->slice_group_change_cycle = GetBits(num_bits); } return MFX_ERR_NONE; } // GetSliceHeaderPart3() void AVCHeadersBitstream::GetScalingList4x4(AVCScalingList4x4 *scl, mfxU8 *def, mfxU8 *scl_type) { mfxU32 lastScale = 8; mfxU32 nextScale = 8; bool DefaultMatrix = false; mfxI32 j; for (j = 0; j < 16; j++ ) { if (nextScale != 0) { mfxI32 delta_scale = GetVLCElement(true); if (delta_scale < -128 || delta_scale > 127) throw AVC_exception(MFX_ERR_UNDEFINED_BEHAVIOR); nextScale = ( lastScale + delta_scale + 256 ) & 0xff; DefaultMatrix = ( j == 0 && nextScale == 0 ); } scl->ScalingListCoeffs[ mp_scan4x4[0][j] ] = ( nextScale == 0 ) ? (mfxU8)lastScale : (mfxU8)nextScale; lastScale = scl->ScalingListCoeffs[ mp_scan4x4[0][j] ]; } if (!DefaultMatrix) { *scl_type = SCLREDEFINED; return; } *scl_type= SCLDEFAULT; FillScalingList4x4(scl,def); return; } void AVCHeadersBitstream::GetScalingList8x8(AVCScalingList8x8 *scl, mfxU8 *def, mfxU8 *scl_type) { mfxU32 lastScale = 8; mfxU32 nextScale = 8; bool DefaultMatrix=false; mfxI32 j; for (j = 0; j < 64; j++ ) { if (nextScale != 0) { mfxI32 delta_scale = GetVLCElement(true); if (delta_scale < -128 || delta_scale > 127) throw AVC_exception(MFX_ERR_UNDEFINED_BEHAVIOR); nextScale = ( lastScale + delta_scale + 256 ) & 0xff; DefaultMatrix = ( j == 0 && nextScale == 0 ); } scl->ScalingListCoeffs[ hp_scan8x8[0][j] ] = ( nextScale == 0 ) ? (mfxU8)lastScale : (mfxU8)nextScale; lastScale = scl->ScalingListCoeffs[ hp_scan8x8[0][j] ]; } if (!DefaultMatrix) { *scl_type=SCLREDEFINED; return; } *scl_type= SCLDEFAULT; FillScalingList8x8(scl,def); return; } void SetDefaultScalingLists(AVCSeqParamSet * sps) { mfxI32 i; for (i = 0; i < 6; i += 1) { FillFlatScalingList4x4(&sps->ScalingLists4x4[i]); } for (i = 0; i < 2; i += 1) { FillFlatScalingList8x8(&sps->ScalingLists8x8[i]); } } mfxStatus DecodeExpGolombOne(mfxU32 **ppBitStream, mfxI32 *pBitOffset, mfxI32 *pDst, mfxI32 isSigned) { mfxU32 code; mfxU32 info = 0; mfxI32 length = 1; /* for first bit read above*/ mfxU32 thisChunksLength = 0; mfxU32 sval; /* Fast check for element = 0 */ avcGetNBits((*ppBitStream), (*pBitOffset), 1, code); if (code) { *pDst = 0; return MFX_ERR_NONE; } avcGetNBits((*ppBitStream), (*pBitOffset), 8, code); length += 8; /* find nonzero byte */ while (code == 0) { avcGetNBits((*ppBitStream), (*pBitOffset), 8, code); length += 8; } /* find leading '1' */ while ((code & 0x80) == 0) { code <<= 1; thisChunksLength++; } length -= 8 - thisChunksLength; avcUngetNBits((*ppBitStream), (*pBitOffset), 8 - (thisChunksLength + 1)); /* Get info portion of codeword */ if (length) { avcGetNBits((*ppBitStream), (*pBitOffset),length, info); } sval = (1 << length) + info - 1; if (isSigned) { if (sval & 1) *pDst = (mfxI32) ((sval + 1) >> 1); else *pDst = -((mfxI32) (sval >> 1)); } else *pDst = (mfxI32) sval; return MFX_ERR_NONE; } mfxI32 AVCHeadersBitstream::GetSEI(const HeaderSet<AVCSeqParamSet> & sps, mfxI32 current_sps, AVCSEIPayLoad *spl) { mfxU32 code; mfxI32 payloadType = 0; avcNextBits(m_pbs, m_bitOffset, 8, code); while (code == 0xFF) { /* fixed-pattern bit string using 8 bits written equal to 0xFF */ avcGetNBits(m_pbs, m_bitOffset, 8, code); payloadType += 255; avcNextBits(m_pbs, m_bitOffset, 8, code); } mfxI32 last_payload_type_byte; //Ipp32u integer using 8 bits avcGetNBits(m_pbs, m_bitOffset, 8, last_payload_type_byte); payloadType += last_payload_type_byte; mfxI32 payloadSize = 0; avcNextBits(m_pbs, m_bitOffset, 8, code); while( code == 0xFF ) { /* fixed-pattern bit string using 8 bits written equal to 0xFF */ avcGetNBits(m_pbs, m_bitOffset, 8, code); payloadSize += 255; avcNextBits(m_pbs, m_bitOffset, 8, code); } mfxI32 last_payload_size_byte; //Ipp32u integer using 8 bits avcGetNBits(m_pbs, m_bitOffset, 8, last_payload_size_byte); payloadSize += last_payload_size_byte; spl->Reset(); spl->payLoadSize = payloadSize; if (payloadType < 0 || payloadType > SEI_RESERVED) payloadType = SEI_RESERVED; spl->payLoadType = (SEI_TYPE)payloadType; if (spl->payLoadSize > BytesLeft()) { throw AVC_exception(MFX_ERR_UNDEFINED_BEHAVIOR); } mfxU32 * pbs; mfxU32 bitOffsetU; mfxI32 bitOffset; pbs = m_pbs; bitOffsetU = m_bitOffset; bitOffset = bitOffsetU; mfxI32 ret = GetSEIPayload(sps, current_sps, spl); for (mfxU32 i = 0; i < spl->payLoadSize; i++) { avcSkipNBits(pbs, bitOffset, 8); } m_pbs = pbs; m_bitOffset = bitOffset; return ret; } mfxI32 AVCHeadersBitstream::GetSEIPayload(const HeaderSet<AVCSeqParamSet> & sps, mfxI32 current_sps, AVCSEIPayLoad *spl) { switch (spl->payLoadType) { case SEI_RECOVERY_POINT_TYPE: return recovery_point(sps,current_sps,spl); default: return reserved_sei_message(sps,current_sps,spl); } } mfxI32 AVCHeadersBitstream::reserved_sei_message(const HeaderSet<AVCSeqParamSet> & , mfxI32 current_sps, AVCSEIPayLoad *spl) { for (mfxU32 i = 0; i < spl->payLoadSize; i++) avcSkipNBits(m_pbs, m_bitOffset, 8) AlignPointerRight(); return current_sps; } mfxI32 AVCHeadersBitstream::recovery_point(const HeaderSet<AVCSeqParamSet> & , mfxI32 current_sps, AVCSEIPayLoad *spl) { AVCSEIPayLoad::SEIMessages::RecoveryPoint * recPoint = &(spl->SEI_messages.recovery_point); recPoint->recovery_frame_cnt = (mfxU8)GetVLCElement(false); recPoint->exact_match_flag = (mfxU8)Get1Bit(); recPoint->broken_link_flag = (mfxU8)Get1Bit(); recPoint->changing_slice_group_idc = (mfxU8)GetBits(2); if (recPoint->changing_slice_group_idc > 2) return -1; return current_sps; } void HeapObject::Free() { } } // namespace ProtectedLibrary
[ "wai.lun.poon@intel.com" ]
wai.lun.poon@intel.com
72210de034a68d294693f3358f8a26c8d400cd6f
aab7eafab5efae62cb06c3a2b6c26fe08eea0137
/cmtuser/Urania_v2r4/PIDCalib/PIDPerfTools/dict/PIDPerfToolsDict.h
134b46062df1bf6f76badf82a54a254dcd82f1c4
[]
no_license
Sally27/B23MuNu_backup
397737f58722d40e2a1007649d508834c1acf501
bad208492559f5820ed8c1899320136406b78037
refs/heads/master
2020-04-09T18:12:43.308589
2018-12-09T14:16:25
2018-12-09T14:16:25
160,504,958
0
1
null
null
null
null
UTF-8
C++
false
false
2,047
h
// $Id: $ #ifndef DICT_PIDPERFTOOLSDICT_H #define DICT_PIDPERFTOOLSDICT_H 1 // Include files /** @file PIDPerfToolsDict.h dict/PIDPerfToolsDict.h * * * @author Andrew POWELL * @date 2010-10-08 */ #include "PIDPerfTools/TrackDataSet.h" #include "PIDPerfTools/EvtTrackDataSet.h" #include "PIDPerfTools/RICHTrackDataSet.h" #include "PIDPerfTools/MUONTrackDataSet.h" #include "PIDPerfTools/PIDTrackDataSet.h" #include "PIDPerfTools/LHCbPIDTrackDataSet.h" #include "PIDPerfTools/GenericDataSet.h" #include "PIDPerfTools/DataBinCuts.h" #include "PIDPerfTools/PerfCalculator.h" #include "PIDPerfTools/PIDResult.h" #include "PIDPerfTools/PerfCalculator.h" #include "PIDPerfTools/MultiPerfCalculator.h" #include "PIDPerfTools/PIDTable.h" #include "PIDPerfTools/PIDCrossTable.h" #include "PIDPerfTools/TrkPIDParams.h" #include "PIDPerfTools/MultiTrackCalibTool.h" #include "PIDPerfTools/WeightDataSetTool.h" namespace { struct _Instantiations { PerfCalculator<TrackDataSet> a; PerfCalculator<EvtTrackDataSet> b; PerfCalculator<RICHTrackDataSet> c; PerfCalculator<MUONTrackDataSet> d; PerfCalculator<PIDTrackDataSet> e; PerfCalculator<LHCbPIDTrackDataSet> ee; PerfCalculator<GenericDataSet> eee; std::pair<std::string, RooBinning*> f; std::list<std::pair<std::string, RooBinning*> > g; std::vector<RooBinning*> h; PIDResult::Container i; std::vector<std::string> j; WeightDataSetTool<TrackDataSet> k; WeightDataSetTool<EvtTrackDataSet> l; WeightDataSetTool<RICHTrackDataSet> m; WeightDataSetTool<MUONTrackDataSet> n; WeightDataSetTool<PIDTrackDataSet> o; std::pair<std::string, std::string> r; std::vector<std::pair<std::string, std::string> > s; }; } #endif // DICT_PIDPERFTOOLSDICT_H
[ "ss4314@ss4314-laptop.hep.ph.ic.ac.uk" ]
ss4314@ss4314-laptop.hep.ph.ic.ac.uk
65f9c208e6ce49bf68d208a2ec68fd0e07f2a6e3
8431bd966d2eb8c4fe4be2059d6e3ef199df534b
/src/Fighter.h
cd3566d6039ec78d9db1ccbc2e8505e4336115e3
[]
no_license
IssaShane/upgraded-waffle
48d10a75d98cb10a5bdb7a8bb7bc35cb4b16c270
8283617b0baaa991b36561412da5f0d41c4f1055
refs/heads/master
2023-04-19T21:07:24.055722
2021-05-05T04:12:50
2021-05-05T04:12:50
361,979,118
0
0
null
null
null
null
UTF-8
C++
false
false
857
h
#ifndef FIGHTER_H #define FIGHTER_H #include "GameObject.h" #include "Observer.h" #include "Subject.h" class Fighter : public GameObject, public Observer, public Subject { public: Fighter(const char*,SDL_Rect,SDL_Rect); void checkHealth(SDL_Rect POS, bool IsAttacking, int power); void attack(); virtual void notify(State&); //virtual void move(int,int) override; void setPosY(int newy); void UpdateItems(int Type, int TimesCollected); //getters int getHealth(); bool IsAttacking(); int getPower(); double getBoost(); double getSpecial(); protected: //Stats bool Attacking; int Health; double Boost; int Power; int Altitude; bool IsAltChange; int Speed; int gravity; double Special; bool IsEnabledShield; User user; bool IsComputer; }; #endif
[ "shane@collinz.ca" ]
shane@collinz.ca
b634d3da67923841605a76c1e0a7b067f642964d
1bf6b111528404bfd38ef9b5c7d0f1bdc2ab8b6c
/Project.h
f830b1bc6078ee629bf9d1772c236941e17fb545
[]
no_license
HeliumProject/EShellMenu
0dfb4a10e7797b80738882d43d65f6bdfbd61292
770bbb39750cc9740cf1f66a0e24db379d2af7ea
refs/heads/master
2020-12-29T02:44:08.006010
2020-01-22T21:54:08
2020-01-22T21:54:08
2,712,762
1
2
null
2015-04-27T23:45:44
2011-11-04T22:42:53
C++
UTF-8
C++
false
false
2,745
h
#pragma once #include <map> #include <set> #include <string> #include <vector> namespace EShellMenu { class EnvVar { public: EnvVar() : m_IsPath( false ) , m_IsOverride( true ) { } tstring m_Name; tstring m_Value; bool m_IsPath; bool m_IsOverride; }; typedef std::map<tstring, EnvVar> M_EnvVar; class Include { public: Include() : m_Optional( false ) , m_Loaded( false ) { } tstring m_Path; bool m_Optional; bool m_Loaded; }; class Shortcut { public: Shortcut() : m_Optional( false ) { } tstring m_Name; // Display name: "prompt", etc... tstring m_Folder; // Folder to put it in (under the project menu) tstring m_Description; // Mouse over description tstring m_IconPath; // Path to the .png file tstring m_Args; // Args to pass to eshell, overrides tstring m_Target; // If no Args specified, use -run <blah> to this file tstring m_TargetWorkingDir; // The working directory to launch the target in tstring m_TargetInstaller; // If target is defined, but doesn't exist, kick into this installer bool m_Optional; }; class Config { public: Config() : m_Hidden( false ) { } tstring m_Name; tstring m_Parent; tstring m_Description; bool m_Hidden; // used to hide from displayed configs M_EnvVar m_EnvVar; std::vector< Shortcut > m_Shortcuts; std::vector< Include > m_Includes; }; class Project { public: Project(); ~Project(); bool LoadFile( const tstring& project, bool includeFile = false ); static void ProcessValue( tstring& value, const M_EnvVar& envVar ); static void SetEnvVar( const tstring& envVarName, const tstring& envVarValue, M_EnvVar& envVars, bool isPath = true ); static void GetEnvVarAliasValue( const tstring& envVarName, const M_EnvVar& envVars, tstring& aliasVar, const tchar_t* defaultValue = NULL ); protected: static void ParseEnvVar( wxXmlNode* elem, M_EnvVar& envVars, bool includeFile = false ); static void ParseInclude( wxXmlNode* elem, std::vector< Include >& includes ); static void ParseConfig( wxXmlNode* elem, std::map< tstring, Config >& configs, M_EnvVar& globalEnvVar ); static void ParseShortcut( wxXmlNode* elem, std::vector< Shortcut >& shortcuts, M_EnvVar& envVars ); static tstring ProcessEnvVar( const EnvVar& envVar, const M_EnvVar& envVars, std::set< tstring >& currentlyProcessing = std::set< tstring >() ); public: tstring m_Title; tstring m_File; M_EnvVar m_EnvVar; std::map< tstring, Config > m_Configs; std::vector< Include > m_Includes; }; class StringRefData : public wxObjectRefData { public: StringRefData( const tstring& str ) : m_Value( str ) { } tstring m_Value; }; }
[ "geoff@flummoxed.org" ]
geoff@flummoxed.org
6045d9944ab772dde3ddef62d3ecc7af1edc0eab
17216697080c5afdd5549aff14f42c39c420d33a
/src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/tests/Intrusive_Auto_Ptr_Test.cpp
c589c3d01f3c3c769f1183a21f165431cd590fe9
[ "MIT" ]
permissive
AI549654033/RDHelp
9c8b0cc196de98bcd81b2ccc4fc352bdc3783159
0f5f9c7d098635c7216713d7137c845c0d999226
refs/heads/master
2022-07-03T16:04:58.026641
2020-05-18T06:04:36
2020-05-18T06:04:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,020
cpp
// $Id: Intrusive_Auto_Ptr_Test.cpp 81190 2008-04-01 07:38:35Z johnnyw $ // ============================================================================ // // = LIBRARY // tests // // = FILENAME // Intrusive_Auto_Ptr_Test // // = DESCRIPTION // This test verifies the functionality of the <ACE_Intrusive_Auto_Ptr> // implementation. // // = AUTHOR // Iliyan Jeliazkov <iliyan@ociweb.com> // // ============================================================================ #include "test_config.h" #include "ace/Intrusive_Auto_Ptr.h" #include "ace/Thread_Manager.h" ACE_RCSID(tests, Intrusive_Auto_Ptr_Test, "$Id: Intrusive_Auto_Ptr_Test.cpp 81190 2008-04-01 07:38:35Z johnnyw $") class One { static bool released; int m2; int ref; public: One (int refcount): ref(refcount) { released = false; } ~One () { released = true; } bool has_refs (int howmany) { return this->ref == howmany; } static bool was_released (void) { return released; } static void intrusive_add_ref (One *); static void intrusive_remove_ref (One *); }; bool One::released = true; void One::intrusive_add_ref (One *one) { one->ref++; } void One::intrusive_remove_ref (One *one) { one->ref--; if (one->ref == 0) delete one; } int run_main (int, ACE_TCHAR *[]) { ACE_START_TEST (ACE_TEXT ("Intrusive_Auto_Ptr_Test")); One *theone (new One(0)); { ACE_ASSERT (theone->has_refs (0)); ACE_ASSERT (!One::was_released ()); ACE_Intrusive_Auto_Ptr<One> ip2(theone); { ACE_ASSERT (theone->has_refs (1)); ACE_ASSERT (!One::was_released ()); ACE_Intrusive_Auto_Ptr<One> ip2(theone); ACE_ASSERT (theone->has_refs (2)); ACE_ASSERT (!One::was_released ()); } ACE_ASSERT (theone->has_refs (1)); ACE_ASSERT (!One::was_released ()); } ACE_ASSERT (One::was_released()); ACE_END_TEST; return 0; }
[ "jim_xie@trendmicro.com" ]
jim_xie@trendmicro.com
ad6713aa6dc1b3ac852844c670ffeb87f0a5cfde
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/chromeos/dbus/fake_debug_daemon_client.cc
3a7d4035fc0ffbfc4b62365611ea1ef5e311ca6c
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
7,308
cc
// Copyright 2013 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 "chromeos/dbus/fake_debug_daemon_client.h" #include <stddef.h> #include <stdint.h> #include <map> #include <string> #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "chromeos/chromeos_switches.h" #include "dbus/file_descriptor.h" namespace { const char kCrOSTracingAgentName[] = "cros"; const char kCrOSTraceLabel[] = "systemTraceEvents"; } // namespace namespace chromeos { FakeDebugDaemonClient::FakeDebugDaemonClient() : featues_mask_(DebugDaemonClient::DEV_FEATURE_NONE), service_is_available_(true) { } FakeDebugDaemonClient::~FakeDebugDaemonClient() {} void FakeDebugDaemonClient::Init(dbus::Bus* bus) {} void FakeDebugDaemonClient::DumpDebugLogs( bool is_compressed, base::File file, scoped_refptr<base::TaskRunner> task_runner, const GetDebugLogsCallback& callback) { callback.Run(true); } void FakeDebugDaemonClient::SetDebugMode(const std::string& subsystem, const SetDebugModeCallback& callback) { callback.Run(false); } std::string FakeDebugDaemonClient::GetTracingAgentName() { return kCrOSTracingAgentName; } std::string FakeDebugDaemonClient::GetTraceEventLabel() { return kCrOSTraceLabel; } void FakeDebugDaemonClient::StartAgentTracing( const base::trace_event::TraceConfig& trace_config, const StartAgentTracingCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, GetTracingAgentName(), true /* success */)); } void FakeDebugDaemonClient::StopAgentTracing( const StopAgentTracingCallback& callback) { std::string no_data; callback.Run(GetTracingAgentName(), GetTraceEventLabel(), base::RefCountedString::TakeString(&no_data)); } void FakeDebugDaemonClient::SetStopAgentTracingTaskRunner( scoped_refptr<base::TaskRunner> task_runner) {} void FakeDebugDaemonClient::GetRoutes(bool numeric, bool ipv6, const GetRoutesCallback& callback) { std::vector<std::string> empty; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, empty)); } void FakeDebugDaemonClient::GetNetworkStatus( const GetNetworkStatusCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, "")); } void FakeDebugDaemonClient::GetModemStatus( const GetModemStatusCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, "")); } void FakeDebugDaemonClient::GetWiMaxStatus( const GetWiMaxStatusCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, "")); } void FakeDebugDaemonClient::GetNetworkInterfaces( const GetNetworkInterfacesCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, "")); } void FakeDebugDaemonClient::GetPerfOutput( base::TimeDelta duration, const std::vector<std::string>& perf_args, dbus::ScopedFileDescriptor file_descriptor, const DBusMethodErrorCallback& error_callback) { // Nothing to do but close the file descriptor, which its dtor will do. } void FakeDebugDaemonClient::GetScrubbedLogs(const GetLogsCallback& callback) { std::map<std::string, std::string> sample; sample["Sample Scrubbed Log"] = "Your email address is xxxxxxxx"; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, sample)); } void FakeDebugDaemonClient::GetScrubbedBigLogs( const GetLogsCallback& callback) { std::map<std::string, std::string> sample; sample["Sample Scrubbed Big Log"] = "Your email address is xxxxxxxx"; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, sample)); } void FakeDebugDaemonClient::GetAllLogs(const GetLogsCallback& callback) { std::map<std::string, std::string> sample; sample["Sample Log"] = "Your email address is abc@abc.com"; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, sample)); } void FakeDebugDaemonClient::GetUserLogFiles(const GetLogsCallback& callback) { std::map<std::string, std::string> user_logs; user_logs["preferences"] = "Preferences"; user_logs["invalid_file"] = "Invalid File"; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, true, user_logs)); } void FakeDebugDaemonClient::TestICMP(const std::string& ip_address, const TestICMPCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, "")); } void FakeDebugDaemonClient::TestICMPWithOptions( const std::string& ip_address, const std::map<std::string, std::string>& options, const TestICMPCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, false, "")); } void FakeDebugDaemonClient::UploadCrashes() { } void FakeDebugDaemonClient::EnableDebuggingFeatures( const std::string& password, const DebugDaemonClient::EnableDebuggingCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback, true)); } void FakeDebugDaemonClient::QueryDebuggingFeatures( const DebugDaemonClient::QueryDevFeaturesCallback& callback) { bool supported = base::CommandLine::ForCurrentProcess()->HasSwitch( chromeos::switches::kSystemDevMode); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind( callback, true, static_cast<int>( supported ? featues_mask_ : debugd::DevFeatureFlag::DEV_FEATURES_DISABLED))); } void FakeDebugDaemonClient::RemoveRootfsVerification( const DebugDaemonClient::EnableDebuggingCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback, true)); } void FakeDebugDaemonClient::WaitForServiceToBeAvailable( const WaitForServiceToBeAvailableCallback& callback) { if (service_is_available_) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback, true)); } else { pending_wait_for_service_to_be_available_callbacks_.push_back(callback); } } void FakeDebugDaemonClient::SetDebuggingFeaturesStatus(int featues_mask) { featues_mask_ = featues_mask; } void FakeDebugDaemonClient::SetServiceIsAvailable(bool is_available) { service_is_available_ = is_available; if (!is_available) return; std::vector<WaitForServiceToBeAvailableCallback> callbacks; callbacks.swap(pending_wait_for_service_to_be_available_callbacks_); for (size_t i = 0; i < callbacks.size(); ++i) callbacks[i].Run(is_available); } } // namespace chromeos
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com