hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
9655ed03e93a829f9f9c300980c820e7cf723663
2,120
cpp
C++
test/old_tests/UnitTests/boxing.cpp
sylveon/cppwinrt
4d5c5ae3de386ce1f18c3410a27b9ceb40aa524d
[ "MIT" ]
859
2016-10-13T00:11:52.000Z
2019-05-06T15:45:46.000Z
test/old_tests/UnitTests/boxing.cpp
sylveon/cppwinrt
4d5c5ae3de386ce1f18c3410a27b9ceb40aa524d
[ "MIT" ]
655
2019-10-08T12:15:16.000Z
2022-03-31T18:26:40.000Z
test/old_tests/UnitTests/boxing.cpp
sylveon/cppwinrt
4d5c5ae3de386ce1f18c3410a27b9ceb40aa524d
[ "MIT" ]
137
2016-10-13T04:19:59.000Z
2018-11-09T05:08:03.000Z
#include "pch.h" #include "catch.hpp" using namespace winrt; using namespace Windows::Foundation; using namespace std::string_view_literals; using namespace std::chrono_literals; namespace { template<typename T> T empty() { if constexpr (std::is_convertible_v<T, Windows::Foundation::IUnknown>) { return T{ nullptr }; } else { return T{}; } } template<typename T> void TestRoundTrip(T const& value) { Windows::Foundation::IInspectable object = box_value(value); REQUIRE(unbox_value<T>(object) == value); REQUIRE(object.as<T>() == value); T result = empty<T>(); object.as(result); REQUIRE(result == value); } } TEST_CASE("IReference, boxing round trip") { static_assert(std::is_convertible_v<Uri, Windows::Foundation::IUnknown>); TestRoundTrip<uint8_t>(42); TestRoundTrip<int8_t>(42); TestRoundTrip<uint16_t>(42); TestRoundTrip<int16_t>(42); TestRoundTrip<uint32_t>(42); TestRoundTrip<int32_t>(42); TestRoundTrip<uint64_t>(42); TestRoundTrip<int64_t>(42); TestRoundTrip<bool>(true); TestRoundTrip<char16_t>(L'&'); TestRoundTrip<guid>(guid_of<IStringable>()); TestRoundTrip<hstring>(L"I am not a string"); TestRoundTrip<Point>({ 42, 1729 }); TestRoundTrip<Size>({ 42, 1729 }); TestRoundTrip<Rect>({ 0, 0, 42, 1729 }); const DateTime dt = clock::now(); TestRoundTrip<DateTime>(dt); TestRoundTrip<TimeSpan>(clock::now() + 10s - dt); TestRoundTrip<Uri>(Uri{ L"https://github.com/Microsoft/cppwinrt" }); } TEST_CASE("IReference, unbox_value_or") { auto check = [](Windows::Foundation::IInspectable const& boxed) { const std::wstring_view fallback = L"Fallback value"sv; auto unboxed = unbox_value_or<hstring>(boxed, hstring{ fallback }); static_assert(std::is_same_v<decltype(unboxed), hstring>); REQUIRE(unboxed == fallback); }; check(nullptr); check(Uri{ L"https://github.com/Microsoft/cppwinrt" }); check(IReference<int>(42)); }
28.648649
78
0.638208
[ "object" ]
9659c7c580f0047ffcb099cd1181e6d7fa55c051
25,229
cpp
C++
modules/mod_google_transcribe/google_glue.cpp
carolinasolfernandez/drachtio-freeswitch-modules
7e09ed9cbf495cf292d3042a84c1a6b12b86afc8
[ "MIT" ]
33
2021-01-18T01:08:09.000Z
2022-03-27T22:41:51.000Z
modules/mod_google_transcribe/google_glue.cpp
carolinasolfernandez/drachtio-freeswitch-modules
7e09ed9cbf495cf292d3042a84c1a6b12b86afc8
[ "MIT" ]
21
2021-01-26T19:36:57.000Z
2022-03-21T16:16:27.000Z
modules/mod_google_transcribe/google_glue.cpp
carolinasolfernandez/drachtio-freeswitch-modules
7e09ed9cbf495cf292d3042a84c1a6b12b86afc8
[ "MIT" ]
16
2021-01-22T20:43:59.000Z
2022-03-06T17:01:40.000Z
#include <cstdlib> #include <algorithm> #include <switch.h> #include <switch_json.h> #include <grpc++/grpc++.h> #include "google/cloud/speech/v1p1beta1/cloud_speech.grpc.pb.h" #include "mod_google_transcribe.h" #define BUFFER_SECS (3) using google::cloud::speech::v1p1beta1::RecognitionConfig; using google::cloud::speech::v1p1beta1::Speech; using google::cloud::speech::v1p1beta1::SpeechContext; using google::cloud::speech::v1p1beta1::StreamingRecognizeRequest; using google::cloud::speech::v1p1beta1::StreamingRecognizeResponse; using google::cloud::speech::v1p1beta1::SpeakerDiarizationConfig; using google::cloud::speech::v1p1beta1::SpeechAdaptation; using google::cloud::speech::v1p1beta1::PhraseSet; using google::cloud::speech::v1p1beta1::PhraseSet_Phrase; using google::cloud::speech::v1p1beta1::RecognitionMetadata; using google::cloud::speech::v1p1beta1::RecognitionMetadata_InteractionType_DISCUSSION; using google::cloud::speech::v1p1beta1::RecognitionMetadata_InteractionType_PRESENTATION; using google::cloud::speech::v1p1beta1::RecognitionMetadata_InteractionType_PHONE_CALL; using google::cloud::speech::v1p1beta1::RecognitionMetadata_InteractionType_VOICEMAIL; using google::cloud::speech::v1p1beta1::RecognitionMetadata_InteractionType_PROFESSIONALLY_PRODUCED; using google::cloud::speech::v1p1beta1::RecognitionMetadata_InteractionType_VOICE_SEARCH; using google::cloud::speech::v1p1beta1::RecognitionMetadata_InteractionType_VOICE_COMMAND; using google::cloud::speech::v1p1beta1::RecognitionMetadata_InteractionType_DICTATION; using google::cloud::speech::v1p1beta1::RecognitionMetadata_MicrophoneDistance_NEARFIELD; using google::cloud::speech::v1p1beta1::RecognitionMetadata_MicrophoneDistance_MIDFIELD; using google::cloud::speech::v1p1beta1::RecognitionMetadata_MicrophoneDistance_FARFIELD; using google::cloud::speech::v1p1beta1::RecognitionMetadata_OriginalMediaType_AUDIO; using google::cloud::speech::v1p1beta1::RecognitionMetadata_OriginalMediaType_VIDEO; using google::cloud::speech::v1p1beta1::RecognitionMetadata_RecordingDeviceType_SMARTPHONE; using google::cloud::speech::v1p1beta1::RecognitionMetadata_RecordingDeviceType_PC; using google::cloud::speech::v1p1beta1::RecognitionMetadata_RecordingDeviceType_PHONE_LINE; using google::cloud::speech::v1p1beta1::RecognitionMetadata_RecordingDeviceType_VEHICLE; using google::cloud::speech::v1p1beta1::RecognitionMetadata_RecordingDeviceType_OTHER_OUTDOOR_DEVICE; using google::cloud::speech::v1p1beta1::RecognitionMetadata_RecordingDeviceType_OTHER_INDOOR_DEVICE; using google::cloud::speech::v1p1beta1::StreamingRecognizeResponse_SpeechEventType_END_OF_SINGLE_UTTERANCE; using google::rpc::Status; namespace { int case_insensitive_match(std::string s1, std::string s2) { std::transform(s1.begin(), s1.end(), s1.begin(), ::tolower); std::transform(s2.begin(), s2.end(), s2.begin(), ::tolower); if(s1.compare(s2) == 0) return 1; //The strings are same return 0; //not matched } } class GStreamer; class GStreamer { public: GStreamer(switch_core_session_t *session, uint32_t channels, char* lang, int interim, int single_utterance, int separate_recognition, int max_alternatives, int profanity_filter, int word_time_offset, int punctuation, char* model, int enhanced, char* hints) : m_session(session), m_writesDone(false) { const char* var; switch_channel_t *channel = switch_core_session_get_channel(session); if (var = switch_channel_get_variable(channel, "GOOGLE_APPLICATION_CREDENTIALS")) { auto channelCreds = grpc::SslCredentials(grpc::SslCredentialsOptions()); auto callCreds = grpc::ServiceAccountJWTAccessCredentials(var); auto creds = grpc::CompositeChannelCredentials(channelCreds, callCreds); m_channel = grpc::CreateChannel("speech.googleapis.com", creds); } else { auto creds = grpc::GoogleDefaultCredentials(); m_channel = grpc::CreateChannel("speech.googleapis.com", creds); } m_stub = Speech::NewStub(m_channel); auto* streaming_config = m_request.mutable_streaming_config(); RecognitionConfig* config = streaming_config->mutable_config(); streaming_config->set_interim_results(interim); if (single_utterance == 1) { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "enable_single_utterance\n"); streaming_config->set_single_utterance(true); } config->set_language_code(lang); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "transcribe language %s \n", lang); config->set_sample_rate_hertz(8000); config->set_encoding(RecognitionConfig::LINEAR16); // the rest of config comes from channel vars // number of channels in the audio stream (default: 1) if (channels > 1) { config->set_audio_channel_count(channels); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "audio_channel_count %d\n", channels); // transcribe each separately? if (separate_recognition == 1) { config->set_enable_separate_recognition_per_channel(true); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "enable_separate_recognition_per_channel on\n"); } } // max alternatives if (max_alternatives > 1) { config->set_max_alternatives(max_alternatives); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "max_alternatives %d\n", max_alternatives); } // profanity filter if (profanity_filter == 1) { config->set_profanity_filter(true); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "profanity_filter\n"); } // enable word offsets if (word_time_offset == 1) { config->set_enable_word_time_offsets(true); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "enable_word_time_offsets\n"); } // enable automatic punctuation if (punctuation == 1) { config->set_enable_automatic_punctuation(true); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "enable_automatic_punctuation\n"); } // speech model if (model != NULL) { config->set_model(model); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "speech model %s\n", model); } // use enhanced model if (enhanced == 1) { config->set_use_enhanced(true); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "use_enhanced\n"); } // hints if (hints != NULL) { auto* adaptation = config->mutable_adaptation(); auto* phrase_set = adaptation->add_phrase_sets(); char *phrases[500] = { 0 }; auto *context = config->add_speech_contexts(); int argc = switch_separate_string((char *) hints, ',', phrases, 500); for (int i = 0; i < argc; i++) { auto* phrase = phrase_set->add_phrases(); phrase->set_value(phrases[i]); } switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "added %d hints\n", argc); } // alternative language if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_ALTERNATIVE_LANGUAGE_CODES")) { char *alt_langs[3] = { 0 }; int argc = switch_separate_string((char *) var, ',', alt_langs, 3); for (int i = 0; i < argc; i++) { config->add_alternative_language_codes(alt_langs[i]); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "added alternative lang %s\n", alt_langs[i]); } } // speaker diarization if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_SPEAKER_DIARIZATION")) { auto* diarization_config = config->mutable_diarization_config(); diarization_config->set_enable_speaker_diarization(true); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "enabling speaker diarization\n", var); if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_SPEAKER_DIARIZATION_MIN_SPEAKER_COUNT")) { int count = std::max(atoi(var), 1); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "setting min speaker count to %d\n", count); diarization_config->set_min_speaker_count(count); } if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_SPEAKER_DIARIZATION_MAX_SPEAKER_COUNT")) { int count = std::max(atoi(var), 2); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "setting max speaker count to %d\n", count); diarization_config->set_max_speaker_count(count); } } // recognition metadata auto* metadata = config->mutable_metadata(); if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_METADATA_INTERACTION_TYPE")) { if (case_insensitive_match("discussion", var)) metadata->set_interaction_type(RecognitionMetadata_InteractionType_DISCUSSION); if (case_insensitive_match("presentation", var)) metadata->set_interaction_type(RecognitionMetadata_InteractionType_PRESENTATION); if (case_insensitive_match("phone_call", var)) metadata->set_interaction_type(RecognitionMetadata_InteractionType_PHONE_CALL); if (case_insensitive_match("voicemail", var)) metadata->set_interaction_type(RecognitionMetadata_InteractionType_VOICEMAIL); if (case_insensitive_match("professionally_produced", var)) metadata->set_interaction_type(RecognitionMetadata_InteractionType_PROFESSIONALLY_PRODUCED); if (case_insensitive_match("voice_search", var)) metadata->set_interaction_type(RecognitionMetadata_InteractionType_VOICE_SEARCH); if (case_insensitive_match("voice_command", var)) metadata->set_interaction_type(RecognitionMetadata_InteractionType_VOICE_COMMAND); if (case_insensitive_match("dictation", var)) metadata->set_interaction_type(RecognitionMetadata_InteractionType_DICTATION); } if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_METADATA_INDUSTRY_NAICS_CODE")) { metadata->set_industry_naics_code_of_audio(atoi(var)); } if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_METADATA_MICROPHONE_DISTANCE")) { if (case_insensitive_match("nearfield", var)) metadata->set_microphone_distance(RecognitionMetadata_MicrophoneDistance_NEARFIELD); if (case_insensitive_match("midfield", var)) metadata->set_microphone_distance(RecognitionMetadata_MicrophoneDistance_MIDFIELD); if (case_insensitive_match("farfield", var)) metadata->set_microphone_distance(RecognitionMetadata_MicrophoneDistance_FARFIELD); } if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_METADATA_ORIGINAL_MEDIA_TYPE")) { if (case_insensitive_match("audio", var)) metadata->set_original_media_type(RecognitionMetadata_OriginalMediaType_AUDIO); if (case_insensitive_match("video", var)) metadata->set_original_media_type(RecognitionMetadata_OriginalMediaType_VIDEO); } if (var = switch_channel_get_variable(channel, "GOOGLE_SPEECH_METADATA_RECORDING_DEVICE_TYPE")) { if (case_insensitive_match("smartphone", var)) metadata->set_recording_device_type(RecognitionMetadata_RecordingDeviceType_SMARTPHONE); if (case_insensitive_match("pc", var)) metadata->set_recording_device_type(RecognitionMetadata_RecordingDeviceType_PC); if (case_insensitive_match("phone_line", var)) metadata->set_recording_device_type(RecognitionMetadata_RecordingDeviceType_PHONE_LINE); if (case_insensitive_match("vehicle", var)) metadata->set_recording_device_type(RecognitionMetadata_RecordingDeviceType_VEHICLE); if (case_insensitive_match("other_outdoor_device", var)) metadata->set_recording_device_type(RecognitionMetadata_RecordingDeviceType_OTHER_OUTDOOR_DEVICE); if (case_insensitive_match("other_indoor_device", var)) metadata->set_recording_device_type(RecognitionMetadata_RecordingDeviceType_OTHER_INDOOR_DEVICE); } // Begin a stream. m_streamer = m_stub->StreamingRecognize(&m_context); // Write the first request, containing the config only. m_streamer->Write(m_request); } ~GStreamer() { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(m_session), SWITCH_LOG_DEBUG, "GStreamer::~GStreamer - deleting channel and stub\n"); } bool write(void* data, uint32_t datalen) { m_request.set_audio_content(data, datalen); bool ok = m_streamer->Write(m_request); return ok; } uint32_t nextMessageSize(void) { uint32_t size = 0; m_streamer->NextMessageSize(&size); return size; } bool read(StreamingRecognizeResponse* response) { return m_streamer->Read(response); } grpc::Status finish() { return m_streamer->Finish(); } void writesDone() { // grpc crashes if we call this twice on a stream if (!m_writesDone) { m_streamer->WritesDone(); m_writesDone = true; } } protected: private: switch_core_session_t* m_session; grpc::ClientContext m_context; std::shared_ptr<grpc::Channel> m_channel; std::unique_ptr<Speech::Stub> m_stub; std::unique_ptr< grpc::ClientReaderWriterInterface<StreamingRecognizeRequest, StreamingRecognizeResponse> > m_streamer; StreamingRecognizeRequest m_request; bool m_writesDone; }; static void *SWITCH_THREAD_FUNC grpc_read_thread(switch_thread_t *thread, void *obj) { static int count; struct cap_cb *cb = (struct cap_cb *) obj; GStreamer* streamer = (GStreamer *) cb->streamer; // Read responses. StreamingRecognizeResponse response; while (streamer->read(&response)) { // Returns false when no more to read. count++; switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "response counter: %d\n",count) ; auto speech_event_type = response.speech_event_type(); Status st = response.error(); switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "speech_event_type: %d \n", response.speech_event_type()) ; switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "grpc_read_thread: error %s code: (%d)\n", st.message().c_str(), st.code()) ; if (response.has_error()) { Status status = response.error(); switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "grpc_read_thread: error %s (%d)\n", status.message().c_str(), status.code()) ; } switch_core_session_t* session = switch_core_session_locate(cb->sessionId); if (!session) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "grpc_read_thread: session %s is gone!\n", cb->sessionId) ; return nullptr; } if (cb->play_file == 1){ cb->responseHandler(session, "play_interrupt"); } for (int r = 0; r < response.results_size(); ++r) { auto result = response.results(r); cJSON * jResult = cJSON_CreateObject(); cJSON * jAlternatives = cJSON_CreateArray(); cJSON * jStability = cJSON_CreateNumber(result.stability()); cJSON * jIsFinal = cJSON_CreateBool(result.is_final()); cJSON_AddItemToObject(jResult, "stability", jStability); cJSON_AddItemToObject(jResult, "is_final", jIsFinal); cJSON_AddItemToObject(jResult, "alternatives", jAlternatives); for (int a = 0; a < result.alternatives_size(); ++a) { auto alternative = result.alternatives(a); cJSON* jAlt = cJSON_CreateObject(); cJSON* jConfidence = cJSON_CreateNumber(alternative.confidence()); cJSON* jTranscript = cJSON_CreateString(alternative.transcript().c_str()); cJSON_AddItemToObject(jAlt, "confidence", jConfidence); cJSON_AddItemToObject(jAlt, "transcript", jTranscript); if (alternative.words_size() > 0) { cJSON * jWords = cJSON_CreateArray(); switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "grpc_read_thread: %d words\n", alternative.words_size()) ; for (int b = 0; b < alternative.words_size(); b++) { auto words = alternative.words(b); cJSON* jWord = cJSON_CreateObject(); cJSON_AddItemToObject(jWord, "word", cJSON_CreateString(words.word().c_str())); if (words.has_start_time()) { cJSON_AddItemToObject(jWord, "start_time", cJSON_CreateNumber(words.start_time().seconds())); } if (words.has_end_time()) { cJSON_AddItemToObject(jWord, "end_time", cJSON_CreateNumber(words.end_time().seconds())); } int speaker_tag = words.speaker_tag(); if (speaker_tag > 0) { cJSON_AddItemToObject(jWord, "speaker_tag", cJSON_CreateNumber(speaker_tag)); } float confidence = words.confidence(); if (confidence > 0.0) { cJSON_AddItemToObject(jWord, "confidence", cJSON_CreateNumber(confidence)); } cJSON_AddItemToArray(jWords, jWord); } cJSON_AddItemToObject(jAlt, "words", jWords); } cJSON_AddItemToArray(jAlternatives, jAlt); } char* json = cJSON_PrintUnformatted(jResult); cb->responseHandler(session, (const char *) json); free(json); cJSON_Delete(jResult); } if (speech_event_type == StreamingRecognizeResponse_SpeechEventType_END_OF_SINGLE_UTTERANCE) { // we only get this when we have requested it, and recognition stops after we get this switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "grpc_read_thread: got end_of_utterance\n") ; cb->responseHandler(session, "end_of_utterance"); cb->end_of_utterance = 1; streamer->writesDone(); } switch_core_session_rwunlock(session); switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "grpc_read_thread: got %d responses\n", response.results_size()); } { switch_core_session_t* session = switch_core_session_locate(cb->sessionId); if (session) { if (1 == cb->end_of_utterance) { cb->responseHandler(session, "end_of_transcript"); } grpc::Status status = streamer->finish(); if (11 == status.error_code()) { if (std::string::npos != status.error_message().find("Exceeded maximum allowed stream duration")) { cb->responseHandler(session, "max_duration_exceeded"); } else { cb->responseHandler(session, "no_audio"); } } switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "grpc_read_thread: finish() status %s (%d)\n", status.error_message().c_str(), status.error_code()) ; switch_core_session_rwunlock(session); } } return nullptr; } extern "C" { switch_status_t google_speech_init() { const char* gcsServiceKeyFile = std::getenv("GOOGLE_APPLICATION_CREDENTIALS"); if (gcsServiceKeyFile) { try { auto creds = grpc::GoogleDefaultCredentials(); } catch (const std::exception& e) { switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_CRIT, "Error initializing google api with provided credentials in %s: %s\n", gcsServiceKeyFile, e.what()); return SWITCH_STATUS_FALSE; } } return SWITCH_STATUS_SUCCESS; } switch_status_t google_speech_cleanup() { return SWITCH_STATUS_SUCCESS; } switch_status_t google_speech_session_init(switch_core_session_t *session, responseHandler_t responseHandler, uint32_t samples_per_second, uint32_t channels, char* lang, int interim, int single_utterance, int separate_recognition, int max_alternatives, int profanity_filter, int word_time_offset, int punctuation, char* model, int enhanced, char* hints, char* play_file, void **ppUserData) { switch_channel_t *channel = switch_core_session_get_channel(session); struct cap_cb *cb; int err; cb =(struct cap_cb *) switch_core_session_alloc(session, sizeof(*cb)); strncpy(cb->sessionId, switch_core_session_get_uuid(session), MAX_SESSION_ID); cb->end_of_utterance = 0; if (play_file != NULL){ cb->play_file = 1; } switch_mutex_init(&cb->mutex, SWITCH_MUTEX_NESTED, switch_core_session_get_pool(session)); if (samples_per_second != 8000) { cb->resampler = speex_resampler_init(channels, samples_per_second, 8000, SWITCH_RESAMPLE_QUALITY, &err); if (0 != err) { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "%s: Error initializing resampler: %s.\n", switch_channel_get_name(channel), speex_resampler_strerror(err)); return SWITCH_STATUS_FALSE; } } else { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_DEBUG, "%s: no resampling needed for this call\n", switch_channel_get_name(channel)); } GStreamer *streamer = NULL; try { streamer = new GStreamer(session, channels, lang, interim, single_utterance, separate_recognition, max_alternatives, profanity_filter, word_time_offset, punctuation, model, enhanced, hints); cb->streamer = streamer; } catch (std::exception& e) { switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_ERROR, "%s: Error initializing gstreamer: %s.\n", switch_channel_get_name(channel), e.what()); return SWITCH_STATUS_FALSE; } cb->responseHandler = responseHandler; // create the read thread switch_threadattr_t *thd_attr = NULL; switch_memory_pool_t *pool = switch_core_session_get_pool(session); switch_threadattr_create(&thd_attr, pool); switch_threadattr_stacksize_set(thd_attr, SWITCH_THREAD_STACKSIZE); switch_thread_create(&cb->thread, thd_attr, grpc_read_thread, cb, pool); *ppUserData = cb; return SWITCH_STATUS_SUCCESS; } switch_status_t google_speech_session_cleanup(switch_core_session_t *session, int channelIsClosing) { switch_channel_t *channel = switch_core_session_get_channel(session); switch_media_bug_t *bug = (switch_media_bug_t*) switch_channel_get_private(channel, MY_BUG_NAME); if (bug) { struct cap_cb *cb = (struct cap_cb *) switch_core_media_bug_get_user_data(bug); switch_mutex_lock(cb->mutex); // stop playback if available if (cb->play_file == 1){ if (switch_channel_test_flag(channel, CF_BROADCAST)) { switch_channel_stop_broadcast(channel); } else { switch_channel_set_flag_value(channel, CF_BREAK, 1); } } // close connection and get final responses GStreamer* streamer = (GStreamer *) cb->streamer; if (streamer) { streamer->writesDone(); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "google_speech_session_cleanup: waiting for read thread to complete\n"); switch_status_t st; switch_thread_join(&st, cb->thread); switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "google_speech_session_cleanup: read thread completed\n"); delete streamer; cb->streamer = NULL; } if (cb->resampler) { speex_resampler_destroy(cb->resampler); } switch_channel_set_private(channel, MY_BUG_NAME, NULL); switch_mutex_unlock(cb->mutex); if (!channelIsClosing) { switch_core_media_bug_remove(session, &bug); } switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "google_speech_session_cleanup: Closed stream\n"); return SWITCH_STATUS_SUCCESS; } switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_INFO, "%s Bug is not attached.\n", switch_channel_get_name(channel)); return SWITCH_STATUS_FALSE; } switch_bool_t google_speech_frame(switch_media_bug_t *bug, void* user_data) { switch_core_session_t *session = switch_core_media_bug_get_session(bug); struct cap_cb *cb = (struct cap_cb *) user_data; if (cb->streamer && !cb->end_of_utterance) { GStreamer* streamer = (GStreamer *) cb->streamer; uint8_t data[SWITCH_RECOMMENDED_BUFFER_SIZE]; switch_frame_t frame = {}; frame.data = data; frame.buflen = SWITCH_RECOMMENDED_BUFFER_SIZE; if (switch_mutex_trylock(cb->mutex) == SWITCH_STATUS_SUCCESS) { while (switch_core_media_bug_read(bug, &frame, SWITCH_TRUE) == SWITCH_STATUS_SUCCESS && !switch_test_flag((&frame), SFF_CNG)) { if (frame.datalen) { if (cb->resampler) { spx_int16_t out[SWITCH_RECOMMENDED_BUFFER_SIZE]; spx_uint32_t out_len = SWITCH_RECOMMENDED_BUFFER_SIZE; spx_uint32_t in_len = frame.samples; size_t written; speex_resampler_process_interleaved_int(cb->resampler, (const spx_int16_t *) frame.data, (spx_uint32_t *) &in_len, &out[0], &out_len); streamer->write( &out[0], sizeof(spx_int16_t) * out_len); } else { streamer->write( frame.data, sizeof(spx_int16_t) * frame.samples); } } } switch_mutex_unlock(cb->mutex); } } return SWITCH_TRUE; } }
45.870909
163
0.720282
[ "model", "transform" ]
965c2c2a583e09766ba0d4983f3ecb83574aeeb8
10,857
cc
C++
llvm_mode/utils.cc
lmrs2/afl_cc
d074c0470ce58e15f537cdf16856ab3669c266fb
[ "Apache-2.0" ]
20
2019-11-07T05:40:59.000Z
2021-07-06T17:16:57.000Z
llvm_mode/utils.cc
lmrs2/afl_cc
d074c0470ce58e15f537cdf16856ab3669c266fb
[ "Apache-2.0" ]
1
2020-07-21T22:29:22.000Z
2020-07-21T22:29:22.000Z
llvm_mode/utils.cc
lmrs2/afl_cc
d074c0470ce58e15f537cdf16856ab3669c266fb
[ "Apache-2.0" ]
8
2019-11-27T06:21:12.000Z
2020-10-28T00:18:31.000Z
#include "../config.h" #include "../debug.h" #include "common.h" #include <iostream> #include <sstream> #include <algorithm> #include <cctype> #include <iostream> #include <string.h> // for demangle #include <cxxabi.h> #include "llvm/IR/DebugInfo.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/Constants.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/IR/CallSite.h" using namespace llvm; namespace utils { void remove_char(std::string & s, char c) { std::string::iterator end_pos = std::remove(s.begin(), s.end(), c); s.erase(end_pos, s.end()); } std::string Tolower(std::string s) { std::string ret; for (size_t i=0; i<s.size(); ++i) { ret.push_back(std::tolower(s[i])); } return ret; } const char * getEnvVar(const char * s) { char * env = getenv(s); return env ? env : ""; } bool isEnvVarSet(const char * s) { const char * env = getEnvVar(s); return ( *env != '\0' && strcmp(env, "0") != 0 ); } bool isEnvVarSetTo(const char * s, const char * v) { const char * env = getEnvVar(s); return ( strcmp(env, v) == 0 ); } void split(const std::string& s, char delim, std::set<std::string>& v, bool demangle) { std::stringstream ss(s); std::string item; while (getline(ss, item, delim)) { if (demangle) { item = utils::demangleName(item); } if (!v.count(item)) v.insert(item); } } void split(const std::string& s, char delim, std::vector<std::string>& v, bool demangle) { std::stringstream ss(s); std::string item; while (getline(ss, item, delim)) { if (demangle) { item = utils::demangleName(item); } if (std::find(v.begin(), v.end(), item) == v.end()) v.push_back(item); } } std::string getDebugInfo(Instruction &I) { std::string debugInfo; BasicBlock & BB = *I.getParent(); MDNode* dbg = I.getMetadata("dbg"); /* If we cannot find dbg on the instruction, try in the entire parent block */ if ( !dbg ) { for (auto & II : BB) { if ( (dbg = II.getMetadata("dbg")) ) { break; } } } if ( dbg ) { DebugLoc DLoc(dbg); DILocation * DILoc = DLoc.get(); char * dup = strdup(DILoc->getFilename().str().c_str()); char * name = basename(dup); std::string filename = std::string(name); free (dup); std::string line = std::to_string(DILoc->getLine()); std::string point = "."; std::string rep = "_"; std::string minus = "-"; while ( filename.find(minus) != std::string::npos ) { filename = filename.replace(filename.find(minus),minus.length(),(rep+rep).c_str(), 2); } while ( filename.find(point) != std::string::npos ) { filename = filename.replace(filename.find(point),point.length(),rep) + rep + line; } debugInfo = filename; } return debugInfo; } bool starts_with(const std::string& str, const std::string& prefix) { if(prefix.length() > str.length()) { return false; } return str.substr(0, prefix.length()) == prefix; } bool is_llvm_dbg_intrinsic(Instruction & instr) { const bool is_call = instr.getOpcode() == Instruction::Invoke || instr.getOpcode() == Instruction::Call; if(!is_call) { return false; } CallSite cs(&instr); Function* calledFunc = cs.getCalledFunction(); if (calledFunc != NULL) { const bool ret = calledFunc->isIntrinsic() && starts_with(calledFunc->getName().str(), "llvm."); //llvm::errs() << instr << ":" << ret << "\n"; return ret; } else { return false; } } static bool is_afl_function_call(Instruction & II) { const bool is_call = II.getOpcode() == Instruction::Call; if(!is_call) { return false; } CallSite cs(&II); Function* calledFunc = cs.getCalledFunction(); if (calledFunc != NULL) { return calledFunc->getName().equals("__afl_bb_trace"); } return false; } std::string addSrcInfo(BasicBlock &BB, std::string sinit) { std::string srcInfo; std::set<std::string> Set; for (auto & II : BB) { /* Skip intrinsics. Why? Because code like int a; will have an intrinsic associated with it, and we don't want to account for it thru functional coverage -- see paper */ if ( is_llvm_dbg_intrinsic(II) ) { continue; } if ( is_afl_function_call(II) ) { continue; } if ( MDNode* dbg = II.getMetadata("dbg") ) { DebugLoc DLoc(dbg); DILocation * DILoc = DLoc.get(); Set.insert( DILoc->getFilename().str() + ":" + std::to_string(DILoc->getLine()) ); } } for (auto s : Set) { srcInfo += s + ","; } return ((sinit.size()) ? (sinit + ",") : "") + srcInfo.substr(0, srcInfo.size() > 0 ? srcInfo.size()-1: 0); } /* Replace original instruction and copy the dictionnary information too */ void ReplaceInstWithInst (LLVMContext & C, std::string origin, BasicBlock::InstListType & BIL, BasicBlock::iterator & OldI, Instruction & NewI) { bool found = false; DictElt elt = getDictRecordFromInstr(C, *OldI, origin, found); ReplaceInstWithInst(BIL, OldI, &NewI); if ( found ) { recordDictToInstr(C, NewI, elt, origin, false /* already stringified */); } } bool CopyDictToInst(LLVMContext & C, std::string origin, Instruction & FromI, Instruction & ToI) { bool found = false; DictElt elt = getDictRecordFromInstr(C, FromI, origin, found); if ( found ) { recordDictToInstr(C, ToI, elt, origin, false /* already stringified */); } return found; } void recordDictToInstr(LLVMContext & C, Instruction & I, utils::DictElt & elt, std::string origin, bool doStringify, bool isText) { // http://jiten-thakkar.com/posts/how-to-read-and-write-metadata-in-llvm std::string ss = doStringify ? utils::Stringify(elt.getFirst(), isText) : elt.getFirst(); std::string debug = elt.getSecond(); std::string value; if (ss.size()) { /* filename_c_line=keyvalue */ if ( !doStringify ) { ASSERT ( ss.size() >= 2 ); /* should have at least the first and last double-quote '"' */ ss = ss.substr(1, ss.size() - 2); } value = (debug.size()?debug:"NDEBUG") + "=\"" + ss + "\""; MDString * S = MDString::get(C, value); ASSERT (S); MDNode* Meta = MDNode::get(C, S); /* origin = value */ I.setMetadata(origin, Meta); } } void init_metanames(void) { /* Creating the custon kinds seems necessary. Without this I encountered problems when adding metadata */ getGlobalContext().getMDKindID(S2U_DICT); /* create the S2U_DICT meta kind */ getGlobalContext().getMDKindID(C2U_DICT); /* create the C2U_DICT meta kind */ /* Initialiaze the meta names */ for ( size_t n=0; n< utils::max_origin_multiple(); ++n ) { getGlobalContext().getMDKindID(utils::origin_to_multiple(S2U_DICT, n)); /* create the S2U_DICT meta kind */ getGlobalContext().getMDKindID(utils::origin_to_multiple(SIC_DICT, n)); /* create the SIC_DICT meta kind */ } getGlobalContext().getMDKindID("FuncPointedToList"); /* For retrieveing DSA's generated list of function. See dsa/lib/DSA/CallTargets.cpp */ } std::string origin_to_multiple(std::string origin, size_t n) { return origin + "_" + std::to_string(n); } /* use when we need an instruction to have mtultiple meta from same origin */ void recordMultipleDictToInstr(LLVMContext & C, Instruction & I, DictElt & elt, std::string origin, bool doStringify, bool isText) { /* Find the available origin as origin-n */ size_t n = 0; DictElt elmt("",""); std::string orig; while (1) { bool found = false; orig = origin_to_multiple(origin, n); elmt = getDictRecordFromInstr(C, I, orig, found); if (!found) { break; } else { ++n; } } ASSERT ( n < max_origin_multiple() ); recordDictToInstr(C, I, elt, orig, doStringify, isText); } DictElt2 getDict2RecordFromInstr(LLVMContext & C, Instruction & I, std::string origin, bool & found) { DictElt elmt = getDictRecordFromInstr(C, I, origin, found); return std::make_pair(elmt.getFirst(), elmt.getSecond()); } DictElt getDictRecordFromInstr(LLVMContext & C, Instruction & I, std::string origin, bool & found, bool remove) { if ( MDNode* Meta = I.getMetadata(origin) ) { const std::string s = cast<MDString>(Meta->getOperand(0))->getString().str(); std::vector<std::string> values; split(s, '=', values); ASSERT ( values.size() == 2 ); found = true; std::string ss = values.at(1); std::string debug = values.at(0); if (remove) I.setMetadata(origin, NULL); return DictElt(ss, debug); } found = false; return DictElt("", ""); } bool isDictRecordedToBB(llvm::BasicBlock & BB, std::string origin) { for ( auto & I : BB ) { if ( isDictRecordedToInstr(I, origin) ) { return true; } } return false; } bool isDictRecordedToInstr(Instruction & I, std::string origin) { return (I.getMetadata(origin) != NULL); } std::string getSrcInfo(BasicBlock &BB) { return addSrcInfo(BB, ""); } std::string Stringify(const std::string & data, bool isText) { std::string TokenStr; size_t len = data.size(); if (len < MIN_AUTO_EXTRA || len > MAX_AUTO_EXTRA) { WARNF("Ignoring token of invalid length '%s'", data.c_str()); return ""; } for(size_t i = 0; i < len; ++i) { /* Do not append the last '\0' if it's text */ if (isText && i==len-1 && data[len-1] == '\0') { return TokenStr; } uint8_t c = data[i]; switch (c) { case 0 ... 31: case 127 ... 255: /* = and " are special characters as we keep meta as name="value" */ case '=': case '\"': case '\\': { char buf[5] { }; sprintf(buf, "\\x%02x", c); TokenStr.append(buf); break; } default: { if (isText) { TokenStr.push_back(c); } else { char buf[5] { }; sprintf(buf, "\\x%02x", c); TokenStr.append(buf); } break; } } } return TokenStr; } // http://aviral.lab.asu.edu/llvm-def-use-use-def-chains/ // https://stackoverflow.com/questions/35370195/llvm-difference-between-uses-and-user-in-instruction-or-value-classes void getUsersOf(Value & V, std::vector<Instruction*> & Userlist) { for(auto U : V.users()){ // U is of type User* if (auto I = dyn_cast<Instruction>(U)){ // an instruction uses V Userlist.push_back(I); } } } static std::string demangle(StringRef SRef) { int status = -1; const char* name = SRef.str().c_str(); std::unique_ptr<char, void(*)(void*)> res { abi::__cxa_demangle(name, NULL, NULL, &status), std::free }; return (status == 0) ? res.get() : std::string(name); } std::string demangleName( StringRef SRef ) { std::string demangledF = demangle(SRef); std::size_t pos = demangledF.find("("); if ( std::string::npos == pos ) { return demangledF; } return demangledF.substr (0, pos); } } // end namespace
28.496063
145
0.622456
[ "vector" ]
965f4bd367061d4da25296001a4a6d11b7b3fe6a
790
cpp
C++
1-Two-Sum/two-sum.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
4
2018-08-07T11:45:32.000Z
2019-05-19T08:52:19.000Z
1-Two-Sum/two-sum.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
null
null
null
1-Two-Sum/two-sum.cpp
xta0/LeetCode-Solutions
ab0de97b35fb54c24bcef0398a9d75bdac9ee8b2
[ "MIT" ]
null
null
null
#include <iostream> #include <map> #include <vector> using namespace std; /* Hashmap solution Time Complexity: O(n) Space Complexity: O(n) */ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { std::vector<int> result; map<int,int> dict; for(size_t i=0; i<nums.size(); ++i){ int l = nums[i]; int r = target -l; if(dict.find(r) != dict.end()){ if(dict[r] != i){ result.push_back(i); result.push_back(dict[r]); break; } } dict[l] = i; } return result; } }; int main(){ Solution s; vector<int> nums = {3,2,4}; s.twoSum(nums, 6); return 0; }
19.268293
55
0.464557
[ "vector" ]
965f6403253887ce0479fef30ca1b65045b9194c
3,193
hpp
C++
tket/src/MeasurementSetup/MeasurementSetup.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
tket/src/MeasurementSetup/MeasurementSetup.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
tket/src/MeasurementSetup/MeasurementSetup.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
// Copyright 2019-2021 Cambridge Quantum Computing // // 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. #pragma once #include "Circuit/Circuit.hpp" #include "Utils/PauliStrings.hpp" namespace tket { /** * MeasurementSetup * Captures an expectation value experiment. * Given a collection of Pauli terms, the setup contains a collection * of measurement circuits from which each Pauli measurement can be extracted. * * The result_map maps Pauli terms to circuits from which the expectation value * can be obtained, along with the classical post-processing required on each * shot (which bits/columns of the shot table to XOR together, and whether to * invert the final value). * * There may be multiple measurement circuits that measure the same Pauli term, * so we have a vector of MeasurementBitMaps for each term to exploit this and * effectively get extra shots for free. */ class MeasurementSetup { public: struct MeasurementBitMap { MeasurementBitMap( unsigned _circ_index, const std::vector<unsigned> &_bits, bool _invert = 0) : circ_index{_circ_index}, bits{_bits}, invert{_invert} {} unsigned circ_index; std::vector<unsigned> bits; bool invert; const unsigned &get_circ_index() const { return circ_index; } const std::vector<unsigned> &get_bits() const { return bits; } const bool &get_invert() const { return invert; } std::string to_str() const; }; struct QPSHasher { std::size_t operator()(const QubitPauliString &qps) const { return hash_value(qps); } }; typedef std::unordered_map< QubitPauliString, std::vector<MeasurementBitMap>, QPSHasher> measure_result_map_t; const std::vector<Circuit> &get_circs() const { return measurement_circs; } const measure_result_map_t &get_result_map() const { return result_map; } void add_measurement_circuit(const Circuit &circ); void add_result_for_term( const QubitPauliString &term, const MeasurementBitMap &result); /** * Rejects the coefficient in the QubitPauliTensor. Used for * convenience at the C++ level, and should not be exposed. */ void add_result_for_term( const QubitPauliTensor &term, const MeasurementBitMap &result); /** * Checks that the tensors to be measured correspond to the * correct tensors generated by the measurement circs. Includes * parity checks. */ bool verify() const; std::string to_str() const; private: /** * Clifford circuits to generate the correct Pauli measurements, * with Measure gates on the required qubits. */ std::vector<Circuit> measurement_circs; measure_result_map_t result_map; }; } // namespace tket
33.610526
79
0.728782
[ "vector" ]
96606a8b3da7b0040c2aace6e790097286bc445c
29,059
hpp
C++
library/peripherals/msp432p401r/system_controller.hpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
6
2020-06-20T23:56:42.000Z
2021-12-18T08:13:54.000Z
library/peripherals/msp432p401r/system_controller.hpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
153
2020-06-09T14:49:29.000Z
2022-01-31T16:39:39.000Z
library/peripherals/msp432p401r/system_controller.hpp
SarahS16/SJSU-Dev2
47f9ddb7d3c3743f839b57f381bf979dd61d49ab
[ "Apache-2.0" ]
10
2020-08-02T00:55:38.000Z
2022-01-24T23:06:51.000Z
#pragma once #include <cstdint> #include "platforms/targets/msp432p401r/msp432p401r.h" #include "peripherals/system_controller.hpp" #include "utility/math/bit.hpp" #include "utility/build_info.hpp" #include "utility/enum.hpp" #include "utility/log.hpp" namespace sjsu { namespace msp432p401r { /// SystemController class used to manage power control and various clock system /// resources on the MSP432P401R MCU. class SystemController final : public sjsu::SystemController { public: /// Contains the device id for each of the available clock system modules. class Modules { public: //! @cond Doxygen_Suppress static constexpr auto kAuxiliaryClock = ResourceID::Define<0>(); static constexpr auto kMasterClock = ResourceID::Define<1>(); static constexpr auto kSubsystemMasterClock = ResourceID::Define<2>(); static constexpr auto kLowSpeedSubsystemMasterClock = ResourceID::Define<3>(); static constexpr auto kBackupClock = ResourceID::Define<4>(); static constexpr auto kLowFrequencyClock = ResourceID::Define<5>(); static constexpr auto kVeryLowFrequencyClock = ResourceID::Define<6>(); static constexpr auto kReferenceClock = ResourceID::Define<7>(); static constexpr auto kModuleClock = ResourceID::Define<8>(); static constexpr auto kSystemClock = ResourceID::Define<9>(); //! @endcond }; /// The available internal oscillators for the clock system module. enum class Oscillator : uint8_t { /// Low frequency oscillator (LFXT) with frequency of 32.768 kHz. kLowFrequency = 0b000, /// Ultra low power oscillator (VLO) with typical frequency of 9.4 kHz. kVeryLowFrequency = 0b001, /// Low frequency reference oscillator (REFO) that can be configured to /// output 32.768 kHz or 128 kHz. kReference = 0b010, /// Digitally controlled oscillator (DCO) that can be configured to /// generate a frequency between 1 MHZ and 48 MHz. kDigitallyControlled = 0b011, /// Low power oscillator with a typical frequency of 25 MHz. kModule = 0b100, /// High frequency oscillator (HFXT) which can be driven by an external /// oscillator or external square wave with frequency ranging from 1 MHz to /// 48 Mhz. kHighFrequency = 0b101, }; /// The available system clocks used to drive various peripheral modules where /// kAuxiliary, kMaster, kSubsystemMaster, kLowSpeedSubsystemMaster, and /// kBackup are the primary clock signals. /// /// @see Figure 6-1. Clock System Block Diagram /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=380 enum class Clock : uint8_t { /// Auxiliary clock (ACLK) with a max frequency of 128 kHz. kAuxiliary = 0, /// Master clock (MCLK) that drives the CPU. kMaster, /// Subsystem master clock (HSMCLK). kSubsystemMaster, /// Low-speed subsystem master clock (SMCLK). kLowSpeedSubsystemMaster, /// Low speed backup domain clock (BCLK). The with maximum restricted /// frequency of 32.768 kHz. kBackup, /// Low frequency low power clock (LFXTCLK). This clock can be driven /// by the LFXT oscillator or an external oscillator with a frequency /// of 32.768 kHz or less in bypass mode. kLowFrequency, /// Very low frequency low power clock (VLOCLK). kVeryLowFrequency, /// Low frequency reference clock (REFOCLK). kReference, /// Low power module clock (MODCLK). kModule, /// System oscillator clock (SYSCLK). kSystem, }; /// The available reference clock frequency options. enum ReferenceClockFrequency : uint8_t { /// 32.768 kHz. kF32768Hz = 0b0, /// 128 kHz. kF128kHz = 0b1, }; /// The available clock dividers for the primary clocks. enum class ClockDivider : uint8_t { kDivideBy1 = 0b000, kDivideBy2 = 0b001, kDivideBy4 = 0b010, kDivideBy8 = 0b011, kDivideBy16 = 0b100, kDivideBy32 = 0b101, kDivideBy64 = 0b110, kDivideBy128 = 0b111, }; /// Namespace containing the fixed clock rates of the available internal /// oscillators. /// /// @see 6.1 Clock System Introduction /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=379 struct InternalOscillator // NOLINT { /// Clock rate for the very low power oscillator. static constexpr units::frequency::hertz_t kVeryLowFrequency = 9'400_Hz; /// Clock rate for the low power oscillator. static constexpr units::frequency::hertz_t kModule = 25_MHz; /// Internal system oscillator. static constexpr units::frequency::hertz_t kSystem = 5_MHz; /// Clock rates for the reference oscillator The reference oscillator is /// configuration to be either 32.768 kHz or 128 kHz. static constexpr std::array<units::frequency::hertz_t, 2> kReference = { 32'768_Hz, 128_kHz }; }; /// Namespace containing the fixed clock rates of the available on-board /// external oscillators. /// /// @see 6.1 Clock System Introduction /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=379 struct ExternalOscillator // NOLINT { /// Clock rate for the on-board external low frequency oscillator. static constexpr units::frequency::hertz_t kLowFrequency = 32'768_Hz; /// Clock rate for the on-board external high frequency oscillator. static constexpr units::frequency::hertz_t kHighFrequency = 48_MHz; }; // =========================================================================== // Register and Bit Mask Definitions // =========================================================================== /// Namespace containing the bit masks for the Key Register (KEY) which locks /// or unlocks the other clock system registers. struct KeyRegister // NOLINT { /// @see Table 6-3. CSKEY Register Description /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=394 /// /// @returns The CSKEY bit register. static bit::Register<uint32_t> Register() { return bit::Register(&clock_system->KEY); } /// The CSKEY bit mask used for locking or unlocking the clock system /// registers. static constexpr auto kCsKey = bit::MaskFromRange(0, 15); }; /// Namespace containing the bit masks for the Control 0 Register (CTL0) /// which controls the configurations for the digitally controlled oscillator. struct Control0Register // NOLINT { /// @see Table 6-4. CSCTL0 Register Description /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=395 /// /// @returns The CSCTL0 bit register. static bit::Register<uint32_t> Register() { return bit::Register(&clock_system->CTL0); } /// DCO tuning value bit mask. static constexpr auto kTuningSelect = bit::MaskFromRange(0, 9); /// DCO frequency seelect bit mask. static constexpr auto kFrequencySelect = bit::MaskFromRange(16, 18); /// DCO enable bit mask. static constexpr auto kEnable = bit::MaskFromRange(23); }; /// Namespace containing the bit masks for the Control 1 Register (CTL1) /// which controls the configurations for selecting the oscillator source and /// clock divider for the primary clock signals. struct Control1Register // NOLINT { /// @see Table 6-5. CSCTL1 Register Description /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=396 /// /// @returns The CSCTL1 bit register. static bit::Register<uint32_t> Register() { return bit::Register(&clock_system->CTL1); } /// Master clock source select bit mask. static constexpr auto kMasterClockSourceSelect = bit::MaskFromRange(0, 2); /// Subsystem master clock source select bit mask. static constexpr auto kSubsystemClockSourceSelect = bit::MaskFromRange(4, 6); /// Auxiliary clock source select bit mask. static constexpr auto kAuxiliaryClockSourceSelect = bit::MaskFromRange(8, 10); /// Backup clock source select bit mask. static constexpr auto kBackupClockSourceSelect = bit::MaskFromRange(12); /// Master clock divider select bit mask. static constexpr auto kMasterClockDividerSelect = bit::MaskFromRange(16, 18); /// Subsystem master clock divider select bit mask. static constexpr auto kSubsystemClockDividerSelect = bit::MaskFromRange(20, 22); /// Auxiliary clock divider select bit mask. static constexpr auto kAuxiliaryClockDividerSelect = bit::MaskFromRange(24, 26); /// Low speed subsystem master clock divider select bit mask. static constexpr auto kLowSpeedSubsystemClockDividerSelect = bit::MaskFromRange(28, 30); }; /// Namespace containing the bit masks for the Clock Enable Register (CLKEN). struct ClockEnableRegister // NOLINT { /// @see Table 6-8. CSCLKEN Register Description /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=401 /// /// @returns The CSCLKEN bit register. static bit::Register<uint32_t> Register() { return bit::Register(&clock_system->CLKEN); } /// Reference clock frequency select bit mask. static constexpr auto kReferenceFrequencySelect = bit::MaskFromRange(15); }; // =========================================================================== // Clock Configuration // =========================================================================== /// @see Figure 6-1. Clock System Block Diagram /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=380 struct ClockConfiguration_t { /// Configurations for the auxiliary clock module. struct { /// @note Only the reference clock, very low frequency clock, or the low /// frequency clock can be used as the clock source. Oscillator clock_source = Oscillator::kReference; /// Clock divider for the auxiliary clock. ClockDivider divider = ClockDivider::kDivideBy1; } auxiliary = {}; /// Configurations for the master clock module. This clock module is also /// used to drive the CPU clock. struct { /// On reset, the master clock is driven by the digitally controlled /// clock. Oscillator clock_source = Oscillator::kDigitallyControlled; /// Clock divider for the master clock. ClockDivider divider = ClockDivider::kDivideBy1; } master = {}; /// Configurations for the subsystem master clock module. struct { /// On reset, the subsystem master clocks are driven by the DCO clock. /// /// @note The specified clock source is used to drive both the subsystem /// master clock and the low speed subsystem master clock. Oscillator clock_source = Oscillator::kDigitallyControlled; /// Clock divider for the subsystem master clock. ClockDivider divider = ClockDivider::kDivideBy1; /// Clock divider for the low speed subsystem master clock. ClockDivider low_speed_divider = ClockDivider::kDivideBy1; } subsystem_master = {}; /// Configurations for the backup clock module. struct { /// Clock source for the backup clock. /// /// @note Only the reference clock or the low frequency clock can be used /// as the clock source. Oscillator clock_source = Oscillator::kReference; } backup = {}; /// Configurations for the reference clock. The reference clock is /// configurable to output 32.768 kHz or 128 kHz. struct { /// The reference clock outputs a default frequency of 32.768 kHz. ReferenceClockFrequency frequency = ReferenceClockFrequency::kF32768Hz; } reference = {}; /// Configurations for the digitally controlled (DCO) clock module. struct { /// On reset, the digitally controlled clock is used to drive the master /// clock and the subsystem master clocks. This value should be set to /// false if an alternate clock source is used to drive those clocks. bool enabled = true; /// The target DCO output frequency. On reset, DCO outputs 3 MHz. units::frequency::hertz_t frequency = 3_MHz; } dco = {}; }; /// Reference to the structure containing the clock system control registers. inline static CS_Type * clock_system = msp432p401r::CS; /// Reference to the device descriptor tag-length-value (TLV) structure /// containing the clock system calibration constants. inline static TLV_Type * device_descriptors = msp432p401r::TLV; /// The number of available clocks that can be used by the system. inline static constexpr size_t kClockPeripheralCount = 10; /// @param clock_configuration The desired clock configurations for the /// system. explicit constexpr SystemController( ClockConfiguration_t & clock_configuration) : clock_configuration_(clock_configuration) { } /// Initializes the system controller by configuring the DCO clock, reference /// clock, and all the primary clocks. void Initialize() override { // For an overview of the clock system, see: // https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=380 // Internal oscillators with fixed frequencies. constexpr units::frequency::hertz_t kVlo = InternalOscillator::kVeryLowFrequency; constexpr units::frequency::hertz_t kMod = InternalOscillator::kModule; constexpr units::frequency::hertz_t kLfxt = ExternalOscillator::kLowFrequency; constexpr units::frequency::hertz_t kHfxt = ExternalOscillator::kHighFrequency; // ========================================================================= // Step 1. Configure the DCO and Reference clocks // ========================================================================= units::frequency::hertz_t dco = ConfigureDcoClock(); units::frequency::hertz_t refo = ConfigureReferenceClock(); // ========================================================================= // Step 2. Set the clock source for each of the primary clocks // ========================================================================= SetClockSource(Clock::kAuxiliary, clock_configuration_.auxiliary.clock_source); SetClockSource(Clock::kMaster, clock_configuration_.master.clock_source); SetClockSource(Clock::kSubsystemMaster, clock_configuration_.subsystem_master.clock_source); SetClockSource(Clock::kBackup, clock_configuration_.backup.clock_source); // ========================================================================= // Step 3. Configure primary clock dividers // ========================================================================= SetClockDivider(Clock::kAuxiliary, clock_configuration_.auxiliary.divider); SetClockDivider(Clock::kMaster, clock_configuration_.master.divider); SetClockDivider(Clock::kSubsystemMaster, clock_configuration_.subsystem_master.divider); SetClockDivider(Clock::kLowSpeedSubsystemMaster, clock_configuration_.subsystem_master.low_speed_divider); // ========================================================================= // Step 4. Determine the clock rate of each of the clocks based on the // configured clock source and clock dividers. // ========================================================================= units::frequency::hertz_t aclk = 0_Hz; units::frequency::hertz_t mclk = 0_Hz; units::frequency::hertz_t smclk = 0_Hz; units::frequency::hertz_t bclk = 0_Hz; switch (clock_configuration_.auxiliary.clock_source) { case Oscillator::kLowFrequency: aclk = kLfxt; break; case Oscillator::kVeryLowFrequency: aclk = kVlo; break; case Oscillator::kReference: aclk = refo; break; default: break; } switch (clock_configuration_.master.clock_source) { case Oscillator::kLowFrequency: mclk = kLfxt; break; case Oscillator::kVeryLowFrequency: mclk = kVlo; break; case Oscillator::kReference: mclk = refo; break; case Oscillator::kDigitallyControlled: mclk = dco; break; case Oscillator::kModule: mclk = kMod; break; case Oscillator::kHighFrequency: mclk = kHfxt; break; } switch (clock_configuration_.subsystem_master.clock_source) { case Oscillator::kLowFrequency: smclk = kLfxt; break; case Oscillator::kVeryLowFrequency: smclk = kVlo; break; case Oscillator::kReference: smclk = refo; break; case Oscillator::kDigitallyControlled: smclk = dco; break; case Oscillator::kModule: smclk = kMod; break; case Oscillator::kHighFrequency: smclk = kHfxt; break; } switch (clock_configuration_.backup.clock_source) { case Oscillator::kLowFrequency: bclk = kLfxt; break; case Oscillator::kReference: bclk = refo; break; default: break; } clock_rates_[Value(Clock::kAuxiliary)] = aclk / (1 << Value(clock_configuration_.auxiliary.divider)); clock_rates_[Value(Clock::kMaster)] = mclk / (1 << Value(clock_configuration_.master.divider)); clock_rates_[Value(Clock::kSubsystemMaster)] = smclk / (1 << Value(clock_configuration_.subsystem_master.divider)); clock_rates_[Value(Clock::kLowSpeedSubsystemMaster)] = smclk / (1 << Value(clock_configuration_.subsystem_master.low_speed_divider)); clock_rates_[Value(Clock::kBackup)] = bclk; clock_rates_[Value(Clock::kReference)] = refo; } /// @returns A pointer to the clock configuration object used to configure /// this system controller. void * GetClockConfiguration() override { return &clock_configuration_; } /// @returns The clock rate frequency of a clock system module. units::frequency::hertz_t GetClockRate(ResourceID peripheral) const override { if (peripheral.device_id >= kClockPeripheralCount) { return 0_MHz; } return clock_rates_[peripheral.device_id]; } /// Configures the clock divider for one of the four primary clock signals /// (ACLK, MCLK, HSMCLK, or SMCLK). /// /// @param clock The clock to configure. /// @param divider The desired clock divider value. Only the following /// dividers are available: 1, 2, 4, 8, 16, 32, 64, 128. void SetClockDivider(Clock clock, ClockDivider divider) const { if (Value(clock) > Value(Clock::kLowSpeedSubsystemMaster)) { LogWarning( "Ignoring attempt to set clock divider for a non-primary clock."); return; } constexpr bit::Mask kDividerSelectMasks[] = { Control1Register::kAuxiliaryClockDividerSelect, Control1Register::kMasterClockDividerSelect, Control1Register::kSubsystemClockDividerSelect, Control1Register::kLowSpeedSubsystemClockDividerSelect, }; UnlockClockSystemRegisters(); { Control1Register::Register() .Insert(Value(divider), kDividerSelectMasks[Value(clock)]) .Save(); } LockClockSystemRegisters(); WaitForClockReadyStatus(clock); } /// @returns Always returns false. bool IsPeripheralPoweredUp(ResourceID) const override { return false; } /// @note This function does nothing. void PowerUpPeripheral(ResourceID) const override {} /// @note This function does nothing. void PowerDownPeripheral(ResourceID) const override {} private: /// Unlocks the clock system registers by writing the necessary value to the /// CSKEY register. void UnlockClockSystemRegisters() const { constexpr uint16_t kUnlockKey = 0x695A; KeyRegister::Register().Insert(kUnlockKey, KeyRegister::kCsKey).Save(); } /// Locks the clock system registers by writing the necessary value to the /// CSKEY register. void LockClockSystemRegisters() const { constexpr uint16_t kLockKey = 0x0000; KeyRegister::Register().Insert(kLockKey, KeyRegister::kCsKey).Save(); } /// Checks and waits for a clock signal to become stable after a frequency or /// divider configuration. /// /// @note This feature is only available for the primary clock signals. /// /// @param clock The primary clock signal ready status to wait on. void WaitForClockReadyStatus(Clock clock) const { SJ2_ASSERT_FATAL( Value(clock) <= Value(Clock::kBackup), "Only the following clocks have a ready status: kAuxiliary, kMaster, " "kSubsystemMaster, kLowSpeedSubsystemMaster, or kBackup."); constexpr uint8_t kClockReadyBit = 24; const uint8_t kOffset = Value(clock); const bit::Mask kReadyBitMask = bit::MaskFromRange(static_cast<uint8_t>(kClockReadyBit + kOffset)); while (!bit::Read(clock_system->STAT, kReadyBitMask)) { continue; } } /// Configures one of the five primary clock signals (ACLK, MCLK, /// HSMCLK / SMCLK, and BCLK) to be sourced by the specified oscillator. /// /// @note When selecting the oscillator source for either SMCLK or SMCLK, the /// oscillator will applied to both clock signals. /// /// @see https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=397 /// /// @param clock The primary clock to configure. /// @param source The oscillator used to source the clock. void SetClockSource(Clock clock, Oscillator source) const { constexpr bit::Mask kPrimaryClockSelectMasks[] = { Control1Register::kAuxiliaryClockSourceSelect, Control1Register::kMasterClockSourceSelect, Control1Register::kSubsystemClockSourceSelect, Control1Register::kSubsystemClockSourceSelect, Control1Register::kBackupClockSourceSelect, }; uint8_t select_value = Value(source); switch (clock) { case Clock::kMaster: [[fallthrough]]; case Clock::kSubsystemMaster: [[fallthrough]]; case Clock::kLowSpeedSubsystemMaster: break; case Clock::kAuxiliary: { SJ2_ASSERT_FATAL( select_value <= Value(Oscillator::kReference), "The auxiliary clock can only be driven by kLowFrequency, " "kVeryLowFrequency, or kReference. The system will default to " "using kReference"); break; } case Clock::kBackup: { switch (source) { case Oscillator::kLowFrequency: break; case Oscillator::kReference: { select_value = 0b1; break; } default: SJ2_ASSERT_FATAL(false, "The backup clock can only be driven by " "kLowFrequency or kReference."); return; } break; } default: { SJ2_ASSERT_FATAL( false, "clock must be one of the five primary clocks: kAuxiliary, " "kMaster, kSubsystemMaster, kLowSpeedSubsystemMaster, or " "kBackup."); return; } } Control1Register::Register() .Insert(select_value, kPrimaryClockSelectMasks[Value(clock)]) .Save(); } /// Configures the DCO clock to generate a desired target frequency. /// /// @see 6.2.8.3 DCO Ranges and Tuning in the MSP432P4xx Reference Manual. /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=386 /// /// @returns The DCO output frequency. units::frequency::hertz_t ConfigureDcoClock() const { const auto & dco_config = clock_configuration_.dco; const units::frequency::kilohertz_t kTargetFrequency = dco_config.frequency; // Configure DCO only if it is used as a clock source. if (dco_config.enabled) { // ======================================================================= // Step 1. Ensure the target frequency is valid. // ======================================================================= constexpr units::frequency::megahertz_t kMinimumDcoFrequency = 1_MHz; constexpr units::frequency::megahertz_t kMaximumDcoFrequency = 48_MHz; SJ2_ASSERT_FATAL( (kMinimumDcoFrequency <= kTargetFrequency) && (kTargetFrequency <= kMaximumDcoFrequency), "The desired frequency must be between 1 MHz and 48 MHz."); // ======================================================================= // Step 2. Determine the DCO tuning configuration values by finding the // DCO frequency range, DCO constant, and DCO calibration values // based on the desired target frequency. // ======================================================================= uint8_t dco_frequency_select = 0b000; float dco_constant = static_cast<float>(device_descriptors->DCOIR_CONSTK_RSEL04); int32_t dco_calibration = static_cast<int32_t>(device_descriptors->DCOIR_FCAL_RSEL04); if (kTargetFrequency >= 32_MHz) { // target frequency is 32 MHz to 48 MHz dco_frequency_select = 0b101; dco_constant = static_cast<float>(device_descriptors->DCOIR_CONSTK_RSEL5); dco_calibration = static_cast<int32_t>(device_descriptors->DCOIR_FCAL_RSEL5); } else if (kTargetFrequency >= 16_MHz) { // target frequency is 16 MHz to 32 MHz dco_frequency_select = 0b100; } else if (kTargetFrequency >= 8_MHz) { // target frequency is 8 MHz to 16 MHz dco_frequency_select = 0b011; } else if (kTargetFrequency >= 4_MHz) { // target frequency is 4 MHz to 8 MHz dco_frequency_select = 0b010; } else if (kTargetFrequency >= 2_MHz) { // target frequency is 2 MHz to 4 MHz dco_frequency_select = 0b001; } else { // target frequency is 1 MHz to 2 MHz with center frequency of 1.5 MHz // use the default initialized values } // ======================================================================= // Step 3. Calculate the signed 10-bit tuning value using Equation 6 from // https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=387 // ======================================================================= constexpr units::frequency::kilohertz_t kDcoCenterFrequencies[] = { 1500_kHz, 3_MHz, 6_MHz, 12_MHz, 24_MHz, 48_MHz }; const auto kCenterFrequency = kDcoCenterFrequencies[dco_frequency_select]; const float kFrequencyDifference = (kTargetFrequency - kCenterFrequency).to<float>(); const float kCalibration = (1.0f + dco_constant * static_cast<float>(768 - dco_calibration)); const float kDividend = kFrequencyDifference * kCalibration; const float kDivisor = kTargetFrequency.to<float>() * dco_constant; const int16_t kTuningValue = static_cast<int16_t>(kDividend / kDivisor); // ======================================================================= // Step 4. Configure the CSCTL0 register. // ======================================================================= UnlockClockSystemRegisters(); { Control0Register::Register() .Insert(kTuningValue, Control0Register::kTuningSelect) .Insert(dco_frequency_select, Control0Register::kFrequencySelect) .Set(Control0Register::kEnable) .Save(); } LockClockSystemRegisters(); } return kTargetFrequency; } /// Configures the reference clock to output either 32.768 kHz or 128 kHz. /// /// @see Table 6-8. CSCLKEN Register Description /// https://www.ti.com/lit/ug/slau356i/slau356i.pdf#page=401 /// /// @returns The running reference clock frequency. units::frequency::hertz_t ConfigureReferenceClock() const { const uint8_t kFrequencySelect = Value(clock_configuration_.reference.frequency); ClockEnableRegister::Register() .Insert(kFrequencySelect, ClockEnableRegister::kReferenceFrequencySelect) .Save(); return InternalOscillator::kReference[kFrequencySelect]; } /// Clock system configurations. ClockConfiguration_t & clock_configuration_; /// Array containing the clock rates of all the clock system peripherals. std::array<units::frequency::hertz_t, kClockPeripheralCount> clock_rates_ = { 0_Hz, // auxiliary clock 0_Hz, // master clock 0_Hz, // subsystem master clock 0_Hz, // low speed subsystem master clock 0_Hz, // backup clock ExternalOscillator::kLowFrequency, // low frequency clock InternalOscillator::kVeryLowFrequency, // very low frequency clock 0_Hz, // reference clock InternalOscillator::kModule, // module clock InternalOscillator::kSystem, // system clock }; }; } // namespace msp432p401r } // namespace sjsu
38.745333
80
0.635913
[ "object" ]
966e5b57c6664f8862767098e321673004d4ef71
1,980
cpp
C++
Task 1/Yet another shortest path/Solution.cpp
adityatiwari23/Hacktoberfest_2020
abc102b5a50852f91dcae17589a9b07d8fe08202
[ "MIT" ]
74
2021-09-22T06:29:40.000Z
2022-01-20T14:46:11.000Z
Task 1/Yet another shortest path/Solution.cpp
adityatiwari23/Hacktoberfest_2020
abc102b5a50852f91dcae17589a9b07d8fe08202
[ "MIT" ]
65
2020-10-02T11:03:42.000Z
2020-11-01T06:00:25.000Z
Task 1/Yet another shortest path/Solution.cpp
adityatiwari23/Hacktoberfest_2020
abc102b5a50852f91dcae17589a9b07d8fe08202
[ "MIT" ]
184
2020-10-02T10:53:53.000Z
2021-08-20T12:27:04.000Z
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; #define int ll typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; typedef vector<vi> vvi; typedef vector<vii> vvii; #define INF INT_MAX #define MOD 1000000007 #define all(x) x.begin(), x.end() void SOLVE1(int P, int K, int Q){ vi comp(P, -1); comp[0] = 0; int cc = 1; for(int u = 1; u < P; u++){ if(comp[u] != -1) continue; int tmp = u; while(true){ comp[tmp] = cc; tmp = (tmp*K)%P; if(tmp == u) break; } cc++; } vvi D(cc, vi(cc, INF)); for(int u = 0; u < cc; u++) D[u][u] = 0; for(int u = 0; u < P; u++){ int v = ((K*u)+1)%P; if(comp[u] != comp[v]) D[comp[u]][comp[v]] = 1; } for(int i = 0; i < cc; i++) for(int j = 0; j < cc; j++) for(int k = 0; k < cc; k++) D[j][k] = min(D[j][k], D[j][i]+D[i][k]); while(Q--){ int X, Y; cin >> X >> Y; cout << D[comp[X]][comp[Y]] << "\n"; } } void SOLVE2(int P, int K, int Q){ vi D(P, INF); D[0] = 0; deque<int> q; q.push_back(0); while(!q.empty()){ int u = q.front(); q.pop_front(); int v0 = (K*u)%P, v1 = (v0+1)%P; if(D[u]+0 < D[v0]){ D[v0] = D[u]+0; q.push_front(v0); } if(D[u]+1 < D[v1]){ D[v1] = D[u]+1; q.push_back(v1); } } while(Q--){ int X, Y; cin >> X >> Y; int ans = INF, tmp = X; while(true){ ans = min(ans, D[(Y-tmp+P)%P]); tmp = (tmp*K)%P; if(tmp == X) break; } cout << ans << "\n"; } } signed main(){ ios::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; while(T--){ int P, K, Q; cin >> P >> K >> Q; if(K%P == 0){ while(Q--){ int X, Y; cin >> X >> Y; if(X == Y) cout << 0 << "\n"; else cout << Y << "\n"; } continue; } ll R = 0, tmp = 1; while(true){ R++; tmp = (tmp*K)%P; if(tmp == 1) break; } if((P-1)/R <= 500) SOLVE1(P, K, Q); // Dijkstra else SOLVE2(P, K, Q); // 0-1 BFS } return 0; }
16.923077
49
0.484848
[ "vector" ]
96796b48a17dcfd70f659909b6b06b525f749a45
1,355
hpp
C++
app/Utility.hpp
lgruelas/Graph
079ec1d42a30e66c47ecbce1228b6581ca56cf34
[ "MIT" ]
7
2016-08-25T07:42:10.000Z
2019-10-30T09:05:29.000Z
app/Utility.hpp
lgruelas/Graph
079ec1d42a30e66c47ecbce1228b6581ca56cf34
[ "MIT" ]
1
2018-08-16T20:38:26.000Z
2018-08-16T22:11:32.000Z
app/Utility.hpp
lgruelas/Graph
079ec1d42a30e66c47ecbce1228b6581ca56cf34
[ "MIT" ]
10
2018-01-31T15:10:16.000Z
2018-08-16T18:15:20.000Z
#pragma once #include "Geometry/AllConvex.hpp" #include <SFML/Graphics.hpp> template <class T> T interpolate(real t, const T& from, const T& to) { return t*to + (1.0 - t)*from; } inline sf::Color interpolate(real t, const sf::Color& from, const sf::Color& to) { real r1 = from.r; real g1 = from.g; real b1 = from.b; real a1 = from.a; real r2 = to.r; real g2 = to.g; real b2 = to.b; real a2 = to.a; real r = interpolate(t, r1, r2); real g = interpolate(t, g1, g2); real b = interpolate(t, b1, b2); real a = interpolate(t, a1, a2); auto clamp = [](real* t, real a, real b) { if (*t < a) *t = a; if (*t > b) *t = b; }; clamp(&r, 1, 254); clamp(&g, 1, 254); clamp(&b, 1, 254); clamp(&a, 1, 254); auto ur = static_cast<unsigned char>(r); auto ug = static_cast<unsigned char>(g); auto ub = static_cast<unsigned char>(b); auto ua = static_cast<unsigned char>(a); return {ur, ug, ub, ua}; } template <class U, class T = U> inline std::vector<T> interpolate(real t, const std::vector<U>& A, const std::vector<U>& B) { assert(A.size() == B.size()); std::vector<T> result(A.size()); for (size_t i = 0; i < result.size(); ++i) { result[i] = interpolate(t, A[i], B[i]); } return result; }
21.854839
80
0.543911
[ "geometry", "vector" ]
967cea4038b04fc480e79b6477aebdf6ca14f1b9
1,426
cc
C++
riscv/src/PhysicalPageManagerRISCV.cc
jeremybennett/force-riscv
a5222a3b3fa8a0b9464204056ddca148f16b7e49
[ "Apache-2.0" ]
null
null
null
riscv/src/PhysicalPageManagerRISCV.cc
jeremybennett/force-riscv
a5222a3b3fa8a0b9464204056ddca148f16b7e49
[ "Apache-2.0" ]
null
null
null
riscv/src/PhysicalPageManagerRISCV.cc
jeremybennett/force-riscv
a5222a3b3fa8a0b9464204056ddca148f16b7e49
[ "Apache-2.0" ]
1
2020-06-17T09:37:45.000Z
2020-06-17T09:37:45.000Z
// // Copyright (C) [2020] Futurewei Technologies, Inc. // // FORCE-RISCV is 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 // // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR // FIT FOR A PARTICULAR PURPOSE. // See the License for the specific language governing permissions and // limitations under the License. // #include <PhysicalPageManagerRISCV.h> using namespace std; namespace Force { PhysicalPageManagerRISCV::PhysicalPageManagerRISCV(EMemBankType bankType) : PhysicalPageManager(bankType), mPteTypes() { mPteTypes.push_back(EPteType::P4K); mPteTypes.push_back(EPteType::P2M); mPteTypes.push_back(EPteType::P1G); mPteTypes.push_back(EPteType::P512G); } void PhysicalPageManagerRISCV::GetIncompatibleAttributes(const ConstraintSet* pMemAttrs, std::vector<EMemoryAttributeType>& memConstraintTypes) { // TODO Determine what implementation is needed here } void PhysicalPageManagerRISCV::ConvertMemoryAttributes(const ConstraintSet* pMemAttrs, std::vector<EMemoryAttributeType>& memConstraintTypes) { // TODO Determine what implementation is needed here } }
33.952381
145
0.760168
[ "vector" ]
968a37f222fa10ce93bbb7115a42a8107087b8e6
4,148
cpp
C++
Modules/Segmentation/Algorithms/mitkShowSegmentationAsSurface.cpp
samsmu/MITK
c93dce6dc38d8f4c961de4440e4dd113b9841c8c
[ "BSD-3-Clause" ]
5
2015-02-05T10:58:41.000Z
2019-04-17T15:04:07.000Z
Modules/Segmentation/Algorithms/mitkShowSegmentationAsSurface.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
141
2015-03-03T06:52:01.000Z
2020-12-10T07:28:14.000Z
Modules/Segmentation/Algorithms/mitkShowSegmentationAsSurface.cpp
kometa-dev/MITK
984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d
[ "BSD-3-Clause" ]
4
2015-02-19T06:48:13.000Z
2020-06-19T16:20:25.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkShowSegmentationAsSurface.h" #include "mitkManualSegmentationToSurfaceFilter.h" #include "mitkVtkRepresentationProperty.h" #include <mitkCoreObjectFactory.h> #include <mitkImageCast.h> #include <vtkPolyDataNormals.h> #include <itkConstantPadImageFilter.h> namespace mitk { ShowSegmentationAsSurface::ShowSegmentationAsSurface() { m_ProgressAccumulator = itk::ProgressAccumulator::New(); } ShowSegmentationAsSurface::~ShowSegmentationAsSurface() { } void ShowSegmentationAsSurface::GenerateData() { m_ProgressAccumulator->ResetProgress(); m_ProgressAccumulator->SetMiniPipelineFilter(this); m_ProgressAccumulator->UnregisterAllFilters(); // Pad image typedef itk::ConstantPadImageFilter<InputImageType, InputImageType> PadFilterType; typename PadFilterType::Pointer padFilter = PadFilterType::New(); m_ProgressAccumulator->RegisterInternalFilter(padFilter, .02f); InputImageType::SizeType paddingSize; paddingSize.Fill(1); padFilter->SetInput(m_Input); padFilter->SetPadBound(paddingSize); padFilter->SetConstant(0); padFilter->Update(); Image::Pointer mitkImage; CastToMitkImage<InputImageType>(padFilter->GetOutput(), mitkImage); // Move back by slice to adjust image position by padding mitk::Point3D point = mitkImage->GetGeometry()->GetOrigin(); auto spacing = mitkImage->GetGeometry()->GetSpacing(); auto directionMatrix = m_Input->GetDirection(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { point[i] -= spacing[i] * directionMatrix[i][j]; } } mitkImage->SetOrigin(point); ManualSegmentationToSurfaceFilter::Pointer surfaceFilter = ManualSegmentationToSurfaceFilter::New(); m_ProgressAccumulator->RegisterInternalFilter(surfaceFilter, .98f); surfaceFilter->SetInput(mitkImage); surfaceFilter->SetThreshold(.5f); //expects binary image with zeros and ones surfaceFilter->SetUseGaussianImageSmooth(m_Args.smooth); // apply gaussian to thresholded image ? surfaceFilter->SetSmooth(m_Args.smooth); if (m_Args.smooth) { surfaceFilter->InterpolationOn(); surfaceFilter->SetGaussianStandardDeviation(m_Args.gaussianSD); } surfaceFilter->SetMedianFilter3D(m_Args.applyMedian); // apply median to segmentation before marching cubes ? if (m_Args.applyMedian) { // Apply median to segmentation before marching cubes surfaceFilter->SetMedianKernelSize(m_Args.medianKernelSize, m_Args.medianKernelSize, m_Args.medianKernelSize); } //fix to avoid vtk warnings see bug #5390 if (mitkImage->GetDimension() > 3) { m_Args.decimateMesh = false; } if (m_Args.decimateMesh) { surfaceFilter->SetDecimate( ImageToSurfaceFilter::QuadricDecimation ); surfaceFilter->SetTargetReduction( m_Args.decimationRate ); } else { surfaceFilter->SetDecimate( ImageToSurfaceFilter::NoDecimation ); } surfaceFilter->UpdateLargestPossibleRegion(); // calculate normals for nicer display Surface::Pointer surf = surfaceFilter->GetOutput(); vtkPolyData* polyData = surf->GetVtkPolyData(); if (!polyData) { throw std::logic_error("Could not create polygon model"); } polyData->SetVerts(0); polyData->SetLines(0); if ( m_Args.smooth || m_Args.applyMedian || m_Args.decimateMesh) { vtkPolyDataNormals* normalsGen = vtkPolyDataNormals::New(); normalsGen->SetInputData( polyData ); normalsGen->Update(); m_Output = normalsGen->GetOutput(); normalsGen->Delete(); } else { m_Output = surf->GetVtkPolyData(); } m_ProgressAccumulator->SetMiniPipelineFilter(nullptr); m_ProgressAccumulator->UnregisterAllFilters(); UpdateProgress(1.); } } // namespace
30.057971
114
0.731437
[ "model" ]
968ecca775a194cd2b3335bc2fc7cb0babf95981
12,273
cpp
C++
c++2/Assign5/NIUString.cpp
Andrew-Slade/cplusplus-projects
e5c5ac610f51d139f5d097ea00ac136c6fe1c365
[ "MIT" ]
null
null
null
c++2/Assign5/NIUString.cpp
Andrew-Slade/cplusplus-projects
e5c5ac610f51d139f5d097ea00ac136c6fe1c365
[ "MIT" ]
null
null
null
c++2/Assign5/NIUString.cpp
Andrew-Slade/cplusplus-projects
e5c5ac610f51d139f5d097ea00ac136c6fe1c365
[ "MIT" ]
null
null
null
/************************************************ CSCI-241 -Assignment 5- Spring 2017 Programmer: Andrew Slade Z-ID: z1818810 Section: 4 TA: Dinesh Sandadi Date Due: 03/28/2017 Purpose:Contains methods for NIUString class and standalone functions. These manipulate data in a method similar to the standard string class. *************************************************/ #include "NIUString.h" #include <iostream> #include <cstring> using std::strlen; using std::cout; using std::ostream; /************************************************ NIUString(default constructor) Use: Constructs NIUString with default values. Parameters: none(default constructor) Returns: nothing(default constructor) ************************************************/ NIUString::NIUString() { sized = 0;//default values for size capacityd = 0;//default values for capacity stringPointer = nullptr; //default value for pointer to string } /************************************************ NIUString(parameter constructor) Use: Constructs NIUString with input values. Parameters: a const char*. Returns: nothing(constructor) ************************************************/ NIUString::NIUString(const char* other) { sized = strlen(other);//size from read in string capacityd = sized;//capacity from size if(capacityd == 0) { //null pointer if capacity is zero stringPointer = nullptr; } else { //else new dynamic memory and assign values stringPointer = new char[capacityd]; for(size_t c = 0; c < capacityd; c++) { //assign values to stringPointer from other stringPointer[c] = other[c]; } } } /************************************************ NIUString(copy constructor) Use: Constructs NIUString with input values. Parameters: a reference to a NIUString object. Returns: nothing(constructor) ************************************************/ NIUString::NIUString(const NIUString& other) { capacityd = other.capacityd;//capacity assigned from other's capacity sized = other.sized;//size from other's size if(capacityd == 0) { //if there is no capacity, assign nullpointer stringPointer = nullptr; } else { //if there is a capacity, allocate memory and write to it stringPointer = new char[capacityd]; for(size_t t = 0; t < capacityd; t++) { //assigns values to stringPointer from parameter other stringPointer[t] = other[t]; } } } /************************************************ ~NIUString Use: Destroys NIUString class and clears values. Parameters: none(destructor). Returns: nothing(destructor). ************************************************/ NIUString::~NIUString() { //call clear method clear(); } /************************************************ reserve Use: makes string capacity higher. Parameters: a size_t. Returns: none(void). ************************************************/ void NIUString::reserve(size_t n) { if(n < sized || n == capacityd) { /* if user input value is less than size or equal to current capacity, ignore */ return; } else { //otherwise set new capacity capacityd = n; char* temp;//temp holder for an array pointer if(capacityd == 0) { //if capacity is zero, nullpointer stringPointer = nullptr; } else { /* otherwise create new memory and copy contents into the temporary array then delete string and set pointer to temporary pointer */ temp = new char[capacityd]; for(size_t l = 0; l < capacityd; l++) { temp[l] = stringPointer[l]; } delete[] stringPointer; stringPointer = temp; } } return; } /************************************************ operator==(overload == operator) Use: Overloads == operator for comparing two NIUString objects. Parameters: a reference to a constant NIUString object. Returns: bool. ************************************************/ bool NIUString::operator==(const NIUString& rhs) const { bool booly;//temporary holder for a bool int county = 0;//temp variable if(sized == rhs.sized) { //if the size of the current object is equal to the right hand side for(size_t q = 0; q < rhs.capacityd; q++) { if(stringPointer[q] == rhs.stringPointer[q]) { //search through the array and if values are similar mark true booly = true; } else { //otherwise tally up values that are not similar county++; } } if(county > 0) { //if the tally is higher than zero, the strings are not similar booly = false; } } else { //if the strings are not the same size, they are not similar booly = false; } return booly; } /************************************************ operator==(overload == operator) Use: Overloads == operator for comparing a NIUString object and char array. Parameters: a const char*. Returns: bool. ************************************************/ bool NIUString::operator==(const char* rhs) const { bool bools;//temp holder for the returned bool int counter = 0;//temp variable for(size_t d = 0; d < strlen(rhs); d++) { if(stringPointer[d] == rhs[d]) { //search through the array and register values that are the same bools = true; /* overwrites bools each time, however, works for values that are all true */ } else { //otherwise tally up values that are not similar counter++; } if(counter > 0) { //if the tally is higher than zero, the strings are not similar bools = false; } } return bools; } /************************************************ operator=(overload = operator) Use: Overloads = operator for assigning to a NIUString object. Parameters: a refernce to a const NIUString object. Returns: reference to an NIUString object. ************************************************/ NIUString& NIUString::operator=(const NIUString& other) { bool boolo = false;//temp holder for bool if(this == &other) { //if self assignment, skip to end boolo = true; } else if(boolo == false) { //if no self assignment delete[] stringPointer;//delete dynamic memory sized = other.sized;//set size to the other object's size capacityd = other.capacityd;//set capacity to other's capacity if(other.capacityd == 0) { //if other's capacity is zero, pointer to string is nullpointer stringPointer = nullptr; } else { //otherwise allocate new dynamic memory and assign values stringPointer = new char[capacityd]; for(size_t zz = 0; zz < capacityd; zz++) { //assigns string's values from other's strings values stringPointer[zz] = other.stringPointer[zz]; } } } return *this; } /************************************************ operator=(overload = operator) Use: Overloads = operator for assigning to a NIUString object. Parameters: a const char*. Returns: reference to an NIUString object. ************************************************/ NIUString& NIUString::operator=(const char* other) { delete[] stringPointer;//delete dynamic memory sized = strlen(other);//set size to length of character array capacityd = sized;//set capacity equal to size if(strlen(other)== 0) { //if the length of the string is zero, nullpointer stringPointer = nullptr; } else { //otherwise, new dynamic memory and assign stringPointer = new char[capacityd]; for(size_t zz = 0; zz < capacityd; zz++) { //assign values to string from other string stringPointer[zz] = other[zz]; } } return *this; } /************************************************ capacity Use: Returns value for capacity(accessor). Parameters: none. Returns: size_t. ************************************************/ size_t NIUString::capacity() const { //return capacity value return capacityd; } /********************************************* size Use: Returns value for size(accessor). Parameters: none. Returns: size_t. ************************************************/ size_t NIUString::size() const { //return size value return sized; } /********************************************* empty Use: Checks if string is empty. Parameters: none. Returns: bool. ************************************************/ bool NIUString::empty() const { bool booled;//temp for bool if(sized == 0) { //if empty, set to true booled = true; } else { //otherwise set to false booled = false; } return booled; } /********************************************* clear Use: Defaults all variables and releases dynamic memory. Parameters: none. Returns: none(void). ************************************************/ void NIUString::clear() { sized = 0;//default capacityd = 0;//default delete[] stringPointer;//deallocate dynamic memory stringPointer = nullptr;//default return; } /********************************************* operator[](overload [] opeartor) Use: overloads [] operator. Parameters: a size_t. Returns: reference to a const char&. ************************************************/ const char& NIUString::operator[](size_t pos) const { //returns value at that position return stringPointer[pos]; } /********************************************* operator[] (overload [] operator) Use: Allows for writing to a specific value in the array. Parameters:a size_t. Returns: reference to a character. ************************************************/ char& NIUString::operator[](size_t pos) { //return value at position return stringPointer[pos]; } /********************************************* operator<<(overload << operator) Use: Overload stream operator. Parameters:a reference to an ostream object and a reference to a constant NIUString object. Returns: a reference to an ostream object. ************************************************/ ostream& operator<<(ostream& lhs, const NIUString& rhs) { for(size_t i = 0; i < rhs.sized; i++) { cout << rhs.stringPointer[i]; } return lhs; } /********************************************* operator==(overload == operator) Use: Overload relational operator. Parameters:a const char* and a reference to a constant NIUString object. Returns: a bool. ************************************************/ bool operator==(const char* lhs, const NIUString& rhs) { bool boold;//temp bool int count = 0;//temp count for(size_t a = 0; a < strlen(lhs); a++) { if(rhs.stringPointer[a] == lhs[a]) { //iterate through stringPointer and compare values //true if values are the same boold = true; //overwrites, but works for values that are all the same } else { //tallys up dissenting values count++; } if(count > 0) { //if there are more than zero dissenting values, sets bool to false boold = false; } } return boold; }
25.09816
79
0.503707
[ "object" ]
f7b61732c42aed0994990d9eb1dc78b0e22576d0
1,339
cpp
C++
UVA_ONLINE_JUDGE/WEEK_2/REC_2/PESKY_PALINDROMES.cpp
WarlonZeng/Big4-Hackerrank
90791d2df5fffea648dbef1dff56c1bc7062203e
[ "MIT" ]
1
2017-01-28T07:54:53.000Z
2017-01-28T07:54:53.000Z
UVA_ONLINE_JUDGE/WEEK_2/REC_2/PESKY_PALINDROMES.cpp
WarlonZeng/Big4-Hackerrank
90791d2df5fffea648dbef1dff56c1bc7062203e
[ "MIT" ]
null
null
null
UVA_ONLINE_JUDGE/WEEK_2/REC_2/PESKY_PALINDROMES.cpp
WarlonZeng/Big4-Hackerrank
90791d2df5fffea648dbef1dff56c1bc7062203e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <string.h> #include <cmath> #include <new> #include <vector> #include <ctime> #include <algorithm> #include <utility> #include <functional> #include <sstream> #include <list> #include <set> #include <unordered_set> #include <iterator> #include <ostream> #include <array> #include <forward_list> #include <stack> #include <queue> #include <map> #include <exception> #include <unordered_map> #include <cstdio> #include <cstdlib> #include <cctype> //#define M_PI 3.1415926535897932 using namespace std; bool palindrome(string& word) { int len = word.length(); int half = (len / 2); // half of the string for (int i = 0, j = len - 1; i <= half; i++, j--) { if (word[i] != word[j]) return false; } return true; } int main() { string input; string temp; int n; //vector<string> palis; map<string, int> palis; int len; // int j = 0; while (getline(cin, input)) { for (int i = 0; i < input.length(); i++) { for (int j = 1; (i + j) <= input.length(); j++) { // is always sum cuz of substr implementation... temp = input.substr(i, j); // cout << temp << endl; if (palindrome(temp)) { palis[temp] = 1; } } } n = palis.size(); cout << "The string '" << input << "' contains " << n << " palindromes.\n"; palis.clear(); } return 0; }
18.342466
101
0.613144
[ "vector" ]
f7b95e978bf27da18ea2492fbf49da0a7998dd78
727
hpp
C++
inc/MapParser.hpp
Xwilarg/RythmHero
a29558a47127e1ad29b3fc2d7fff0df6f844fbb4
[ "Apache-2.0" ]
null
null
null
inc/MapParser.hpp
Xwilarg/RythmHero
a29558a47127e1ad29b3fc2d7fff0df6f844fbb4
[ "Apache-2.0" ]
null
null
null
inc/MapParser.hpp
Xwilarg/RythmHero
a29558a47127e1ad29b3fc2d7fff0df6f844fbb4
[ "Apache-2.0" ]
null
null
null
#pragma once # include <fstream> # include <filesystem> # include <vector> # include "Beat.hpp" namespace rhythm { class MapParser final { public: static bool LoadFile(const std::filesystem::path& path) noexcept; static const std::string& GetAudioExtension() noexcept; static const std::vector<Beat> GetAllBeats() noexcept; private: static std::string GetFieldValue(const std::string& line) noexcept; static Beat GetBeatValue(const std::string &line) noexcept; enum ParsingType { FIELD, BEAT }; static std::string _audioExtension; // Extension of the music file static std::vector<Beat> _beats; }; }
25.068966
75
0.631362
[ "vector" ]
f7c90c0277aeefa4ffe5eb1b07ec0a7cc5aadb06
2,389
cpp
C++
src/ann.cpp
cshong0618/artificial_nnetwork
89a281f695e68206f87c3a2934451c5105811b40
[ "MIT" ]
null
null
null
src/ann.cpp
cshong0618/artificial_nnetwork
89a281f695e68206f87c3a2934451c5105811b40
[ "MIT" ]
1
2016-12-26T21:00:20.000Z
2017-11-04T18:49:50.000Z
src/ann.cpp
cshong0618/artificial_nnetwork
89a281f695e68206f87c3a2934451c5105811b40
[ "MIT" ]
null
null
null
#include "../include/ann.h" /* AddLayer Method. */ void ann::ANN::AddLayer() { t_layer l; nnetwork.push_back(l); } /* AddNode Method */ bool ann::ANN::AddNode(int layer) { if(layer >= 0 && layer < (int)nnetwork.size()) { t_weight n; nnetwork.at(layer).push_back(n); return true; } return false; } /* AddWeight Method. Used for controlled iterated initialization helper. */ bool ann::ANN::AddWeight(int layer, int node, const double& weight) { if(layer >= 0 && layer < (int)nnetwork.size()) { if(node >= 0 && node < (int)nnetwork.at(layer).size()) { nnetwork.at(layer).at(node).push_back(weight); return true; } } return false; } /* SetWeight Method. Used to append weight */ bool ann::ANN::SetWeight(int layer, int node, int n, const double& weight) { if(layer >= 0 && layer < (int)nnetwork.size()) { if(node >= 0 && node < (int)nnetwork.at(layer).size()) { if(n >= 0 && n < (int)nnetwork.at(layer).at(node).size()) { this->nnetwork.at(layer).at(node).at(n) = weight; return true; } } } return false; } void ann::ANN::SetRawNNetwork(const ann::network& nnetwork) { this->nnetwork = nnetwork; } void ann::ANN::SetRawNode(const std::vector<struct node>& input) { this->raw_node = input; } void ann::ANN::AddTrainingSet(const std::vector<double>& input, const std::vector<double>& output) { this->training_set[input] = output; } void ann::ANN::AddTrainingSet(const std::vector<node>& input, const std::vector<double>& output) { std::vector<double> temp; for(auto n : input) { temp.push_back(n.val); } this->AddTrainingSet(temp, output); } /* SetSigmoidFunction Used to set custom sigmoid function */ void ann::ANN::SetActivationFunction(std::function<double(const double& net)>f) { this->sigmoid_function = f; } double ann::ANN::ActivationValue(const double& net) const { return sigmoid_function(net); } void ann::ANN::SetErrorMargin(const double& error_margin) { this->error_margin = error_margin; } void ann::ANN::SetLearningRate(const double& learning_rate) { this->learning_rate = learning_rate; }
19.422764
79
0.588112
[ "vector" ]
f7d9d30a1130ed534ba8740d5dc473b52769720c
14,119
cpp
C++
src/metaspades/src/projects/cds_subgraphs/main.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
null
null
null
src/metaspades/src/projects/cds_subgraphs/main.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
null
null
null
src/metaspades/src/projects/cds_subgraphs/main.cpp
STRIDES-Codes/Exploring-the-Microbiome-
bd29c8c74d8f40a58b63db28815acb4081f20d6b
[ "MIT" ]
2
2021-06-05T07:40:20.000Z
2021-06-05T08:02:58.000Z
//*************************************************************************** //* Copyright (c) 2018 Saint Petersburg State University //* Copyright (c) 2019 University of Warwick //* All Rights Reserved //* See file LICENSE for details. //*************************************************************************** #include "stop_condon_finder.hpp" #include "subgraph_extraction.hpp" #include "io/reads/file_reader.hpp" #include "toolchain/edge_label_helper.hpp" #include "toolchain/utils.hpp" #include "toolchain/subgraph_utils.hpp" #include "utils/segfault_handler.hpp" #include "version.hpp" #include <clipp/clipp.h> #include <string> #include <set> #include <numeric> #include <sys/types.h> using namespace debruijn_graph; namespace cds_subgraphs { struct PartialGeneInfo { size_t unitig_id; Range r; std::string gene_id; bool strand; }; inline std::istream &operator>>(std::istream &is, PartialGeneInfo &pgi) { is >> pgi.unitig_id; is >> pgi.r.start_pos; is >> pgi.r.end_pos; is >> pgi.gene_id; std::string strand_symbol; is >> strand_symbol; if (strand_symbol == "+") pgi.strand = true; else if (strand_symbol == "-") pgi.strand = false; else CHECK_FATAL_ERROR(false, "Unsupported strand symbol"); return is; } inline std::ostream &operator<<(std::ostream &os, const PartialGeneInfo &pgi) { os << "Unitig id: " << pgi.unitig_id << "; "; os << "Range: [" << pgi.r.start_pos << ", " << pgi.r.end_pos << "]; "; os << "Gene id:" << pgi.gene_id << "; "; os << "Strand: " << (pgi.strand ? "+" : "-"); return os; } static Range ConjugateRange(const Graph &g, EdgeId e, const Range &r) { return Range(g.length(e) - r.end_pos, g.length(e) - r.start_pos); } using GeneInitSeq = std::multimap<std::string, std::string>; static GeneInitSeq PredictionsFromDescFile(const Graph &g, const omnigraph::GraphElementFinder<Graph> &element_finder, const std::string &desc_file) { fs::CheckFileExistenceFATAL(desc_file); std::ifstream descs(desc_file); std::string l; PartialGeneInfo info; size_t i = 1; GeneInitSeq starting_seqs; while (std::getline(descs, l)) { std::istringstream ss(l); ss >> info; INFO("Gene prediction #" << i << ": " << info); EdgeId e = element_finder.ReturnEdgeId(info.unitig_id); VERIFY(e != EdgeId()); Range r = info.r; //exclusive right position r.end_pos += 1; //to 0-based coordinates r.shift(-1); VERIFY(r.size() > g.k()); //to k+1-mer coordinates // r.end_pos -= g.k(); if (!info.strand) { r = ConjugateRange(g, e, r); e = g.conjugate(e); } starting_seqs.insert(make_pair(info.gene_id, g.EdgeNucls(e).Subseq(r.start_pos, r.end_pos).str())); ++i; } return starting_seqs; } std::unordered_map<std::string, size_t> CDSLengthsFromFile(const std::string &fn) { INFO("Parsing estimated CDS lengths from " << fn); fs::CheckFileExistenceFATAL(fn); std::unordered_map<std::string, size_t> answer; std::ifstream in(fn); std::string l; std::string gene_id; double est_len; while (std::getline(in, l)) { std::istringstream ss(l); ss >> gene_id; ss >> est_len; answer[gene_id] = RoundedProduct(3, est_len); } return answer; } static std::string GeneNameFromFasta(const std::string &header) { std::stringstream ss(header); std::string s; ss >> s; ss >> s; return s; } static GeneInitSeq PredictionsFromFastaFile(const std::string &fasta_fn) { fs::CheckFileExistenceFATAL(fasta_fn); io::FileReadStream gene_frags(fasta_fn); io::SingleRead gene_frag; size_t i = 1; GeneInitSeq starting_seqs; while (!gene_frags.eof()) { gene_frags >> gene_frag; INFO("Gene prediction #" << i << ": " << gene_frag.name()); starting_seqs.insert(make_pair(GeneNameFromFasta(gene_frag.name()), gene_frag.GetSequenceString())); ++i; } return starting_seqs; } static void WriteComponent(const omnigraph::GraphComponent<Graph> &component, const std::string &prefix, const std::set<GraphPos> &stop_codon_poss, const io::EdgeNamingF<Graph> &naming_f) { const auto &g = component.g(); toolchain::WriteComponentWithDeadends(component, prefix, naming_f); INFO("Writing potential stop-codon positions to " << prefix << ".stops") std::ofstream stop_codon_os(prefix + ".stops"); io::CanonicalEdgeHelper<Graph> canonical_helper(g, naming_f); //1-based coordinate gives the start of the stop-codon for (GraphPos gpos : stop_codon_poss) { if (component.edges().count(gpos.first)) { stop_codon_os << canonical_helper.EdgeOrientationString(gpos.first, "\t") << "\t" << (gpos.second + g.k() - 2) << "\n"; } else { WARN("Earlier detected stop codon " << naming_f(g, gpos.first) << " " << gpos.second << " is outside the component"); } } } void ExtractCDSSubgraphs(const GraphPack &gp, const GeneInitSeq &starting_seqs, const std::unordered_map<std::string, size_t> &cds_len_ests, const io::EdgeNamingF<Graph> &edge_naming_f, const std::string &out_folder) { const auto &graph = gp.get<Graph>(); //fixme rename PartialGenePathProcessor partial_path_processor(graph, edge_naming_f); auto mapper = MapperInstance(gp); CDSSubgraphExtractor subgraph_extractor(graph, *mapper, partial_path_processor); INFO("Searching relevant subgraphs in parallel for all partial predictions"); for (const auto &gene_id : utils::key_set(starting_seqs)) { INFO("Processing gene " << gene_id); INFO("Subgraphs extracted for all " << starting_seqs.count(gene_id) << " of its partial predictions will be united"); std::set<EdgeId> edges; std::set<GraphPos> stop_codon_poss; for (const std::string &s : utils::get_all(starting_seqs, gene_id)) { auto gc = subgraph_extractor.ProcessPartialCDS(s, utils::get(cds_len_ests, gene_id), &stop_codon_poss); //TODO remove INFO("'Closing' gathered component"); toolchain::ComponentExpander expander(graph); gc = expander.Expand(gc); utils::insert_all(edges, gc.edges()); } toolchain::ComponentExpander expander(graph); auto component = expander.Expand(omnigraph::GraphComponent<Graph>::FromEdges(graph, edges.begin(), edges.end(), /*add conjugate*/true)); if (component.e_size() > 0) { WriteComponent(component, out_folder + gene_id, stop_codon_poss, edge_naming_f); } else { INFO("Couldn't find a non-trivial component for gene " << gene_id); } } } void ParallelExtractCDSSubgraphs(const GraphPack &gp, const GeneInitSeq &starting_seqs, const std::unordered_map<std::string, size_t> &cds_len_ests, const io::EdgeNamingF<Graph> &edge_naming_f, const std::string &out_folder) { const auto &graph = gp.get<Graph>(); //fixme rename PartialGenePathProcessor partial_path_processor(graph, edge_naming_f); auto mapper = MapperInstance(gp); CDSSubgraphExtractor subgraph_extractor(graph, *mapper, partial_path_processor); INFO("Searching relevant subgraphs in parallel for all partial predictions"); std::vector<std::string> flattened_ids; std::vector<std::string> flattened_part_genes; for (const auto &id_part : starting_seqs) { flattened_ids.push_back(id_part.first); flattened_part_genes.push_back(id_part.second); } size_t n = flattened_ids.size(); std::vector<std::set<EdgeId>> flattened_relevant_edges(n); std::vector<std::set<GraphPos>> flattened_stop_poss(n); #pragma omp parallel for schedule(guided) for (size_t i = 0; i < n; ++i) { auto gc = subgraph_extractor.ProcessPartialCDS(flattened_part_genes[i], utils::get(cds_len_ests, flattened_ids[i]), &flattened_stop_poss[i]); //TODO remove INFO("'Closing' gathered component"); toolchain::ComponentExpander expander(graph); gc = expander.Expand(gc); flattened_relevant_edges[i] = subgraph_extractor.ProcessPartialCDS(flattened_part_genes[i], utils::get(cds_len_ests, flattened_ids[i]), &flattened_stop_poss[i]).edges(); } INFO("Done searching subgraphs"); std::set<EdgeId> edges; std::set<GraphPos> stop_codon_poss; for (size_t i = 0; i < n; ++i) { const std::string &gene_id = flattened_ids[i]; utils::insert_all(edges, flattened_relevant_edges[i]); utils::insert_all(stop_codon_poss, flattened_stop_poss[i]); if (i == n - 1 || flattened_ids[i + 1] != gene_id) { toolchain::ComponentExpander expander(graph); auto component = expander.Expand(omnigraph::GraphComponent<Graph>::FromEdges(graph, edges.begin(), edges.end(), /*add conjugate*/true)); if (component.e_size() > 0) { WriteComponent(component, out_folder + gene_id, stop_codon_poss, edge_naming_f); } else { INFO("Couldn't find a non-trivial component for gene " << gene_id); } edges.clear(); stop_codon_poss.clear(); } } } } struct gcfg { gcfg() : k(0), nthreads(omp_get_max_threads() / 2 + 1) {} unsigned k; std::string graph; std::string tmpdir; std::string outdir; std::string genes_desc; std::string genes_seq; std::string cds_len_fn; unsigned nthreads; }; static void process_cmdline(int argc, char **argv, gcfg &cfg) { using namespace clipp; auto cli = ( (required("-o", "--output-folder") & value("dir", cfg.outdir)) % "output folder to use for GFA files", one_of((option("--part-desc") & value("file", cfg.genes_desc)) % "file with partial genes description (.gff)", (option("--part-seq") & value("file", cfg.genes_seq)) % "file with partial genes sequences (.fasta)"), (required("--graph") & value("graph", cfg.graph)) % "In GFA (ending with .gfa) or prefix to SPAdes graph pack", (required("--cds-len-est") & value("file", cfg.cds_len_fn)) % "file with cds length estimamtes", (required("-k") & integer("value", cfg.k)) % "k-mer length to use", (option("-t", "--threads") & integer("value", cfg.nthreads)) % "# of threads to use (default: max_threads / 2)", (option("--tmpdir") & value("dir", cfg.tmpdir)) % "scratch directory to use (default: <outdir>/tmp)" ); auto result = parse(argc, argv, cli); if (!result) { std::cout << make_man_page(cli, argv[0]); exit(1); } } int main(int argc, char** argv) { utils::segfault_handler sh; gcfg cfg; process_cmdline(argc, argv, cfg); toolchain::create_console_logger(/*logging::L_TRACE*/); START_BANNER("Extracting relevant subgraphs for (partial) predicted CDS"); try { unsigned nthreads = cfg.nthreads; unsigned k = cfg.k; std::string out_folder = cfg.outdir + "/"; fs::make_dirs(out_folder); INFO("K-mer length set to " << k); nthreads = std::min(nthreads, (unsigned) omp_get_max_threads()); // Inform OpenMP runtime about this :) omp_set_num_threads((int) nthreads); INFO("# of threads to use: " << nthreads); std::string tmpdir = cfg.tmpdir.empty() ? out_folder + "tmp" : cfg.tmpdir; fs::make_dirs(tmpdir); debruijn_graph::GraphPack gp(k, tmpdir, 0); const auto &graph = gp.get<Graph>(); omnigraph::GraphElementFinder<Graph> element_finder(graph); INFO("Loading de Bruijn graph from " << cfg.graph); gp.get_mutable<KmerMapper<Graph>>().Attach(); // TODO unnecessary io::EdgeLabelHelper<Graph> label_helper(element_finder, toolchain::LoadGraph(gp, cfg.graph)); gp.EnsureBasicMapping(); VERIFY(cfg.genes_desc.empty() != cfg.genes_seq.empty()); auto starting_seqs = cfg.genes_desc.empty() ? cds_subgraphs::PredictionsFromFastaFile(cfg.genes_seq) : cds_subgraphs::PredictionsFromDescFile(graph, element_finder, cfg.genes_desc); auto cds_len_ests = cds_subgraphs::CDSLengthsFromFile(cfg.cds_len_fn); static const bool parallel = false; if (parallel) { //Experimental parallel mode cds_subgraphs::ParallelExtractCDSSubgraphs(gp, starting_seqs, cds_len_ests, label_helper.edge_naming_f(), out_folder); } else { cds_subgraphs::ExtractCDSSubgraphs(gp, starting_seqs, cds_len_ests, label_helper.edge_naming_f(), out_folder); } INFO("Done"); } catch (const std::string &s) { std::cerr << s << std::endl; return EINTR; } catch (const std::exception &e) { std::cerr << "ERROR: " << e.what() << std::endl; return EINTR; } }
38.262873
132
0.58269
[ "vector" ]
f7df7105d586400adca5a89dbcc2aa96597e02c0
3,009
cpp
C++
platform/windows/Corona.Component.Library/CoronaLabs/Corona/WinRT/Interop/Graphics/HorizontalAlignment.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
1,968
2018-12-30T21:14:22.000Z
2022-03-31T23:48:16.000Z
platform/windows/Corona.Component.Library/CoronaLabs/Corona/WinRT/Interop/Graphics/HorizontalAlignment.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
303
2019-01-02T19:36:43.000Z
2022-03-31T23:52:45.000Z
platform/windows/Corona.Component.Library/CoronaLabs/Corona/WinRT/Interop/Graphics/HorizontalAlignment.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
254
2019-01-02T19:05:52.000Z
2022-03-30T06:32:28.000Z
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "HorizontalAlignment.h" #include "CoronaLabs\WinRT\NativeStringServices.h" namespace CoronaLabs { namespace Corona { namespace WinRT { namespace Interop { namespace Graphics { #pragma region Pre-allocated HorizontalAlignment Objects const HorizontalAlignment^ HorizontalAlignment::kLeft = ref new HorizontalAlignment("left"); const HorizontalAlignment^ HorizontalAlignment::kCenter = ref new HorizontalAlignment("center"); const HorizontalAlignment^ HorizontalAlignment::kRight = ref new HorizontalAlignment("right"); #pragma endregion #pragma region Consructors/Destructors HorizontalAlignment::HorizontalAlignment(Platform::String^ coronaStringId) : fCoronaStringId(coronaStringId) { // Validate. if (!coronaStringId) { throw ref new Platform::NullReferenceException("coronaStringId"); } // Add this instance to the collection. // Used to fetch a pre-existing instance via this class' static From() functions. HorizontalAlignment::MutableCollection->Append(this); } #pragma endregion #pragma region Public Methods/Properties HorizontalAlignment^ HorizontalAlignment::Left::get() { return const_cast<HorizontalAlignment^>(kLeft); } HorizontalAlignment^ HorizontalAlignment::Center::get() { return const_cast<HorizontalAlignment^>(kCenter); } HorizontalAlignment^ HorizontalAlignment::Right::get() { return const_cast<HorizontalAlignment^>(kRight); } Platform::String^ HorizontalAlignment::CoronaStringId::get() { return fCoronaStringId; } Platform::String^ HorizontalAlignment::ToString() { return fCoronaStringId; } Windows::Foundation::Collections::IIterable<HorizontalAlignment^>^ HorizontalAlignment::Collection::get() { return HorizontalAlignment::MutableCollection->GetView(); } HorizontalAlignment^ HorizontalAlignment::FromCoronaStringId(Platform::String^ stringId) { if (stringId && (stringId->Length() > 0)) { for (auto&& item : HorizontalAlignment::MutableCollection) { if (item->fCoronaStringId->Equals(stringId)) { return item; } } } return nullptr; } #pragma endregion #pragma region Internal Functions HorizontalAlignment^ HorizontalAlignment::FromCoronaStringId(const char *stringId) { return FromCoronaStringId(CoronaLabs::WinRT::NativeStringServices::Utf16FromUtf8(stringId)); } #pragma endregion #pragma region Private Methods/Properties Platform::Collections::Vector<HorizontalAlignment^>^ HorizontalAlignment::MutableCollection::get() { static Platform::Collections::Vector<HorizontalAlignment^> sCollection; return %sCollection; } #pragma endregion } } } } } // namespace CoronaLabs::Corona::WinRT::Interop::Graphics
26.628319
105
0.740778
[ "vector" ]
f7ee8d1daaf0f586167e9e3697a32e0d83a80d3a
7,945
cpp
C++
ares/fc/apu/apu.cpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/fc/apu/apu.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/fc/apu/apu.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
#include <fc/fc.hpp> namespace ares::Famicom { APU apu; #include "envelope.cpp" #include "sweep.cpp" #include "pulse.cpp" #include "triangle.cpp" #include "noise.cpp" #include "dmc.cpp" #include "serialization.cpp" auto APU::load(Node::Object parent) -> void { node = parent->append<Node::Component>("APU"); stream = node->append<Node::Stream>("PSG"); stream->setChannels(1); stream->setFrequency(uint(system.frequency() + 0.5) / rate()); stream->addHighPassFilter( 90.0, 1); stream->addHighPassFilter( 440.0, 1); stream->addLowPassFilter (14000.0, 1); for(uint amp : range(32)) { if(amp == 0) { pulseDAC[amp] = 0; } else { pulseDAC[amp] = 16384.0 * 95.88 / (8128.0 / amp + 100.0); } } for(uint dmcAmp : range(128)) { for(uint triangleAmp : range(16)) { for(uint noiseAmp : range(16)) { if(dmcAmp == 0 && triangleAmp == 0 && noiseAmp == 0) { dmcTriangleNoiseDAC[dmcAmp][triangleAmp][noiseAmp] = 0; } else { dmcTriangleNoiseDAC[dmcAmp][triangleAmp][noiseAmp] = 16384.0 * 159.79 / (100.0 + 1.0 / (triangleAmp / 8227.0 + noiseAmp / 12241.0 + dmcAmp / 22638.0)); } } } } } auto APU::unload() -> void { node = {}; stream = {}; } auto APU::main() -> void { uint pulseOutput = pulse1.clock() + pulse2.clock(); uint triangleOutput = triangle.clock(); uint noiseOutput = noise.clock(); uint dmcOutput = dmc.clock(); clockFrameCounterDivider(); int output = 0; output += pulseDAC[pulseOutput]; output += dmcTriangleNoiseDAC[dmcOutput][triangleOutput][noiseOutput]; stream->sample(sclamp<16>(output) / 32768.0); tick(); } auto APU::tick() -> void { Thread::step(rate()); Thread::synchronize(cpu); } auto APU::setIRQ() -> void { cpu.apuLine(frame.irqPending | dmc.irqPending); } auto APU::power(bool reset) -> void { Thread::create(system.frequency(), {&APU::main, this}); pulse1.power(); pulse2.power(); triangle.power(); noise.power(); dmc.power(); frame.irqPending = 0; frame.mode = 0; frame.counter = 0; frame.divider = 1; enabledChannels = 0; setIRQ(); } auto APU::readIO(uint16 address) -> uint8 { uint8 data = cpu.mdr(); switch(address) { case 0x4015: { data.bit(0) = (bool)pulse1.lengthCounter; data.bit(1) = (bool)pulse2.lengthCounter; data.bit(2) = (bool)triangle.lengthCounter; data.bit(3) = (bool)noise.lengthCounter; data.bit(4) = (bool)dmc.lengthCounter; data.bit(5) = 0; data.bit(6) = frame.irqPending; data.bit(7) = dmc.irqPending; frame.irqPending = false; setIRQ(); return data; } } return data; } auto APU::writeIO(uint16 address, uint8 data) -> void { switch(address) { case 0x4000: { pulse1.envelope.speed = data.bit(0,3); pulse1.envelope.useSpeedAsVolume = data.bit(4); pulse1.envelope.loopMode = data.bit(5); pulse1.duty = data.bit(6,7); return; } case 0x4001: { pulse1.sweep.shift = data.bit(0,2); pulse1.sweep.decrement = data.bit(3); pulse1.sweep.period = data.bit(4,6); pulse1.sweep.enable = data.bit(7); pulse1.sweep.reload = true; return; } case 0x4002: { pulse1.period.bit(0,7) = data.bit(0,7); pulse1.sweep.pulsePeriod.bit(0,7) = data.bit(0,7); return; } case 0x4003: { pulse1.period.bit(8,10) = data.bit(0,2); pulse1.sweep.pulsePeriod.bit(8,10) = data.bit(0,2); pulse1.dutyCounter = 0; pulse1.envelope.reloadDecay = true; if(enabledChannels.bit(0)) { pulse1.lengthCounter = lengthCounterTable[data.bit(3,7)]; } return; } case 0x4004: { pulse2.envelope.speed = data.bit(0,3); pulse2.envelope.useSpeedAsVolume = data.bit(4); pulse2.envelope.loopMode = data.bit(5); pulse2.duty = data.bit(6,7); return; } case 0x4005: { pulse2.sweep.shift = data.bit(0,2); pulse2.sweep.decrement = data.bit(3); pulse2.sweep.period = data.bit(4,6); pulse2.sweep.enable = data.bit(7); pulse2.sweep.reload = true; return; } case 0x4006: { pulse2.period.bit(0,7) = data.bit(0,7); pulse2.sweep.pulsePeriod.bit(0,7) = data.bit(0,7); return; } case 0x4007: { pulse2.period.bit(8,10) = data.bit(0,2); pulse2.sweep.pulsePeriod.bit(8,10) = data.bit(0,2); pulse2.dutyCounter = 0; pulse2.envelope.reloadDecay = true; if(enabledChannels.bit(1)) { pulse2.lengthCounter = lengthCounterTable[data.bit(3,7)]; } return; } case 0x4008: { triangle.linearLength = data.bit(0,6); triangle.haltLengthCounter = data.bit(7); return; } case 0x400a: { triangle.period.bit(0,7) = data.bit(0,7); return; } case 0x400b: { triangle.period.bit(8,10) = data.bit(0,2); triangle.reloadLinear = true; if(enabledChannels.bit(2)) { triangle.lengthCounter = lengthCounterTable[data.bit(3,7)]; } return; } case 0x400c: { noise.envelope.speed = data.bit(0,3); noise.envelope.useSpeedAsVolume = data.bit(4); noise.envelope.loopMode = data.bit(5); return; } case 0x400e: { noise.period = data.bit(0,3); noise.shortMode = data.bit(7); return; } case 0x400f: { noise.envelope.reloadDecay = true; if(enabledChannels.bit(3)) { noise.lengthCounter = lengthCounterTable[data.bit(3,7)]; } return; } case 0x4010: { dmc.period = data.bit(0,3); dmc.loopMode = data.bit(6); dmc.irqEnable = data.bit(7); dmc.irqPending = dmc.irqPending && dmc.irqEnable && !dmc.loopMode; setIRQ(); return; } case 0x4011: { dmc.dacLatch = data.bit(0,6); return; } case 0x4012: { dmc.addressLatch = data; return; } case 0x4013: { dmc.lengthLatch = data; return; } case 0x4015: { if(data.bit(0) == 0) pulse1.lengthCounter = 0; if(data.bit(1) == 0) pulse2.lengthCounter = 0; if(data.bit(2) == 0) triangle.lengthCounter = 0; if(data.bit(3) == 0) noise.lengthCounter = 0; if(data.bit(4) == 0) dmc.stop(); if(data.bit(4) == 1) dmc.start(); dmc.irqPending = false; setIRQ(); enabledChannels = data.bit(0,4); return; } case 0x4017: { frame.mode = data.bit(6,7); frame.counter = 0; if(frame.mode.bit(1)) { clockFrameCounter(); } if(frame.mode.bit(0)) { frame.irqPending = false; setIRQ(); } frame.divider = FrameCounter::NtscPeriod; return; } } } auto APU::clockFrameCounter() -> void { frame.counter++; if(frame.counter.bit(0)) { pulse1.clockLength(); pulse1.sweep.clock(0); pulse2.clockLength(); pulse2.sweep.clock(1); triangle.clockLength(); noise.clockLength(); } pulse1.envelope.clock(); pulse2.envelope.clock(); triangle.clockLinearLength(); noise.envelope.clock(); if(frame.counter == 0) { if(frame.mode.bit(1)) { frame.divider += FrameCounter::NtscPeriod; } if(frame.mode == 0) { frame.irqPending = true; setIRQ(); } } } auto APU::clockFrameCounterDivider() -> void { frame.divider -= 2; if(frame.divider <= 0) { clockFrameCounter(); frame.divider += FrameCounter::NtscPeriod; } } const uint8 APU::lengthCounterTable[32] = { 0x0a, 0xfe, 0x14, 0x02, 0x28, 0x04, 0x50, 0x06, 0xa0, 0x08, 0x3c, 0x0a, 0x0e, 0x0c, 0x1a, 0x0e, 0x0c, 0x10, 0x18, 0x12, 0x30, 0x14, 0x60, 0x16, 0xc0, 0x18, 0x48, 0x1a, 0x10, 0x1c, 0x20, 0x1e, }; const uint16 APU::noisePeriodTableNTSC[16] = { 4, 8, 16, 32, 64, 96, 128, 160, 202, 254, 380, 508, 762, 1016, 2034, 4068, }; const uint16 APU::noisePeriodTablePAL[16] = { 4, 8, 14, 30, 60, 88, 118, 148, 188, 236, 354, 472, 708, 944, 1890, 3778, }; const uint16 APU::dmcPeriodTableNTSC[16] = { 428, 380, 340, 320, 286, 254, 226, 214, 190, 160, 142, 128, 106, 84, 72, 54, }; const uint16 APU::dmcPeriodTablePAL[16] = { 398, 354, 316, 298, 276, 236, 210, 198, 176, 148, 132, 118, 98, 78, 66, 50, }; }
22.507082
110
0.611957
[ "object" ]
f7f441fc52aaa1f22ba890fc4575a49024464a54
370
hpp
C++
impl/gamelib/experience_spawner_interface.hpp
runvs/Alakajam14
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
[ "CC0-1.0" ]
null
null
null
impl/gamelib/experience_spawner_interface.hpp
runvs/Alakajam14
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
[ "CC0-1.0" ]
null
null
null
impl/gamelib/experience_spawner_interface.hpp
runvs/Alakajam14
28ad5839dae9d26782f22f7d18e2dff42f4c0d1f
[ "CC0-1.0" ]
null
null
null
#ifndef ALAKAJAM14_EXPERIENCE_SPAWNER_INTERFACE_HPP #define ALAKAJAM14_EXPERIENCE_SPAWNER_INTERFACE_HPP #include "vector.hpp" class ExperienceSpawnerInterface { public: virtual ~ExperienceSpawnerInterface() = default; virtual void spawnExperience(int amount, jt::Vector2f const& pos, bool single) = 0; }; #endif // ALAKAJAM14_EXPERIENCE_SPAWNER_INTERFACE_HPP
28.461538
87
0.818919
[ "vector" ]
7900adacc2fb1bc54f3ed4d80bd2b535fa27c597
5,208
hpp
C++
proton-c/bindings/cpp/include/proton/facade.hpp
Azure/qpid-proton
fa784b1f3c4f3dbd6b143d5cceda10bf76da23a5
[ "Apache-2.0" ]
2
2020-04-28T13:33:06.000Z
2020-06-01T14:51:05.000Z
proton-c/bindings/cpp/include/proton/facade.hpp
Azure/qpid-proton
fa784b1f3c4f3dbd6b143d5cceda10bf76da23a5
[ "Apache-2.0" ]
null
null
null
proton-c/bindings/cpp/include/proton/facade.hpp
Azure/qpid-proton
fa784b1f3c4f3dbd6b143d5cceda10bf76da23a5
[ "Apache-2.0" ]
4
2015-10-17T20:44:45.000Z
2021-06-08T19:00:56.000Z
#ifndef PROTON_CPP_FACADE_H #define PROTON_CPP_FACADE_H /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ /*! \page c-and-cpp C and memory management. *\brief * * The C++ API is a very thin wrapper over the C API. The C API consists of a * set of `struct` types and associated C functions. For each there is a a C++ * `facade` that provides C++ member functions to call the corresponding C * functions on the underlying C struct. Facade classes derive from the * `proton::facade` template. * * The facade class occupies no additional memory. The C+ facade pointer points * directly to the underlying C++ struct, calling C++ member functions corresponds * directly to calling the C function. * * If you want to mix C and C++ code (which should be done carefully!) you can * cast between a facade pointer and a C struct pointer with `proton::pn_cast` * and `foo::cast()` where `foo` is some C++ facade class. * * Deleting a facade object calls the appropriate `pn_foo_free` function or * `pn_decref` as appropriate. * * Some proton structs are reference counted, the facade classes for these * derive from the `proton::counted_facade` template. Most proton functions that * return facade objects return a reference to an object that is owned by the * called object. Such references are only valid in a limited scope (for example * in an event handler function.) To keep a reference outside that scope, call * the `ptr()` member function. This returns a `proton::counted_ptr`, which you * can convert safely to `std::shared_ptr`, `std::unique_ptr`, * `boost::shared_ptr`, or `boost::intrusive_ptr`. */ /**@file * Classes and templates used by object facades. */ #include "proton/export.hpp" #include "counted_ptr.hpp" namespace proton { ///@cond INTERNAL struct empty_base {}; ///@endcond /** * Base class for C++ facades of proton C struct types. * * @see \ref c-and-cpp */ template <class P, class T, class Base=empty_base> class facade : public Base { public: /// The underlying C struct type. typedef P pn_type; /// Cast the C struct pointer to a C++ facade pointer. static T* cast(P* p) { return reinterpret_cast<T*>(p); } private: facade(); facade(const facade&); facade& operator=(const facade&); void operator delete(void* p); }; /** Cast a facade type to the C struct type. * Allow casting away const, the underlying pn structs have not constness. */ template <class T> typename T::pn_type* pn_cast(const T* p) { return reinterpret_cast<typename T::pn_type*>(const_cast<T*>(p)); } /** Cast a counted pointer to a facade type to the C struct type. * Allow casting away const, the underlying pn structs have not constness. */ template <class T> typename T::pn_type* pn_cast(const counted_ptr<T>& p) { return reinterpret_cast<typename T::pn_type*>(const_cast<T*>(p.get())); } /** * Some proton C structs are reference counted. The C++ facade for such structs can be * converted to any of the following smart pointers: std::shared_ptr, std::unique_ptr, * boost::shared_ptr, boost::intrusive_ptr. * * unique_ptr takes ownership of a single *reference* not the underlying struct, * so it is safe to have multiple unique_ptr to the same facade object or to mix * unique_ptr with shared_ptr etc. * * Deleting a counted_facade subclass actually calls `pn_decref` to remove a reference. */ template <class P, class T, class Base=empty_base> class counted_facade : public facade<P, T, Base> { public: /// Deleting a counted_facade actually calls `pn_decref` to remove a reference. void operator delete(void* p) { decref(p); } /** Get a reference-counted pointer to the underlying object. It can be * converted safely to `std::shared_ptr`, `std::unique_ptr`, * `boost::shared_ptr`, or `boost::intrusive_ptr`. */ counted_ptr<T> ptr() { return counted_ptr<T>(static_cast<T*>(this)); } /** Get a reference-counted pointer to the underlying object. It can be * converted safely to `std::shared_ptr`, `std::unique_ptr`, * `boost::shared_ptr`, or `boost::intrusive_ptr`. */ counted_ptr<const T> ptr() const { return counted_ptr<const T>(static_cast<const T*>(this)); } private: counted_facade(const counted_facade&); counted_facade& operator=(const counted_facade&); template <class U> friend class counted_ptr; }; } #endif /*!PROTON_CPP_FACADE_H*/
35.671233
87
0.711598
[ "object" ]
790ee41cca31b01fa71b324e08411e1e0bcc1889
2,973
cc
C++
bssopenapi/src/model/QuerySplitItemBillRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
bssopenapi/src/model/QuerySplitItemBillRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
bssopenapi/src/model/QuerySplitItemBillRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/bssopenapi/model/QuerySplitItemBillRequest.h> using AlibabaCloud::BssOpenApi::Model::QuerySplitItemBillRequest; QuerySplitItemBillRequest::QuerySplitItemBillRequest() : RpcServiceRequest("bssopenapi", "2017-12-14", "QuerySplitItemBill") { setMethod(HttpRequest::Method::Post); } QuerySplitItemBillRequest::~QuerySplitItemBillRequest() {} std::string QuerySplitItemBillRequest::getProductCode()const { return productCode_; } void QuerySplitItemBillRequest::setProductCode(const std::string& productCode) { productCode_ = productCode; setParameter("ProductCode", productCode); } std::string QuerySplitItemBillRequest::getSubscriptionType()const { return subscriptionType_; } void QuerySplitItemBillRequest::setSubscriptionType(const std::string& subscriptionType) { subscriptionType_ = subscriptionType; setParameter("SubscriptionType", subscriptionType); } std::string QuerySplitItemBillRequest::getBillingCycle()const { return billingCycle_; } void QuerySplitItemBillRequest::setBillingCycle(const std::string& billingCycle) { billingCycle_ = billingCycle; setParameter("BillingCycle", billingCycle); } long QuerySplitItemBillRequest::getOwnerId()const { return ownerId_; } void QuerySplitItemBillRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } int QuerySplitItemBillRequest::getPageNum()const { return pageNum_; } void QuerySplitItemBillRequest::setPageNum(int pageNum) { pageNum_ = pageNum; setParameter("PageNum", std::to_string(pageNum)); } long QuerySplitItemBillRequest::getBillOwnerId()const { return billOwnerId_; } void QuerySplitItemBillRequest::setBillOwnerId(long billOwnerId) { billOwnerId_ = billOwnerId; setParameter("BillOwnerId", std::to_string(billOwnerId)); } std::string QuerySplitItemBillRequest::getProductType()const { return productType_; } void QuerySplitItemBillRequest::setProductType(const std::string& productType) { productType_ = productType; setParameter("ProductType", productType); } int QuerySplitItemBillRequest::getPageSize()const { return pageSize_; } void QuerySplitItemBillRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setParameter("PageSize", std::to_string(pageSize)); }
25.194915
89
0.764884
[ "model" ]
7914f3dc1fd1cbf76b91a5166b20af5c0e7e5d21
80,839
cpp
C++
thormang3_walking_module/src/walking_module.cpp
ROBOTIS-GIT/ROBOTIS-THORMANG-P-MPC
52e64a08d4a759c2eb93530b25d9a1bd10a58442
[ "Apache-2.0" ]
8
2016-05-03T14:02:03.000Z
2020-09-21T06:06:13.000Z
thormang3_walking_module/src/walking_module.cpp
ROBOTIS-GIT/ROBOTIS-THORMANG-P-MPC
52e64a08d4a759c2eb93530b25d9a1bd10a58442
[ "Apache-2.0" ]
12
2016-05-18T10:39:45.000Z
2019-08-09T00:56:06.000Z
thormang3_walking_module/src/walking_module.cpp
ROBOTIS-GIT/ROBOTIS-THORMANG-P-MPC
52e64a08d4a759c2eb93530b25d9a1bd10a58442
[ "Apache-2.0" ]
14
2016-04-28T08:56:12.000Z
2021-09-16T07:43:46.000Z
/******************************************************************************* * Copyright 2018 ROBOTIS CO., LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* * online_wakling_module.cpp * * Created on: 2016. 12. 14. * Author: Jay Song */ #include <stdio.h> #include <eigen_conversions/eigen_msg.h> #include "thormang3_walking_module/walking_module.h" using namespace thormang3; class WalkingStatusMSG { public: static const std::string FAILED_TO_ADD_STEP_DATA_MSG; static const std::string BALANCE_PARAM_SETTING_STARTED_MSG; static const std::string BALANCE_PARAM_SETTING_FINISHED_MSG; static const std::string JOINT_FEEDBACK_GAIN_UPDATE_STARTED_MSG; static const std::string JOINT_FEEDBACK_GAIN_UPDATE_FINISHED_MSG; static const std::string WALKING_MODULE_IS_ENABLED_MSG; static const std::string WALKING_MODULE_IS_DISABLED_MSG; static const std::string BALANCE_HAS_BEEN_TURNED_OFF; static const std::string WALKING_START_MSG; static const std::string WALKING_FINISH_MSG; }; const std::string WalkingStatusMSG::FAILED_TO_ADD_STEP_DATA_MSG = "Failed_to_add_Step_Data"; const std::string WalkingStatusMSG::BALANCE_PARAM_SETTING_STARTED_MSG = "Balance_Param_Setting_Started"; const std::string WalkingStatusMSG::BALANCE_PARAM_SETTING_FINISHED_MSG = "Balance_Param_Setting_Finished"; const std::string WalkingStatusMSG::JOINT_FEEDBACK_GAIN_UPDATE_STARTED_MSG = "Joint_FeedBack_Gain_Update_Started"; const std::string WalkingStatusMSG::JOINT_FEEDBACK_GAIN_UPDATE_FINISHED_MSG = "Joint_FeedBack_Gain_Update_Finished"; const std::string WalkingStatusMSG::WALKING_MODULE_IS_ENABLED_MSG = "Walking_Module_is_enabled"; const std::string WalkingStatusMSG::WALKING_MODULE_IS_DISABLED_MSG = "Walking_Module_is_disabled"; const std::string WalkingStatusMSG::BALANCE_HAS_BEEN_TURNED_OFF = "Balance_has_been_turned_off"; const std::string WalkingStatusMSG::WALKING_START_MSG = "Walking_Started"; const std::string WalkingStatusMSG::WALKING_FINISH_MSG = "Walking_Finished"; OnlineWalkingModule::OnlineWalkingModule() : control_cycle_msec_(8) { gazebo_ = false; enable_ = false; module_name_ = "walking_module"; control_mode_ = robotis_framework::PositionControl; result_["r_leg_hip_y"] = new robotis_framework::DynamixelState(); result_["r_leg_hip_r"] = new robotis_framework::DynamixelState(); result_["r_leg_hip_p"] = new robotis_framework::DynamixelState(); result_["r_leg_kn_p" ] = new robotis_framework::DynamixelState(); result_["r_leg_an_p" ] = new robotis_framework::DynamixelState(); result_["r_leg_an_r" ] = new robotis_framework::DynamixelState(); result_["l_leg_hip_y"] = new robotis_framework::DynamixelState(); result_["l_leg_hip_r"] = new robotis_framework::DynamixelState(); result_["l_leg_hip_p"] = new robotis_framework::DynamixelState(); result_["l_leg_kn_p" ] = new robotis_framework::DynamixelState(); result_["l_leg_an_p" ] = new robotis_framework::DynamixelState(); result_["l_leg_an_r" ] = new robotis_framework::DynamixelState(); joint_name_to_index_["r_leg_hip_y"] = 0; joint_name_to_index_["r_leg_hip_r"] = 1; joint_name_to_index_["r_leg_hip_p"] = 2; joint_name_to_index_["r_leg_kn_p" ] = 3; joint_name_to_index_["r_leg_an_p" ] = 4; joint_name_to_index_["r_leg_an_r" ] = 5; joint_name_to_index_["l_leg_hip_y"] = 6; joint_name_to_index_["l_leg_hip_r"] = 7; joint_name_to_index_["l_leg_hip_p"] = 8; joint_name_to_index_["l_leg_kn_p" ] = 9; joint_name_to_index_["l_leg_an_p" ] = 10; joint_name_to_index_["l_leg_an_r" ] = 11; previous_running_ = present_running = false; gyro_roll_ = gyro_pitch_ = 0; orientation_roll_ = orientation_pitch_ = 0; r_foot_fx_N_ = r_foot_fy_N_ = r_foot_fz_N_ = 0; r_foot_Tx_Nm_ = r_foot_Ty_Nm_ = r_foot_Tz_Nm_ = 0; l_foot_fx_N_ = l_foot_fy_N_ = l_foot_fz_N_ = 0; l_foot_Tx_Nm_ = l_foot_Ty_Nm_ = l_foot_Tz_Nm_ = 0; r_foot_ft_publish_checker_ = -1; l_foot_ft_publish_checker_ = -1; desired_matrix_g_to_cob_ = Eigen::MatrixXd::Identity(4,4); desired_matrix_g_to_rfoot_ = Eigen::MatrixXd::Identity(4,4); desired_matrix_g_to_lfoot_ = Eigen::MatrixXd::Identity(4,4); balance_update_with_loop_ = false; balance_update_duration_ = 2.0; balance_update_sys_time_ = 2.0; balance_update_polynomial_coeff_.resize(6, 1); double tf = balance_update_duration_; Eigen::MatrixXd A(6,6), B(6, 1); A << 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, tf*tf*tf*tf*tf, tf*tf*tf*tf, tf*tf*tf, tf*tf, tf, 1.0, 5.0*tf*tf*tf*tf, 4.0*tf*tf*tf, 3.0*tf*tf, 2.0*tf, 1.0, 0.0, 20.0*tf*tf*tf, 12.0*tf*tf, 6.0*tf, 2.0, 0.0, 0.0; B << 0, 0, 0, 2.0, 0, 0; balance_update_polynomial_coeff_ = A.inverse() * B; joint_feedback_update_with_loop_ = false; joint_feedback_update_duration_ = 2.0; joint_feedback_update_sys_time_ = 2.0; joint_feedback_update_polynomial_coeff_ = balance_update_polynomial_coeff_; rot_x_pi_3d_.resize(3,3); rot_x_pi_3d_ << 1, 0, 0, 0, -1, 0, 0, 0, -1; rot_z_pi_3d_.resize(3,3); rot_z_pi_3d_ << -1, 0, 0, 0, -1, 0, 0, 0, 1; } OnlineWalkingModule::~OnlineWalkingModule() { queue_thread_.join(); } void OnlineWalkingModule::initialize(const int control_cycle_msec, robotis_framework::Robot *robot) { queue_thread_ = boost::thread(boost::bind(&OnlineWalkingModule::queueThread, this)); control_cycle_msec_ = control_cycle_msec; THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); online_walking->setInitialPose(0, -0.093, -0.63, 0, 0, 0, 0, 0.093, -0.63, 0, 0, 0, 0, 0, 0, 0, 0, 0); online_walking->hip_roll_feedforward_angle_rad_ = 0.0*M_PI/180.0; online_walking->balance_ctrl_.setCOBManualAdjustment(-10.0*0.001, 0, 0); online_walking->initialize(); process_mutex_.lock(); desired_matrix_g_to_cob_ = online_walking->mat_g_to_cob_; desired_matrix_g_to_rfoot_ = online_walking->mat_g_to_rfoot_; desired_matrix_g_to_lfoot_ = online_walking->mat_g_to_lfoot_; process_mutex_.unlock(); result_["r_leg_hip_y"]->goal_position_ = online_walking->out_angle_rad_[0]; result_["r_leg_hip_r"]->goal_position_ = online_walking->out_angle_rad_[1]; result_["r_leg_hip_p"]->goal_position_ = online_walking->out_angle_rad_[2]; result_["r_leg_kn_p"]->goal_position_ = online_walking->out_angle_rad_[3]; result_["r_leg_an_p"]->goal_position_ = online_walking->out_angle_rad_[4]; result_["r_leg_an_r"]->goal_position_ = online_walking->out_angle_rad_[5]; result_["l_leg_hip_y"]->goal_position_ = online_walking->out_angle_rad_[6]; result_["l_leg_hip_r"]->goal_position_ = online_walking->out_angle_rad_[7]; result_["l_leg_hip_p"]->goal_position_ = online_walking->out_angle_rad_[8]; result_["l_leg_kn_p" ]->goal_position_ = online_walking->out_angle_rad_[9]; result_["l_leg_an_p" ]->goal_position_ = online_walking->out_angle_rad_[10]; result_["l_leg_an_r" ]->goal_position_ = online_walking->out_angle_rad_[11]; online_walking->start(); online_walking->process(); previous_running_ = isRunning(); online_walking->hip_roll_feedforward_angle_rad_ = 0.0; online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.foot_roll_angle_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.foot_roll_angle_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_x_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_x_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_y_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_y_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_z_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_z_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.d_gain_ = 0; } void OnlineWalkingModule::queueThread() { ros::NodeHandle ros_node; ros::CallbackQueue callback_queue; ros_node.setCallbackQueue(&callback_queue); /* publish topics */ robot_pose_pub_ = ros_node.advertise<thormang3_walking_module_msgs::RobotPose>("/robotis/walking/robot_pose", 1); status_msg_pub_ = ros_node.advertise<robotis_controller_msgs::StatusMsg>("robotis/status", 1); pelvis_base_msg_pub_ = ros_node.advertise<geometry_msgs::PoseStamped>("/robotis/pelvis_pose_base_walking", 1); done_msg_pub_ = ros_node.advertise<std_msgs::String>("/robotis/movement_done", 1); #ifdef WALKING_TUNE walking_joint_states_pub_ = ros_node.advertise<thormang3_walking_module_msgs::WalkingJointStatesStamped>("/robotis/walking/walking_joint_states", 1); #endif /* ROS Service Callback Functions */ ros::ServiceServer get_ref_step_data_server = ros_node.advertiseService("/robotis/walking/get_reference_step_data", &OnlineWalkingModule::getReferenceStepDataServiceCallback, this); ros::ServiceServer add_step_data_array_sever = ros_node.advertiseService("/robotis/walking/add_step_data", &OnlineWalkingModule::addStepDataServiceCallback, this); ros::ServiceServer walking_start_server = ros_node.advertiseService("/robotis/walking/walking_start", &OnlineWalkingModule::startWalkingServiceCallback, this); ros::ServiceServer is_running_server = ros_node.advertiseService("/robotis/walking/is_running", &OnlineWalkingModule::IsRunningServiceCallback, this); ros::ServiceServer set_balance_param_server = ros_node.advertiseService("/robotis/walking/set_balance_param", &OnlineWalkingModule::setBalanceParamServiceCallback, this); ros::ServiceServer set_joint_feedback_gain = ros_node.advertiseService("/robotis/walking/joint_feedback_gain", &OnlineWalkingModule::setJointFeedBackGainServiceCallback, this); ros::ServiceServer remove_existing_step_data = ros_node.advertiseService("/robotis/walking/remove_existing_step_data", &OnlineWalkingModule::removeExistingStepDataServiceCallback, this); /* sensor topic subscribe */ ros::Subscriber imu_data_sub = ros_node.subscribe("/robotis/sensor/imu/imu", 3, &OnlineWalkingModule::imuDataOutputCallback, this); ros::WallDuration duration(control_cycle_msec_ / 1000.0); if(ros::param::get("gazebo", gazebo_) == false) gazebo_ = false; while(ros_node.ok()) callback_queue.callAvailable(duration); // while (ros_node.ok()) // { // callback_queue.callAvailable(); // usleep(1000); // } } void OnlineWalkingModule::publishRobotPose(void) { //process_mutex_.lock(); robot_pose_msg_.global_to_center_of_body.position.x = desired_matrix_g_to_cob_.coeff(0, 3); robot_pose_msg_.global_to_center_of_body.position.y = desired_matrix_g_to_cob_.coeff(1, 3); robot_pose_msg_.global_to_center_of_body.position.z = desired_matrix_g_to_cob_.coeff(2, 3); Eigen::Quaterniond quaterniond_g_to_cob(desired_matrix_g_to_cob_.block<3, 3>(0, 0)); robot_pose_msg_.global_to_right_foot.position.x = desired_matrix_g_to_rfoot_.coeff(0, 3); robot_pose_msg_.global_to_right_foot.position.y = desired_matrix_g_to_rfoot_.coeff(1, 3); robot_pose_msg_.global_to_right_foot.position.z = desired_matrix_g_to_rfoot_.coeff(2, 3); Eigen::Quaterniond quaterniond_g_to_rf(desired_matrix_g_to_rfoot_.block<3, 3>(0, 0)); robot_pose_msg_.global_to_left_foot.position.x = desired_matrix_g_to_lfoot_.coeff(0, 3); robot_pose_msg_.global_to_left_foot.position.y = desired_matrix_g_to_lfoot_.coeff(1, 3); robot_pose_msg_.global_to_left_foot.position.z = desired_matrix_g_to_lfoot_.coeff(2, 3); Eigen::Quaterniond quaterniond_g_to_lf(desired_matrix_g_to_lfoot_.block<3, 3>(0, 0)); //process_mutex_.unlock(); tf::quaternionEigenToMsg(quaterniond_g_to_cob, robot_pose_msg_.global_to_center_of_body.orientation); tf::quaternionEigenToMsg(quaterniond_g_to_rf, robot_pose_msg_.global_to_right_foot.orientation); tf::quaternionEigenToMsg(quaterniond_g_to_lf, robot_pose_msg_.global_to_left_foot.orientation); robot_pose_pub_.publish(robot_pose_msg_); // geometry_msgs::PoseStamped pose_msg; // pose_msg.header.stamp = ros::Time::now(); // // process_mutex_.lock(); // // Eigen::MatrixXd g_to_pelvis = desired_matrix_g_to_cob_ * robotis_framework::getTransformationXYZRPY(0, 0, 0.093, 0, 0, 0); // Eigen::Quaterniond pelvis_rotation = robotis_framework::convertRotationToQuaternion(desired_matrix_g_to_cob_); // // pose_msg.pose.position.x = g_to_pelvis.coeff(0, 3); // pose_msg.pose.position.y = g_to_pelvis.coeff(1, 3); // pose_msg.pose.position.z = g_to_pelvis.coeff(2, 3) - 0.093; // tf::quaternionEigenToMsg(pelvis_rotation, pose_msg.pose.orientation); // // process_mutex_.unlock(); // // pelvis_base_msg_pub_.publish(pose_msg); } void OnlineWalkingModule::publishStatusMsg(unsigned int type, std::string msg) { robotis_controller_msgs::StatusMsg status_msg; status_msg.header.stamp = ros::Time::now(); status_msg.type = type; status_msg.module_name = "Walking"; status_msg.status_msg = msg; status_msg_pub_.publish(status_msg); } void OnlineWalkingModule::publishDoneMsg(std::string msg) { std_msgs::String done_msg; done_msg.data = msg; done_msg_pub_.publish(done_msg); } int OnlineWalkingModule::convertStepDataMsgToStepData(thormang3_walking_module_msgs::StepData& src, robotis_framework::StepData& des) { int copy_result = thormang3_walking_module_msgs::AddStepDataArray::Response::NO_ERROR; des.time_data. walking_state = src.time_data.walking_state; des.time_data.abs_step_time = src.time_data.abs_step_time; des.time_data.dsp_ratio = src.time_data.dsp_ratio; des.position_data.moving_foot = src.position_data.moving_foot; des.position_data.shoulder_swing_gain = 0; des.position_data.elbow_swing_gain = 0; des.position_data.foot_z_swap = src.position_data.foot_z_swap; des.position_data.waist_pitch_angle = 0; des.position_data.waist_yaw_angle = src.position_data.torso_yaw_angle_rad; des.position_data.body_z_swap = src.position_data.body_z_swap; des.position_data.body_pose.z = src.position_data.body_pose.z; des.position_data.body_pose.roll = src.position_data.body_pose.roll; des.position_data.body_pose.pitch = src.position_data.body_pose.pitch; des.position_data.body_pose.yaw = src.position_data.body_pose.yaw; des.position_data.right_foot_pose.x = src.position_data.right_foot_pose.x; des.position_data.right_foot_pose.y = src.position_data.right_foot_pose.y; des.position_data.right_foot_pose.z = src.position_data.right_foot_pose.z; des.position_data.right_foot_pose.roll = src.position_data.right_foot_pose.roll; des.position_data.right_foot_pose.pitch = src.position_data.right_foot_pose.pitch; des.position_data.right_foot_pose.yaw = src.position_data.right_foot_pose.yaw; des.position_data.left_foot_pose.x = src.position_data.left_foot_pose.x; des.position_data.left_foot_pose.y = src.position_data.left_foot_pose.y; des.position_data.left_foot_pose.z = src.position_data.left_foot_pose.z; des.position_data.left_foot_pose.roll = src.position_data.left_foot_pose.roll; des.position_data.left_foot_pose.pitch = src.position_data.left_foot_pose.pitch; des.position_data.left_foot_pose.yaw = src.position_data.left_foot_pose.yaw; des.time_data.start_time_delay_ratio_x = src.time_data.start_time_delay_ratio_x; des.time_data.start_time_delay_ratio_y = src.time_data.start_time_delay_ratio_y; des.time_data.start_time_delay_ratio_z = src.time_data.start_time_delay_ratio_z; des.time_data.start_time_delay_ratio_roll = src.time_data.start_time_delay_ratio_roll; des.time_data.start_time_delay_ratio_pitch = src.time_data.start_time_delay_ratio_pitch; des.time_data.start_time_delay_ratio_yaw = src.time_data.start_time_delay_ratio_yaw; des.time_data.finish_time_advance_ratio_x = src.time_data.finish_time_advance_ratio_x; des.time_data.finish_time_advance_ratio_y = src.time_data.finish_time_advance_ratio_y; des.time_data.finish_time_advance_ratio_z = src.time_data.finish_time_advance_ratio_z; des.time_data.finish_time_advance_ratio_roll = src.time_data.finish_time_advance_ratio_roll; des.time_data.finish_time_advance_ratio_pitch = src.time_data.finish_time_advance_ratio_pitch; des.time_data.finish_time_advance_ratio_yaw = src.time_data.finish_time_advance_ratio_yaw; if((src.time_data.walking_state != thormang3_walking_module_msgs::StepTimeData::IN_WALKING_STARTING) && (src.time_data.walking_state != thormang3_walking_module_msgs::StepTimeData::IN_WALKING) && (src.time_data.walking_state != thormang3_walking_module_msgs::StepTimeData::IN_WALKING_ENDING) ) copy_result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_TIME_DATA; if((src.time_data.start_time_delay_ratio_x < 0) || (src.time_data.start_time_delay_ratio_y < 0) || (src.time_data.start_time_delay_ratio_z < 0) || (src.time_data.start_time_delay_ratio_roll < 0) || (src.time_data.start_time_delay_ratio_pitch < 0) || (src.time_data.start_time_delay_ratio_yaw < 0) ) copy_result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_TIME_DATA; if((src.time_data.finish_time_advance_ratio_x < 0) || (src.time_data.finish_time_advance_ratio_y < 0) || (src.time_data.finish_time_advance_ratio_z < 0) || (src.time_data.finish_time_advance_ratio_roll < 0) || (src.time_data.finish_time_advance_ratio_pitch < 0) || (src.time_data.finish_time_advance_ratio_yaw < 0) ) copy_result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_TIME_DATA; if(((src.time_data.start_time_delay_ratio_x + src.time_data.finish_time_advance_ratio_x) > 1.0) || ((src.time_data.start_time_delay_ratio_y + src.time_data.finish_time_advance_ratio_y ) > 1.0) || ((src.time_data.start_time_delay_ratio_z + src.time_data.finish_time_advance_ratio_z ) > 1.0) || ((src.time_data.start_time_delay_ratio_roll + src.time_data.finish_time_advance_ratio_roll ) > 1.0) || ((src.time_data.start_time_delay_ratio_pitch + src.time_data.finish_time_advance_ratio_pitch ) > 1.0) || ((src.time_data.start_time_delay_ratio_yaw + src.time_data.finish_time_advance_ratio_yaw ) > 1.0) ) copy_result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_TIME_DATA; if((src.position_data.moving_foot != thormang3_walking_module_msgs::StepPositionData::STANDING) && (src.position_data.moving_foot != thormang3_walking_module_msgs::StepPositionData::RIGHT_FOOT_SWING) && (src.position_data.moving_foot != thormang3_walking_module_msgs::StepPositionData::LEFT_FOOT_SWING)) copy_result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_POSITION_DATA; if(src.position_data.foot_z_swap < 0) copy_result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_POSITION_DATA; return copy_result; } int OnlineWalkingModule::convertStepDataToStepDataMsg(robotis_framework::StepData& src, thormang3_walking_module_msgs::StepData& des) { des.time_data.walking_state = src.time_data.walking_state; des.time_data.abs_step_time = src.time_data.abs_step_time; des.time_data.dsp_ratio = src.time_data.dsp_ratio; des.time_data.start_time_delay_ratio_x = des.time_data.finish_time_advance_ratio_x = 0; des.time_data.start_time_delay_ratio_y = des.time_data.finish_time_advance_ratio_y = 0; des.time_data.start_time_delay_ratio_z = des.time_data.finish_time_advance_ratio_z = 0; des.time_data.start_time_delay_ratio_roll = des.time_data.finish_time_advance_ratio_roll = 0; des.time_data.start_time_delay_ratio_pitch = des.time_data.finish_time_advance_ratio_pitch = 0; des.time_data.start_time_delay_ratio_yaw = des.time_data.finish_time_advance_ratio_yaw = 0; des.position_data.moving_foot = src.position_data.moving_foot; des.position_data.foot_z_swap = src.position_data.foot_z_swap; des.position_data.torso_yaw_angle_rad = src.position_data.waist_yaw_angle; des.position_data.body_z_swap = src.position_data.body_z_swap; des.position_data.body_pose.z = src.position_data.body_pose.z; des.position_data.body_pose.roll = src.position_data.body_pose.roll; des.position_data.body_pose.pitch = src.position_data.body_pose.pitch; des.position_data.body_pose.yaw = src.position_data.body_pose.yaw; des.position_data.right_foot_pose.x = src.position_data.right_foot_pose.x; des.position_data.right_foot_pose.y = src.position_data.right_foot_pose.y; des.position_data.right_foot_pose.z = src.position_data.right_foot_pose.z; des.position_data.right_foot_pose.roll = src.position_data.right_foot_pose.roll; des.position_data.right_foot_pose.pitch = src.position_data.right_foot_pose.pitch; des.position_data.right_foot_pose.yaw = src.position_data.right_foot_pose.yaw; des.position_data.left_foot_pose.x = src.position_data.left_foot_pose.x; des.position_data.left_foot_pose.y = src.position_data.left_foot_pose.y; des.position_data.left_foot_pose.z = src.position_data.left_foot_pose.z; des.position_data.left_foot_pose.roll = src.position_data.left_foot_pose.roll; des.position_data.left_foot_pose.pitch = src.position_data.left_foot_pose.pitch; des.position_data.left_foot_pose.yaw = src.position_data.left_foot_pose.yaw; return 0; } bool OnlineWalkingModule::getReferenceStepDataServiceCallback(thormang3_walking_module_msgs::GetReferenceStepData::Request &req, thormang3_walking_module_msgs::GetReferenceStepData::Response &res) { THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); robotis_framework::StepData refStepData; online_walking->getReferenceStepDatafotAddition(&refStepData); convertStepDataToStepDataMsg(refStepData, res.reference_step_data); return true; } bool OnlineWalkingModule::addStepDataServiceCallback(thormang3_walking_module_msgs::AddStepDataArray::Request &req, thormang3_walking_module_msgs::AddStepDataArray::Response &res) { THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); res.result = thormang3_walking_module_msgs::AddStepDataArray::Response::NO_ERROR; if(enable_ == false) { res.result |= thormang3_walking_module_msgs::AddStepDataArray::Response::NOT_ENABLED_WALKING_MODULE; std::string status_msg = WalkingStatusMSG::FAILED_TO_ADD_STEP_DATA_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_ERROR, status_msg); return true; } if((req.step_data_array.size() > 100) && (req.remove_existing_step_data == true) && ((online_walking->isRunning() == true))) { res.result |= thormang3_walking_module_msgs::AddStepDataArray::Response::TOO_MANY_STEP_DATA; std::string status_msg = WalkingStatusMSG::FAILED_TO_ADD_STEP_DATA_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_ERROR, status_msg); return true; } robotis_framework::StepData step_data, ref_step_data; std::vector<robotis_framework::StepData> req_step_data_array; online_walking->getReferenceStepDatafotAddition(&ref_step_data); for(int i = 0; i < req.step_data_array.size(); i++) { res.result |= convertStepDataMsgToStepData(req.step_data_array[i], step_data); if(step_data.time_data.abs_step_time <= 0) { res.result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_TIME_DATA; } if(i != 0) { if(step_data.time_data.abs_step_time <= req_step_data_array[req_step_data_array.size() - 1].time_data.abs_step_time) { res.result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_TIME_DATA; } } else { if(step_data.time_data.abs_step_time <= ref_step_data.time_data.abs_step_time) { res.result |= thormang3_walking_module_msgs::AddStepDataArray::Response::PROBLEM_IN_TIME_DATA; } } if(res.result != thormang3_walking_module_msgs::AddStepDataArray::Response::NO_ERROR) { std::string status_msg = WalkingStatusMSG::FAILED_TO_ADD_STEP_DATA_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_ERROR, status_msg); return true; } req_step_data_array.push_back(step_data); } if(req.remove_existing_step_data == true) { int exist_num_of_step_data = online_walking->getNumofRemainingUnreservedStepData(); if(exist_num_of_step_data != 0) for(int remove_count = 0; remove_count < exist_num_of_step_data; remove_count++) online_walking->eraseLastStepData(); } else { if(online_walking->isRunning() == true) { res.result |= thormang3_walking_module_msgs::AddStepDataArray::Response::ROBOT_IS_WALKING_NOW; std::string status_msg = WalkingStatusMSG::FAILED_TO_ADD_STEP_DATA_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_ERROR, status_msg); return true; } } if(checkBalanceOnOff() == false) { std::string status_msg = WalkingStatusMSG::BALANCE_HAS_BEEN_TURNED_OFF; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_ERROR, status_msg); return true; } for(unsigned int i = 0; i < req_step_data_array.size() ; i++) online_walking->addStepData(req_step_data_array[i]); if( req.auto_start == true) { online_walking->start(); } return true; } bool OnlineWalkingModule::startWalkingServiceCallback(thormang3_walking_module_msgs::StartWalking::Request &req, thormang3_walking_module_msgs::StartWalking::Response &res) { THORMANG3OnlineWalking *prev_walking = THORMANG3OnlineWalking::getInstance(); res.result = thormang3_walking_module_msgs::StartWalking::Response::NO_ERROR; if(enable_ == false) { res.result |= thormang3_walking_module_msgs::StartWalking::Response::NOT_ENABLED_WALKING_MODULE; return true; } if(prev_walking->isRunning() == true) { res.result |= thormang3_walking_module_msgs::StartWalking::Response::ROBOT_IS_WALKING_NOW; return true; } if(checkBalanceOnOff() == false) { std::string status_msg = WalkingStatusMSG::BALANCE_HAS_BEEN_TURNED_OFF; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_ERROR, status_msg); return true; } if(prev_walking->getNumofRemainingUnreservedStepData() == 0) { res.result |= thormang3_walking_module_msgs::StartWalking::Response::NO_STEP_DATA; return true; } if(res.result == thormang3_walking_module_msgs::StartWalking::Response::NO_ERROR) { prev_walking->start(); } return true; } bool OnlineWalkingModule::IsRunningServiceCallback(thormang3_walking_module_msgs::IsRunning::Request &req, thormang3_walking_module_msgs::IsRunning::Response &res) { bool is_running = isRunning(); res.is_running = is_running; return true; } bool OnlineWalkingModule::isRunning() { return THORMANG3OnlineWalking::getInstance()->isRunning(); } bool OnlineWalkingModule::setJointFeedBackGainServiceCallback(thormang3_walking_module_msgs::SetJointFeedBackGain::Request &req, thormang3_walking_module_msgs::SetJointFeedBackGain::Response &res) { THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); res.result = thormang3_walking_module_msgs::SetJointFeedBackGain::Response::NO_ERROR; if( enable_ == false) res.result |= thormang3_walking_module_msgs::SetJointFeedBackGain::Response::NOT_ENABLED_WALKING_MODULE; if( joint_feedback_update_with_loop_ == true) res.result |= thormang3_walking_module_msgs::SetJointFeedBackGain::Response::PREV_REQUEST_IS_NOT_FINISHED; if( res.result != thormang3_walking_module_msgs::SetJointFeedBackGain::Response::NO_ERROR) { publishDoneMsg("walking_joint_feedback_failed"); return true; } if( req.updating_duration <= 0.0 ) { // under 8ms apply immediately setJointFeedBackGain(req.feedback_gain); std::string status_msg = WalkingStatusMSG::JOINT_FEEDBACK_GAIN_UPDATE_FINISHED_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, status_msg); publishDoneMsg("walking_joint_feedback"); return true; } else { joint_feedback_update_duration_ = req.updating_duration; } joint_feedback_update_sys_time_ = 0.0; joint_feedback_update_polynomial_coeff_.resize(6, 1); double tf = joint_feedback_update_duration_; Eigen::MatrixXd A(6,6), B(6, 1); A << 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, tf*tf*tf*tf*tf, tf*tf*tf*tf, tf*tf*tf, tf*tf, tf, 1.0, 5.0*tf*tf*tf*tf, 4.0*tf*tf*tf, 3.0*tf*tf, 2.0*tf, 1.0, 0.0, 20.0*tf*tf*tf, 12.0*tf*tf, 6.0*tf, 2.0, 0.0, 0.0; B << 0, 0, 0, 1.0, 0, 0; joint_feedback_update_polynomial_coeff_ = A.inverse() * B; desired_joint_feedback_gain_ = req.feedback_gain; previous_joint_feedback_gain_.r_leg_hip_y_p_gain = online_walking->leg_angle_feed_back_[0].p_gain_; previous_joint_feedback_gain_.r_leg_hip_y_d_gain = online_walking->leg_angle_feed_back_[0].d_gain_; previous_joint_feedback_gain_.r_leg_hip_r_p_gain = online_walking->leg_angle_feed_back_[1].p_gain_; previous_joint_feedback_gain_.r_leg_hip_r_d_gain = online_walking->leg_angle_feed_back_[1].d_gain_; previous_joint_feedback_gain_.r_leg_hip_p_p_gain = online_walking->leg_angle_feed_back_[2].p_gain_; previous_joint_feedback_gain_.r_leg_hip_p_d_gain = online_walking->leg_angle_feed_back_[2].d_gain_; previous_joint_feedback_gain_.r_leg_kn_p_p_gain = online_walking->leg_angle_feed_back_[3].p_gain_; previous_joint_feedback_gain_.r_leg_kn_p_d_gain = online_walking->leg_angle_feed_back_[3].d_gain_; previous_joint_feedback_gain_.r_leg_an_p_p_gain = online_walking->leg_angle_feed_back_[4].p_gain_; previous_joint_feedback_gain_.r_leg_an_p_d_gain = online_walking->leg_angle_feed_back_[4].d_gain_; previous_joint_feedback_gain_.r_leg_an_r_p_gain = online_walking->leg_angle_feed_back_[5].p_gain_; previous_joint_feedback_gain_.r_leg_an_r_d_gain = online_walking->leg_angle_feed_back_[5].d_gain_; previous_joint_feedback_gain_.l_leg_hip_y_p_gain = online_walking->leg_angle_feed_back_[6].p_gain_; previous_joint_feedback_gain_.l_leg_hip_y_d_gain = online_walking->leg_angle_feed_back_[6].d_gain_; previous_joint_feedback_gain_.l_leg_hip_r_p_gain = online_walking->leg_angle_feed_back_[7].p_gain_; previous_joint_feedback_gain_.l_leg_hip_r_d_gain = online_walking->leg_angle_feed_back_[7].d_gain_; previous_joint_feedback_gain_.l_leg_hip_p_p_gain = online_walking->leg_angle_feed_back_[8].p_gain_; previous_joint_feedback_gain_.l_leg_hip_p_d_gain = online_walking->leg_angle_feed_back_[8].d_gain_; previous_joint_feedback_gain_.l_leg_kn_p_p_gain = online_walking->leg_angle_feed_back_[9].p_gain_; previous_joint_feedback_gain_.l_leg_kn_p_d_gain = online_walking->leg_angle_feed_back_[9].d_gain_; previous_joint_feedback_gain_.l_leg_an_p_p_gain = online_walking->leg_angle_feed_back_[10].p_gain_; previous_joint_feedback_gain_.l_leg_an_p_d_gain = online_walking->leg_angle_feed_back_[10].d_gain_; previous_joint_feedback_gain_.l_leg_an_r_p_gain = online_walking->leg_angle_feed_back_[11].p_gain_; previous_joint_feedback_gain_.l_leg_an_r_d_gain = online_walking->leg_angle_feed_back_[11].d_gain_; joint_feedback_update_with_loop_ = true; joint_feedback_update_sys_time_ = 0.0; return true; } bool OnlineWalkingModule::setBalanceParamServiceCallback(thormang3_walking_module_msgs::SetBalanceParam::Request &req, thormang3_walking_module_msgs::SetBalanceParam::Response &res) { THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); res.result = thormang3_walking_module_msgs::SetBalanceParam::Response::NO_ERROR; if( enable_ == false) res.result |= thormang3_walking_module_msgs::SetBalanceParam::Response::NOT_ENABLED_WALKING_MODULE; if( balance_update_with_loop_ == true) { res.result |= thormang3_walking_module_msgs::SetBalanceParam::Response::PREV_REQUEST_IS_NOT_FINISHED; } if( (req.balance_param.roll_gyro_cut_off_frequency <= 0) || (req.balance_param.pitch_gyro_cut_off_frequency <= 0) || (req.balance_param.roll_angle_cut_off_frequency <= 0) || (req.balance_param.pitch_angle_cut_off_frequency <= 0) || (req.balance_param.foot_x_force_cut_off_frequency <= 0) || (req.balance_param.foot_y_force_cut_off_frequency <= 0) || (req.balance_param.foot_z_force_cut_off_frequency <= 0) || (req.balance_param.foot_roll_torque_cut_off_frequency <= 0) || (req.balance_param.foot_pitch_torque_cut_off_frequency <= 0) ) { //res.result |= thormang3_walking_module_msgs::SetBalanceParam::Response::CUT_OFF_FREQUENCY_IS_ZERO_OR_NEGATIVE; previous_balance_param_.roll_gyro_cut_off_frequency = req.balance_param.roll_gyro_cut_off_frequency; previous_balance_param_.pitch_gyro_cut_off_frequency = req.balance_param.pitch_gyro_cut_off_frequency; previous_balance_param_.roll_angle_cut_off_frequency = req.balance_param.roll_angle_cut_off_frequency; previous_balance_param_.pitch_angle_cut_off_frequency = req.balance_param.pitch_angle_cut_off_frequency; previous_balance_param_.foot_x_force_cut_off_frequency = req.balance_param.foot_x_force_cut_off_frequency; previous_balance_param_.foot_y_force_cut_off_frequency = req.balance_param.foot_y_force_cut_off_frequency; previous_balance_param_.foot_z_force_cut_off_frequency = req.balance_param.foot_z_force_cut_off_frequency; previous_balance_param_.foot_roll_torque_cut_off_frequency = req.balance_param.foot_roll_torque_cut_off_frequency; previous_balance_param_.foot_pitch_torque_cut_off_frequency = req.balance_param.foot_pitch_torque_cut_off_frequency; } if(res.result != thormang3_walking_module_msgs::SetBalanceParam::Response::NO_ERROR) { publishDoneMsg("walking_balance_failed"); return true; } if( req.updating_duration <= 0.0 ) { // under 8ms apply immediately setBalanceParam(req.balance_param); std::string status_msg = WalkingStatusMSG::BALANCE_PARAM_SETTING_FINISHED_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, status_msg); publishDoneMsg("walking_balance"); return true; } else { balance_update_duration_ = req.updating_duration; } balance_update_sys_time_ = 0.0; balance_update_polynomial_coeff_.resize(6, 1); double tf = balance_update_duration_; Eigen::MatrixXd A(6,6), B(6, 1); A << 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, tf*tf*tf*tf*tf, tf*tf*tf*tf, tf*tf*tf, tf*tf, tf, 1.0, 5.0*tf*tf*tf*tf, 4.0*tf*tf*tf, 3.0*tf*tf, 2.0*tf, 1.0, 0.0, 20.0*tf*tf*tf, 12.0*tf*tf, 6.0*tf, 2.0, 0.0, 0.0; B << 0, 0, 0, 1.0, 0, 0; balance_update_polynomial_coeff_ = A.inverse() * B; desired_balance_param_ = req.balance_param; previous_balance_param_.cob_x_offset_m = online_walking->balance_ctrl_.getCOBManualAdjustmentX(); previous_balance_param_.cob_y_offset_m = online_walking->balance_ctrl_.getCOBManualAdjustmentY(); previous_balance_param_.hip_roll_swap_angle_rad = online_walking->hip_roll_feedforward_angle_rad_; ////gain //gyro previous_balance_param_.foot_roll_gyro_p_gain = online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.p_gain_; previous_balance_param_.foot_roll_gyro_d_gain = online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.d_gain_; previous_balance_param_.foot_pitch_gyro_p_gain = online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.p_gain_; previous_balance_param_.foot_pitch_gyro_d_gain = online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.d_gain_; //orientation previous_balance_param_.foot_roll_angle_p_gain = online_walking->balance_ctrl_.foot_roll_angle_ctrl_.p_gain_; previous_balance_param_.foot_roll_angle_d_gain = online_walking->balance_ctrl_.foot_roll_angle_ctrl_.d_gain_; previous_balance_param_.foot_pitch_angle_p_gain = online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.p_gain_; previous_balance_param_.foot_pitch_angle_d_gain = online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.d_gain_; //force torque previous_balance_param_.foot_x_force_p_gain = online_walking->balance_ctrl_.right_foot_force_x_ctrl_.p_gain_; previous_balance_param_.foot_y_force_p_gain = online_walking->balance_ctrl_.right_foot_force_y_ctrl_.p_gain_; previous_balance_param_.foot_z_force_p_gain = online_walking->balance_ctrl_.right_foot_force_z_ctrl_.p_gain_; previous_balance_param_.foot_roll_torque_p_gain = online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.p_gain_; previous_balance_param_.foot_pitch_torque_p_gain = online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.p_gain_; previous_balance_param_.foot_x_force_d_gain = online_walking->balance_ctrl_.right_foot_force_x_ctrl_.d_gain_; previous_balance_param_.foot_y_force_d_gain = online_walking->balance_ctrl_.right_foot_force_y_ctrl_.d_gain_; previous_balance_param_.foot_z_force_d_gain = online_walking->balance_ctrl_.right_foot_force_z_ctrl_.d_gain_; previous_balance_param_.foot_roll_torque_d_gain = online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.d_gain_; previous_balance_param_.foot_pitch_torque_d_gain = online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.d_gain_; ////cut off freq //gyro previous_balance_param_.roll_gyro_cut_off_frequency = online_walking->balance_ctrl_.roll_gyro_lpf_.getCutOffFrequency(); previous_balance_param_.pitch_gyro_cut_off_frequency = online_walking->balance_ctrl_.pitch_gyro_lpf_.getCutOffFrequency(); //orientation previous_balance_param_.roll_angle_cut_off_frequency = online_walking->balance_ctrl_.roll_angle_lpf_.getCutOffFrequency(); previous_balance_param_.pitch_angle_cut_off_frequency = online_walking->balance_ctrl_.pitch_angle_lpf_.getCutOffFrequency(); //force torque previous_balance_param_.foot_x_force_cut_off_frequency = online_walking->balance_ctrl_.right_foot_force_x_lpf_.getCutOffFrequency(); previous_balance_param_.foot_y_force_cut_off_frequency = online_walking->balance_ctrl_.right_foot_force_y_lpf_.getCutOffFrequency(); previous_balance_param_.foot_z_force_cut_off_frequency = online_walking->balance_ctrl_.right_foot_force_z_lpf_.getCutOffFrequency(); previous_balance_param_.foot_roll_torque_cut_off_frequency = online_walking->balance_ctrl_.right_foot_torque_roll_lpf_.getCutOffFrequency(); previous_balance_param_.foot_pitch_torque_cut_off_frequency = online_walking->balance_ctrl_.right_foot_torque_pitch_lpf_.getCutOffFrequency(); balance_update_with_loop_ = true; std::string status_msg = WalkingStatusMSG::BALANCE_PARAM_SETTING_STARTED_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, status_msg); return true; } void OnlineWalkingModule::setBalanceParam(thormang3_walking_module_msgs::BalanceParam& balance_param_msg) { THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); online_walking->hip_roll_feedforward_angle_rad_ = balance_param_msg.hip_roll_swap_angle_rad; online_walking->balance_ctrl_.setCOBManualAdjustment(balance_param_msg.cob_x_offset_m, balance_param_msg.cob_y_offset_m, 0); //// set gain //gyro online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.p_gain_ = balance_param_msg.foot_roll_gyro_p_gain; online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.d_gain_ = balance_param_msg.foot_roll_gyro_d_gain; online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.p_gain_ = balance_param_msg.foot_pitch_gyro_p_gain; online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.d_gain_ = balance_param_msg.foot_pitch_gyro_d_gain; //orientation online_walking->balance_ctrl_.foot_roll_angle_ctrl_.p_gain_ = balance_param_msg.foot_roll_angle_p_gain; online_walking->balance_ctrl_.foot_roll_angle_ctrl_.d_gain_ = balance_param_msg.foot_roll_angle_d_gain; online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.p_gain_ = balance_param_msg.foot_pitch_angle_p_gain; online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.d_gain_ = balance_param_msg.foot_pitch_angle_d_gain; //force torque online_walking->balance_ctrl_.right_foot_force_x_ctrl_.p_gain_ = balance_param_msg.foot_x_force_p_gain; online_walking->balance_ctrl_.right_foot_force_y_ctrl_.p_gain_ = balance_param_msg.foot_y_force_p_gain; online_walking->balance_ctrl_.right_foot_force_z_ctrl_.p_gain_ = balance_param_msg.foot_z_force_p_gain; online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.p_gain_ = balance_param_msg.foot_roll_torque_p_gain; online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.p_gain_ = balance_param_msg.foot_roll_torque_p_gain; online_walking->balance_ctrl_.right_foot_force_x_ctrl_.d_gain_ = balance_param_msg.foot_x_force_d_gain; online_walking->balance_ctrl_.right_foot_force_y_ctrl_.d_gain_ = balance_param_msg.foot_y_force_d_gain; online_walking->balance_ctrl_.right_foot_force_z_ctrl_.d_gain_ = balance_param_msg.foot_z_force_d_gain; online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.d_gain_ = balance_param_msg.foot_roll_torque_d_gain; online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.d_gain_ = balance_param_msg.foot_roll_torque_d_gain; online_walking->balance_ctrl_.left_foot_force_x_ctrl_.p_gain_ = balance_param_msg.foot_x_force_p_gain; online_walking->balance_ctrl_.left_foot_force_y_ctrl_.p_gain_ = balance_param_msg.foot_y_force_p_gain; online_walking->balance_ctrl_.left_foot_force_z_ctrl_.p_gain_ = balance_param_msg.foot_z_force_p_gain; online_walking->balance_ctrl_.left_foot_torque_roll_ctrl_.p_gain_ = balance_param_msg.foot_roll_torque_p_gain; online_walking->balance_ctrl_.left_foot_torque_pitch_ctrl_.p_gain_ = balance_param_msg.foot_roll_torque_p_gain; online_walking->balance_ctrl_.left_foot_force_x_ctrl_.d_gain_ = balance_param_msg.foot_x_force_d_gain; online_walking->balance_ctrl_.left_foot_force_y_ctrl_.d_gain_ = balance_param_msg.foot_y_force_d_gain; online_walking->balance_ctrl_.left_foot_force_z_ctrl_.d_gain_ = balance_param_msg.foot_z_force_d_gain; online_walking->balance_ctrl_.left_foot_torque_roll_ctrl_.d_gain_ = balance_param_msg.foot_roll_torque_d_gain; online_walking->balance_ctrl_.left_foot_torque_pitch_ctrl_.d_gain_ = balance_param_msg.foot_roll_torque_d_gain; //// set cut off freq online_walking->balance_ctrl_.roll_gyro_lpf_.setCutOffFrequency(balance_param_msg.roll_gyro_cut_off_frequency); online_walking->balance_ctrl_.pitch_gyro_lpf_.setCutOffFrequency(balance_param_msg.pitch_gyro_cut_off_frequency); online_walking->balance_ctrl_.roll_angle_lpf_.setCutOffFrequency(balance_param_msg.roll_angle_cut_off_frequency); online_walking->balance_ctrl_.pitch_angle_lpf_.setCutOffFrequency(balance_param_msg.pitch_angle_cut_off_frequency); online_walking->balance_ctrl_.right_foot_force_x_lpf_.setCutOffFrequency(balance_param_msg.foot_x_force_cut_off_frequency); online_walking->balance_ctrl_.right_foot_force_y_lpf_.setCutOffFrequency(balance_param_msg.foot_y_force_cut_off_frequency); online_walking->balance_ctrl_.right_foot_force_z_lpf_.setCutOffFrequency(balance_param_msg.foot_z_force_cut_off_frequency); online_walking->balance_ctrl_.right_foot_torque_roll_lpf_.setCutOffFrequency(balance_param_msg.foot_roll_torque_cut_off_frequency); online_walking->balance_ctrl_.right_foot_torque_pitch_lpf_.setCutOffFrequency(balance_param_msg.foot_pitch_torque_cut_off_frequency); online_walking->balance_ctrl_.left_foot_force_x_lpf_.setCutOffFrequency(balance_param_msg.foot_x_force_cut_off_frequency); online_walking->balance_ctrl_.left_foot_force_y_lpf_.setCutOffFrequency(balance_param_msg.foot_y_force_cut_off_frequency); online_walking->balance_ctrl_.left_foot_force_z_lpf_.setCutOffFrequency(balance_param_msg.foot_z_force_cut_off_frequency); online_walking->balance_ctrl_.left_foot_torque_roll_lpf_.setCutOffFrequency(balance_param_msg.foot_roll_torque_cut_off_frequency); online_walking->balance_ctrl_.left_foot_torque_pitch_lpf_.setCutOffFrequency(balance_param_msg.foot_pitch_torque_cut_off_frequency); } void OnlineWalkingModule::updateBalanceParam() { double current_update_gain = balance_update_polynomial_coeff_.coeff(0,0) * robotis_framework::powDI(balance_update_sys_time_ , 5) + balance_update_polynomial_coeff_.coeff(1,0) * robotis_framework::powDI(balance_update_sys_time_ , 4) + balance_update_polynomial_coeff_.coeff(2,0) * robotis_framework::powDI(balance_update_sys_time_ , 3) + balance_update_polynomial_coeff_.coeff(3,0) * robotis_framework::powDI(balance_update_sys_time_ , 2) + balance_update_polynomial_coeff_.coeff(4,0) * robotis_framework::powDI(balance_update_sys_time_ , 1) + balance_update_polynomial_coeff_.coeff(5,0) ; current_balance_param_.cob_x_offset_m = current_update_gain*(desired_balance_param_.cob_x_offset_m - previous_balance_param_.cob_x_offset_m ) + previous_balance_param_.cob_x_offset_m; current_balance_param_.cob_y_offset_m = current_update_gain*(desired_balance_param_.cob_y_offset_m - previous_balance_param_.cob_y_offset_m ) + previous_balance_param_.cob_y_offset_m; current_balance_param_.hip_roll_swap_angle_rad = current_update_gain*(desired_balance_param_.hip_roll_swap_angle_rad - previous_balance_param_.hip_roll_swap_angle_rad ) + previous_balance_param_.hip_roll_swap_angle_rad; current_balance_param_.foot_roll_gyro_p_gain = current_update_gain*(desired_balance_param_.foot_roll_gyro_p_gain - previous_balance_param_.foot_roll_gyro_p_gain ) + previous_balance_param_.foot_roll_gyro_p_gain; current_balance_param_.foot_roll_gyro_d_gain = current_update_gain*(desired_balance_param_.foot_roll_gyro_d_gain - previous_balance_param_.foot_roll_gyro_d_gain ) + previous_balance_param_.foot_roll_gyro_d_gain; current_balance_param_.foot_pitch_gyro_p_gain = current_update_gain*(desired_balance_param_.foot_pitch_gyro_p_gain - previous_balance_param_.foot_pitch_gyro_p_gain ) + previous_balance_param_.foot_pitch_gyro_p_gain; current_balance_param_.foot_pitch_gyro_d_gain = current_update_gain*(desired_balance_param_.foot_pitch_gyro_d_gain - previous_balance_param_.foot_pitch_gyro_d_gain ) + previous_balance_param_.foot_pitch_gyro_d_gain; current_balance_param_.foot_roll_angle_p_gain = current_update_gain*(desired_balance_param_.foot_roll_angle_p_gain - previous_balance_param_.foot_roll_angle_p_gain ) + previous_balance_param_.foot_roll_angle_p_gain; current_balance_param_.foot_roll_angle_d_gain = current_update_gain*(desired_balance_param_.foot_roll_angle_d_gain - previous_balance_param_.foot_roll_angle_d_gain ) + previous_balance_param_.foot_roll_angle_d_gain; current_balance_param_.foot_pitch_angle_p_gain = current_update_gain*(desired_balance_param_.foot_pitch_angle_p_gain - previous_balance_param_.foot_pitch_angle_p_gain ) + previous_balance_param_.foot_pitch_angle_p_gain; current_balance_param_.foot_pitch_angle_d_gain = current_update_gain*(desired_balance_param_.foot_pitch_angle_d_gain - previous_balance_param_.foot_pitch_angle_d_gain ) + previous_balance_param_.foot_pitch_angle_d_gain; current_balance_param_.foot_x_force_p_gain = current_update_gain*(desired_balance_param_.foot_x_force_p_gain - previous_balance_param_.foot_x_force_p_gain ) + previous_balance_param_.foot_x_force_p_gain; current_balance_param_.foot_y_force_p_gain = current_update_gain*(desired_balance_param_.foot_y_force_p_gain - previous_balance_param_.foot_y_force_p_gain ) + previous_balance_param_.foot_y_force_p_gain; current_balance_param_.foot_z_force_p_gain = current_update_gain*(desired_balance_param_.foot_z_force_p_gain - previous_balance_param_.foot_z_force_p_gain ) + previous_balance_param_.foot_z_force_p_gain; current_balance_param_.foot_roll_torque_p_gain = current_update_gain*(desired_balance_param_.foot_roll_torque_p_gain - previous_balance_param_.foot_roll_torque_p_gain ) + previous_balance_param_.foot_roll_torque_p_gain; current_balance_param_.foot_pitch_torque_p_gain = current_update_gain*(desired_balance_param_.foot_pitch_torque_p_gain - previous_balance_param_.foot_pitch_torque_p_gain ) + previous_balance_param_.foot_pitch_torque_p_gain; current_balance_param_.foot_x_force_d_gain = current_update_gain*(desired_balance_param_.foot_x_force_d_gain - previous_balance_param_.foot_x_force_d_gain ) + previous_balance_param_.foot_x_force_d_gain; current_balance_param_.foot_y_force_d_gain = current_update_gain*(desired_balance_param_.foot_y_force_d_gain - previous_balance_param_.foot_y_force_d_gain ) + previous_balance_param_.foot_y_force_d_gain; current_balance_param_.foot_z_force_d_gain = current_update_gain*(desired_balance_param_.foot_z_force_d_gain - previous_balance_param_.foot_z_force_d_gain ) + previous_balance_param_.foot_z_force_d_gain; current_balance_param_.foot_roll_torque_d_gain = current_update_gain*(desired_balance_param_.foot_roll_torque_d_gain - previous_balance_param_.foot_roll_torque_d_gain ) + previous_balance_param_.foot_roll_torque_d_gain; current_balance_param_.foot_pitch_torque_d_gain = current_update_gain*(desired_balance_param_.foot_pitch_torque_d_gain - previous_balance_param_.foot_pitch_torque_d_gain ) + previous_balance_param_.foot_pitch_torque_d_gain; current_balance_param_.roll_gyro_cut_off_frequency = current_update_gain*(desired_balance_param_.roll_gyro_cut_off_frequency - previous_balance_param_.roll_gyro_cut_off_frequency ) + previous_balance_param_.roll_gyro_cut_off_frequency; current_balance_param_.pitch_gyro_cut_off_frequency = current_update_gain*(desired_balance_param_.pitch_gyro_cut_off_frequency - previous_balance_param_.pitch_gyro_cut_off_frequency ) + previous_balance_param_.pitch_gyro_cut_off_frequency; current_balance_param_.roll_angle_cut_off_frequency = current_update_gain*(desired_balance_param_.roll_angle_cut_off_frequency - previous_balance_param_.roll_angle_cut_off_frequency ) + previous_balance_param_.roll_angle_cut_off_frequency; current_balance_param_.pitch_angle_cut_off_frequency = current_update_gain*(desired_balance_param_.pitch_angle_cut_off_frequency - previous_balance_param_.pitch_angle_cut_off_frequency ) + previous_balance_param_.pitch_angle_cut_off_frequency; current_balance_param_.foot_x_force_cut_off_frequency = current_update_gain*(desired_balance_param_.foot_x_force_cut_off_frequency - previous_balance_param_.foot_x_force_cut_off_frequency ) + previous_balance_param_.foot_x_force_cut_off_frequency; current_balance_param_.foot_y_force_cut_off_frequency = current_update_gain*(desired_balance_param_.foot_y_force_cut_off_frequency - previous_balance_param_.foot_y_force_cut_off_frequency ) + previous_balance_param_.foot_y_force_cut_off_frequency; current_balance_param_.foot_z_force_cut_off_frequency = current_update_gain*(desired_balance_param_.foot_z_force_cut_off_frequency - previous_balance_param_.foot_z_force_cut_off_frequency ) + previous_balance_param_.foot_z_force_cut_off_frequency; current_balance_param_.foot_roll_torque_cut_off_frequency = current_update_gain*(desired_balance_param_.foot_roll_torque_cut_off_frequency - previous_balance_param_.foot_roll_torque_cut_off_frequency ) + previous_balance_param_.foot_roll_torque_cut_off_frequency; current_balance_param_.foot_pitch_torque_cut_off_frequency = current_update_gain*(desired_balance_param_.foot_pitch_torque_cut_off_frequency - previous_balance_param_.foot_pitch_torque_cut_off_frequency) + previous_balance_param_.foot_pitch_torque_cut_off_frequency; setBalanceParam(current_balance_param_); } void OnlineWalkingModule::setJointFeedBackGain(thormang3_walking_module_msgs::JointFeedBackGain& msg) { THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); online_walking->leg_angle_feed_back_[0].p_gain_ = msg.r_leg_hip_y_p_gain ; online_walking->leg_angle_feed_back_[0].d_gain_ = msg.r_leg_hip_y_d_gain ; online_walking->leg_angle_feed_back_[1].p_gain_ = msg.r_leg_hip_r_p_gain ; online_walking->leg_angle_feed_back_[1].d_gain_ = msg.r_leg_hip_r_d_gain ; online_walking->leg_angle_feed_back_[2].p_gain_ = msg.r_leg_hip_p_p_gain ; online_walking->leg_angle_feed_back_[2].d_gain_ = msg.r_leg_hip_p_d_gain ; online_walking->leg_angle_feed_back_[3].p_gain_ = msg.r_leg_kn_p_p_gain ; online_walking->leg_angle_feed_back_[3].d_gain_ = msg.r_leg_kn_p_d_gain ; online_walking->leg_angle_feed_back_[4].p_gain_ = msg.r_leg_an_p_p_gain ; online_walking->leg_angle_feed_back_[4].d_gain_ = msg.r_leg_an_p_d_gain ; online_walking->leg_angle_feed_back_[5].p_gain_ = msg.r_leg_an_r_p_gain ; online_walking->leg_angle_feed_back_[5].d_gain_ = msg.r_leg_an_r_d_gain ; online_walking->leg_angle_feed_back_[6].p_gain_ = msg.l_leg_hip_y_p_gain ; online_walking->leg_angle_feed_back_[6].d_gain_ = msg.l_leg_hip_y_d_gain ; online_walking->leg_angle_feed_back_[7].p_gain_ = msg.l_leg_hip_r_p_gain ; online_walking->leg_angle_feed_back_[7].d_gain_ = msg.l_leg_hip_r_d_gain ; online_walking->leg_angle_feed_back_[8].p_gain_ = msg.l_leg_hip_p_p_gain ; online_walking->leg_angle_feed_back_[8].d_gain_ = msg.l_leg_hip_p_d_gain ; online_walking->leg_angle_feed_back_[9].p_gain_ = msg.l_leg_kn_p_p_gain ; online_walking->leg_angle_feed_back_[9].d_gain_ = msg.l_leg_kn_p_d_gain ; online_walking->leg_angle_feed_back_[10].p_gain_ = msg.l_leg_an_p_p_gain ; online_walking->leg_angle_feed_back_[10].d_gain_ = msg.l_leg_an_p_d_gain ; online_walking->leg_angle_feed_back_[11].p_gain_ = msg.l_leg_an_r_p_gain ; online_walking->leg_angle_feed_back_[11].d_gain_ = msg.l_leg_an_r_d_gain ; } void OnlineWalkingModule::updateJointFeedBackGain() { double current_update_gain = joint_feedback_update_polynomial_coeff_.coeff(0,0) * robotis_framework::powDI(joint_feedback_update_sys_time_, 5) + joint_feedback_update_polynomial_coeff_.coeff(1,0) * robotis_framework::powDI(joint_feedback_update_sys_time_ , 4) + joint_feedback_update_polynomial_coeff_.coeff(2,0) * robotis_framework::powDI(joint_feedback_update_sys_time_ , 3) + joint_feedback_update_polynomial_coeff_.coeff(3,0) * robotis_framework::powDI(joint_feedback_update_sys_time_ , 2) + joint_feedback_update_polynomial_coeff_.coeff(4,0) * robotis_framework::powDI(joint_feedback_update_sys_time_ , 1) + joint_feedback_update_polynomial_coeff_.coeff(5,0) ; current_joint_feedback_gain_.r_leg_hip_y_p_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_hip_y_p_gain - previous_joint_feedback_gain_.r_leg_hip_y_p_gain ) + previous_joint_feedback_gain_.r_leg_hip_y_p_gain ; current_joint_feedback_gain_.r_leg_hip_y_d_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_hip_y_d_gain - previous_joint_feedback_gain_.r_leg_hip_y_d_gain ) + previous_joint_feedback_gain_.r_leg_hip_y_d_gain ; current_joint_feedback_gain_.r_leg_hip_r_p_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_hip_r_p_gain - previous_joint_feedback_gain_.r_leg_hip_r_p_gain ) + previous_joint_feedback_gain_.r_leg_hip_r_p_gain ; current_joint_feedback_gain_.r_leg_hip_r_d_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_hip_r_d_gain - previous_joint_feedback_gain_.r_leg_hip_r_d_gain ) + previous_joint_feedback_gain_.r_leg_hip_r_d_gain ; current_joint_feedback_gain_.r_leg_hip_p_p_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_hip_p_p_gain - previous_joint_feedback_gain_.r_leg_hip_p_p_gain ) + previous_joint_feedback_gain_.r_leg_hip_p_p_gain ; current_joint_feedback_gain_.r_leg_hip_p_d_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_hip_p_d_gain - previous_joint_feedback_gain_.r_leg_hip_p_d_gain ) + previous_joint_feedback_gain_.r_leg_hip_p_d_gain ; current_joint_feedback_gain_.r_leg_kn_p_p_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_kn_p_p_gain - previous_joint_feedback_gain_.r_leg_kn_p_p_gain ) + previous_joint_feedback_gain_.r_leg_kn_p_p_gain ; current_joint_feedback_gain_.r_leg_kn_p_d_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_kn_p_d_gain - previous_joint_feedback_gain_.r_leg_kn_p_d_gain ) + previous_joint_feedback_gain_.r_leg_kn_p_d_gain ; current_joint_feedback_gain_.r_leg_an_p_p_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_an_p_p_gain - previous_joint_feedback_gain_.r_leg_an_p_p_gain ) + previous_joint_feedback_gain_.r_leg_an_p_p_gain ; current_joint_feedback_gain_.r_leg_an_p_d_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_an_p_d_gain - previous_joint_feedback_gain_.r_leg_an_p_d_gain ) + previous_joint_feedback_gain_.r_leg_an_p_d_gain ; current_joint_feedback_gain_.r_leg_an_r_p_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_an_r_p_gain - previous_joint_feedback_gain_.r_leg_an_r_p_gain ) + previous_joint_feedback_gain_.r_leg_an_r_p_gain ; current_joint_feedback_gain_.r_leg_an_r_d_gain = current_update_gain*(desired_joint_feedback_gain_.r_leg_an_r_d_gain - previous_joint_feedback_gain_.r_leg_an_r_d_gain ) + previous_joint_feedback_gain_.r_leg_an_r_d_gain ; current_joint_feedback_gain_.l_leg_hip_y_p_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_hip_y_p_gain - previous_joint_feedback_gain_.l_leg_hip_y_p_gain ) + previous_joint_feedback_gain_.l_leg_hip_y_p_gain ; current_joint_feedback_gain_.l_leg_hip_y_d_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_hip_y_d_gain - previous_joint_feedback_gain_.l_leg_hip_y_d_gain ) + previous_joint_feedback_gain_.l_leg_hip_y_d_gain ; current_joint_feedback_gain_.l_leg_hip_r_p_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_hip_r_p_gain - previous_joint_feedback_gain_.l_leg_hip_r_p_gain ) + previous_joint_feedback_gain_.l_leg_hip_r_p_gain ; current_joint_feedback_gain_.l_leg_hip_r_d_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_hip_r_d_gain - previous_joint_feedback_gain_.l_leg_hip_r_d_gain ) + previous_joint_feedback_gain_.l_leg_hip_r_d_gain ; current_joint_feedback_gain_.l_leg_hip_p_p_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_hip_p_p_gain - previous_joint_feedback_gain_.l_leg_hip_p_p_gain ) + previous_joint_feedback_gain_.l_leg_hip_p_p_gain ; current_joint_feedback_gain_.l_leg_hip_p_d_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_hip_p_d_gain - previous_joint_feedback_gain_.l_leg_hip_p_d_gain ) + previous_joint_feedback_gain_.l_leg_hip_p_d_gain ; current_joint_feedback_gain_.l_leg_kn_p_p_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_kn_p_p_gain - previous_joint_feedback_gain_.l_leg_kn_p_p_gain ) + previous_joint_feedback_gain_.l_leg_kn_p_p_gain ; current_joint_feedback_gain_.l_leg_kn_p_d_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_kn_p_d_gain - previous_joint_feedback_gain_.l_leg_kn_p_d_gain ) + previous_joint_feedback_gain_.l_leg_kn_p_d_gain ; current_joint_feedback_gain_.l_leg_an_p_p_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_an_p_p_gain - previous_joint_feedback_gain_.l_leg_an_p_p_gain ) + previous_joint_feedback_gain_.l_leg_an_p_p_gain ; current_joint_feedback_gain_.l_leg_an_p_d_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_an_p_d_gain - previous_joint_feedback_gain_.l_leg_an_p_d_gain ) + previous_joint_feedback_gain_.l_leg_an_p_d_gain ; current_joint_feedback_gain_.l_leg_an_r_p_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_an_r_p_gain - previous_joint_feedback_gain_.l_leg_an_r_p_gain ) + previous_joint_feedback_gain_.l_leg_an_r_p_gain ; current_joint_feedback_gain_.l_leg_an_r_d_gain = current_update_gain*(desired_joint_feedback_gain_.l_leg_an_r_d_gain - previous_joint_feedback_gain_.l_leg_an_r_d_gain ) + previous_joint_feedback_gain_.l_leg_an_r_d_gain ; setJointFeedBackGain(current_joint_feedback_gain_); } bool OnlineWalkingModule::checkBalanceOnOff() { if(gazebo_) return true; THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); if ((fabs(online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.foot_roll_angle_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.foot_roll_angle_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_force_x_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_force_y_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_force_z_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_force_x_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_force_y_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_force_z_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_force_x_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_force_y_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_force_z_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_torque_roll_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_torque_pitch_ctrl_.p_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_force_x_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_force_y_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_force_z_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_torque_roll_ctrl_.d_gain_ ) < 1e-7) && (fabs(online_walking->balance_ctrl_.left_foot_torque_pitch_ctrl_.d_gain_ ) < 1e-7)) { return false; } else return true; } bool OnlineWalkingModule::removeExistingStepDataServiceCallback(thormang3_walking_module_msgs::RemoveExistingStepData::Request &req, thormang3_walking_module_msgs::RemoveExistingStepData::Response &res) { THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); res.result = thormang3_walking_module_msgs::RemoveExistingStepData::Response::NO_ERROR; if(isRunning()) { res.result |= thormang3_walking_module_msgs::RemoveExistingStepData::Response::ROBOT_IS_WALKING_NOW; } else { int exist_num_of_step_data = online_walking->getNumofRemainingUnreservedStepData(); if(exist_num_of_step_data != 0) for(int remove_count = 0; remove_count < exist_num_of_step_data; remove_count++) online_walking->eraseLastStepData(); } return true; } void OnlineWalkingModule::imuDataOutputCallback(const sensor_msgs::Imu::ConstPtr &msg) { THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); online_walking->setCurrentIMUSensorOutput(-1.0*(msg->angular_velocity.x), -1.0*(msg->angular_velocity.y), msg->orientation.x, msg->orientation.y, msg->orientation.z, msg->orientation.w); } void OnlineWalkingModule::onModuleEnable() { std::string status_msg = WalkingStatusMSG::WALKING_MODULE_IS_ENABLED_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, status_msg); } void OnlineWalkingModule::onModuleDisable() { previous_running_ = present_running = false; THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); std::string status_msg = WalkingStatusMSG::WALKING_MODULE_IS_DISABLED_MSG; balance_update_with_loop_ = false; online_walking->leg_angle_feed_back_[0].p_gain_ = 0; online_walking->leg_angle_feed_back_[0].d_gain_ = 0; online_walking->leg_angle_feed_back_[1].p_gain_ = 0; online_walking->leg_angle_feed_back_[1].d_gain_ = 0; online_walking->leg_angle_feed_back_[2].p_gain_ = 0; online_walking->leg_angle_feed_back_[2].d_gain_ = 0; online_walking->leg_angle_feed_back_[3].p_gain_ = 0; online_walking->leg_angle_feed_back_[3].d_gain_ = 0; online_walking->leg_angle_feed_back_[4].p_gain_ = 0; online_walking->leg_angle_feed_back_[4].d_gain_ = 0; online_walking->leg_angle_feed_back_[5].p_gain_ = 0; online_walking->leg_angle_feed_back_[5].d_gain_ = 0; online_walking->leg_angle_feed_back_[6].p_gain_ = 0; online_walking->leg_angle_feed_back_[6].d_gain_ = 0; online_walking->leg_angle_feed_back_[7].p_gain_ = 0; online_walking->leg_angle_feed_back_[7].d_gain_ = 0; online_walking->leg_angle_feed_back_[8].p_gain_ = 0; online_walking->leg_angle_feed_back_[8].d_gain_ = 0; online_walking->leg_angle_feed_back_[9].p_gain_ = 0; online_walking->leg_angle_feed_back_[9].d_gain_ = 0; online_walking->leg_angle_feed_back_[10].p_gain_ = 0; online_walking->leg_angle_feed_back_[10].d_gain_ = 0; online_walking->leg_angle_feed_back_[11].p_gain_ = 0; online_walking->leg_angle_feed_back_[11].d_gain_ = 0; online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.foot_roll_gyro_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.foot_pitch_gyro_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.foot_roll_angle_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.foot_roll_angle_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.foot_pitch_angle_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_x_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_y_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_z_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_x_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_y_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_force_z_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_torque_roll_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.right_foot_torque_pitch_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.left_foot_force_x_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.left_foot_force_y_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.left_foot_force_z_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.left_foot_torque_roll_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.left_foot_torque_pitch_ctrl_.p_gain_ = 0; online_walking->balance_ctrl_.left_foot_force_x_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.left_foot_force_y_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.left_foot_force_z_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.left_foot_torque_roll_ctrl_.d_gain_ = 0; online_walking->balance_ctrl_.left_foot_torque_pitch_ctrl_.d_gain_ = 0; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, status_msg); } void OnlineWalkingModule::process(std::map<std::string, robotis_framework::Dynamixel *> dxls, std::map<std::string, double> sensors) { if(enable_ == false) return; THORMANG3OnlineWalking *online_walking = THORMANG3OnlineWalking::getInstance(); r_foot_fx_N_ = sensors["r_foot_fx_scaled_N"]; r_foot_fy_N_ = sensors["r_foot_fy_scaled_N"]; r_foot_fz_N_ = sensors["r_foot_fz_scaled_N"]; r_foot_Tx_Nm_ = sensors["r_foot_tx_scaled_Nm"]; r_foot_Ty_Nm_ = sensors["r_foot_ty_scaled_Nm"]; r_foot_Tz_Nm_ = sensors["r_foot_tz_scaled_Nm"]; l_foot_fx_N_ = sensors["l_foot_fx_scaled_N"]; l_foot_fy_N_ = sensors["l_foot_fy_scaled_N"]; l_foot_fz_N_ = sensors["l_foot_fz_scaled_N"]; l_foot_Tx_Nm_ = sensors["l_foot_tx_scaled_Nm"]; l_foot_Ty_Nm_ = sensors["l_foot_ty_scaled_Nm"]; l_foot_Tz_Nm_ = sensors["l_foot_tz_scaled_Nm"]; r_foot_fx_N_ = robotis_framework::sign(r_foot_fx_N_) * fmin( fabs(r_foot_fx_N_), 2000.0); r_foot_fy_N_ = robotis_framework::sign(r_foot_fy_N_) * fmin( fabs(r_foot_fy_N_), 2000.0); r_foot_fz_N_ = robotis_framework::sign(r_foot_fz_N_) * fmin( fabs(r_foot_fz_N_), 2000.0); r_foot_Tx_Nm_ = robotis_framework::sign(r_foot_Tx_Nm_) *fmin(fabs(r_foot_Tx_Nm_), 300.0); r_foot_Ty_Nm_ = robotis_framework::sign(r_foot_Ty_Nm_) *fmin(fabs(r_foot_Ty_Nm_), 300.0); r_foot_Tz_Nm_ = robotis_framework::sign(r_foot_Tz_Nm_) *fmin(fabs(r_foot_Tz_Nm_), 300.0); l_foot_fx_N_ = robotis_framework::sign(l_foot_fx_N_) * fmin( fabs(l_foot_fx_N_), 2000.0); l_foot_fy_N_ = robotis_framework::sign(l_foot_fy_N_) * fmin( fabs(l_foot_fy_N_), 2000.0); l_foot_fz_N_ = robotis_framework::sign(l_foot_fz_N_) * fmin( fabs(l_foot_fz_N_), 2000.0); l_foot_Tx_Nm_ = robotis_framework::sign(l_foot_Tx_Nm_) *fmin(fabs(l_foot_Tx_Nm_), 300.0); l_foot_Ty_Nm_ = robotis_framework::sign(l_foot_Ty_Nm_) *fmin(fabs(l_foot_Ty_Nm_), 300.0); l_foot_Tz_Nm_ = robotis_framework::sign(l_foot_Tz_Nm_) *fmin(fabs(l_foot_Tz_Nm_), 300.0); if(balance_update_with_loop_ == true) { balance_update_sys_time_ += control_cycle_msec_ * 0.001; if(balance_update_sys_time_ >= balance_update_duration_ ) { balance_update_sys_time_ = balance_update_duration_; balance_update_with_loop_ = false; setBalanceParam(desired_balance_param_); std::string status_msg = WalkingStatusMSG::BALANCE_PARAM_SETTING_FINISHED_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, status_msg); publishDoneMsg("walking_balance"); } else { updateBalanceParam(); } } if(joint_feedback_update_with_loop_ == true) { joint_feedback_update_sys_time_ += control_cycle_msec_ * 0.001; if(joint_feedback_update_sys_time_ >= joint_feedback_update_duration_ ) { joint_feedback_update_sys_time_ = joint_feedback_update_duration_; joint_feedback_update_with_loop_ = false; setJointFeedBackGain(desired_joint_feedback_gain_); publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, WalkingStatusMSG::JOINT_FEEDBACK_GAIN_UPDATE_FINISHED_MSG); publishDoneMsg("walking_joint_feedback"); } else { updateJointFeedBackGain(); } } online_walking->current_right_fx_N_ = r_foot_fx_N_; online_walking->current_right_fy_N_ = r_foot_fy_N_; online_walking->current_right_fz_N_ = r_foot_fz_N_; online_walking->current_right_tx_Nm_ = r_foot_Tx_Nm_; online_walking->current_right_ty_Nm_ = r_foot_Ty_Nm_; online_walking->current_right_tz_Nm_ = r_foot_Tz_Nm_; online_walking->current_left_fx_N_ = l_foot_fx_N_; online_walking->current_left_fy_N_ = l_foot_fy_N_; online_walking->current_left_fz_N_ = l_foot_fz_N_; online_walking->current_left_tx_Nm_ = l_foot_Tx_Nm_; online_walking->current_left_ty_Nm_ = l_foot_Ty_Nm_; online_walking->current_left_tz_Nm_ = l_foot_Tz_Nm_; online_walking->curr_angle_rad_[0] = result_["r_leg_hip_y"]->goal_position_; online_walking->curr_angle_rad_[1] = result_["r_leg_hip_r"]->goal_position_; online_walking->curr_angle_rad_[2] = result_["r_leg_hip_p"]->goal_position_; online_walking->curr_angle_rad_[3] = result_["r_leg_kn_p" ]->goal_position_; online_walking->curr_angle_rad_[4] = result_["r_leg_an_p" ]->goal_position_; online_walking->curr_angle_rad_[5] = result_["r_leg_an_r" ]->goal_position_; online_walking->curr_angle_rad_[6] = result_["l_leg_hip_y"]->goal_position_; online_walking->curr_angle_rad_[7] = result_["l_leg_hip_r"]->goal_position_; online_walking->curr_angle_rad_[8] = result_["l_leg_hip_p"]->goal_position_; online_walking->curr_angle_rad_[9] = result_["l_leg_kn_p" ]->goal_position_; online_walking->curr_angle_rad_[10] = result_["l_leg_an_p" ]->goal_position_; online_walking->curr_angle_rad_[11] = result_["l_leg_an_r" ]->goal_position_; for(std::map<std::string, robotis_framework::DynamixelState*>::iterator result_it = result_.begin(); result_it != result_.end(); result_it++) { std::map<std::string, robotis_framework::Dynamixel*>::iterator dxls_it = dxls.find(result_it->first); if(dxls_it != dxls.end()) online_walking->curr_angle_rad_[joint_name_to_index_[result_it->first]] = dxls_it->second->dxl_state_->present_position_; } process_mutex_.lock(); online_walking->process(); desired_matrix_g_to_cob_ = online_walking->mat_g_to_cob_; desired_matrix_g_to_rfoot_ = online_walking->mat_g_to_rfoot_; desired_matrix_g_to_lfoot_ = online_walking->mat_g_to_lfoot_; process_mutex_.unlock(); publishRobotPose(); result_["r_leg_hip_y"]->goal_position_ = online_walking->out_angle_rad_[0]; result_["r_leg_hip_r"]->goal_position_ = online_walking->out_angle_rad_[1]; result_["r_leg_hip_p"]->goal_position_ = online_walking->out_angle_rad_[2]; result_["r_leg_kn_p" ]->goal_position_ = online_walking->out_angle_rad_[3]; result_["r_leg_an_p" ]->goal_position_ = online_walking->out_angle_rad_[4]; result_["r_leg_an_r" ]->goal_position_ = online_walking->out_angle_rad_[5]; result_["l_leg_hip_y"]->goal_position_ = online_walking->out_angle_rad_[6]; result_["l_leg_hip_r"]->goal_position_ = online_walking->out_angle_rad_[7]; result_["l_leg_hip_p"]->goal_position_ = online_walking->out_angle_rad_[8]; result_["l_leg_kn_p" ]->goal_position_ = online_walking->out_angle_rad_[9]; result_["l_leg_an_p" ]->goal_position_ = online_walking->out_angle_rad_[10]; result_["l_leg_an_r" ]->goal_position_ = online_walking->out_angle_rad_[11]; #ifdef WALKING_TUNE walking_joint_states_msg_.header.stamp = ros::Time::now(); walking_joint_states_msg_.r_goal_hip_y = online_walking->r_leg_out_angle_rad_[0]; walking_joint_states_msg_.r_goal_hip_r = online_walking->r_leg_out_angle_rad_[1]; walking_joint_states_msg_.r_goal_hip_p = online_walking->r_leg_out_angle_rad_[2]; walking_joint_states_msg_.r_goal_kn_p = online_walking->r_leg_out_angle_rad_[3]; walking_joint_states_msg_.r_goal_an_p = online_walking->r_leg_out_angle_rad_[4]; walking_joint_states_msg_.r_goal_an_r = online_walking->r_leg_out_angle_rad_[5]; walking_joint_states_msg_.l_goal_hip_y = online_walking->l_leg_out_angle_rad_[0]; walking_joint_states_msg_.l_goal_hip_r = online_walking->l_leg_out_angle_rad_[1]; walking_joint_states_msg_.l_goal_hip_p = online_walking->l_leg_out_angle_rad_[2]; walking_joint_states_msg_.l_goal_kn_p = online_walking->l_leg_out_angle_rad_[3]; walking_joint_states_msg_.l_goal_an_p = online_walking->l_leg_out_angle_rad_[4]; walking_joint_states_msg_.l_goal_an_r = online_walking->l_leg_out_angle_rad_[5]; walking_joint_states_msg_.r_present_hip_y = online_walking->curr_angle_rad_[0]; walking_joint_states_msg_.r_present_hip_r = online_walking->curr_angle_rad_[1]; walking_joint_states_msg_.r_present_hip_p = online_walking->curr_angle_rad_[2]; walking_joint_states_msg_.r_present_kn_p = online_walking->curr_angle_rad_[3]; walking_joint_states_msg_.r_present_an_p = online_walking->curr_angle_rad_[4]; walking_joint_states_msg_.r_present_an_r = online_walking->curr_angle_rad_[5]; walking_joint_states_msg_.l_present_hip_y = online_walking->curr_angle_rad_[6]; walking_joint_states_msg_.l_present_hip_r = online_walking->curr_angle_rad_[7]; walking_joint_states_msg_.l_present_hip_p = online_walking->curr_angle_rad_[8]; walking_joint_states_msg_.l_present_kn_p = online_walking->curr_angle_rad_[9]; walking_joint_states_msg_.l_present_an_p = online_walking->curr_angle_rad_[10]; walking_joint_states_msg_.l_present_an_r = online_walking->curr_angle_rad_[11]; walking_joint_states_pub_.publish(walking_joint_states_msg_); #endif present_running = isRunning(); if(previous_running_ != present_running) { if(present_running == true) { std::string status_msg = WalkingStatusMSG::WALKING_START_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, status_msg); } else { std::string status_msg = WalkingStatusMSG::WALKING_FINISH_MSG; publishStatusMsg(robotis_controller_msgs::StatusMsg::STATUS_INFO, status_msg); publishDoneMsg("walking_completed"); } } previous_running_ = present_running; } void OnlineWalkingModule::stop() { return; }
60.508234
270
0.782865
[ "vector" ]
791712de9301c6a240e3c136fc8da40807728735
13,237
cpp
C++
GIDI/Src/GIDI_settings_group.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
GIDI/Src/GIDI_settings_group.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
GIDI/Src/GIDI_settings_group.cpp
Mathnerd314/gidiplus
ed4c48ab399a964fe782f73d0a065849b00090bb
[ "MIT-0", "MIT" ]
null
null
null
/* # <<BEGIN-copyright>> # Copyright 2019, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: MIT # <<END-copyright>> */ #include <iostream> #include <stdio.h> #include <stdlib.h> #include "GIDI.hpp" namespace GIDI { namespace Transporting { /*! \class MultiGroup * Specifies the flux data for a specified Legendre order (see class Flux). */ /* *********************************************************************************************************//** ***********************************************************************************************************/ MultiGroup::MultiGroup( ) { } /* *********************************************************************************************************//** * @param a_label [in] The label for the MultiGroup. * @param a_length [in] The number of boundaries values. * @param a_boundaries [in] The list of boundaries. ***********************************************************************************************************/ MultiGroup::MultiGroup( std::string const &a_label, int a_length, double const *a_boundaries ) : m_label( a_label ) { for( int i1 = 0; i1 < a_length; ++i1 ) m_boundaries.push_back( a_boundaries[i1] ); } /* *********************************************************************************************************//** * @param a_label [in] The label for the MultiGroup. * @param a_boundaries [in] The list of boundaries. ***********************************************************************************************************/ MultiGroup::MultiGroup( std::string const &a_label, std::vector<double> const &a_boundaries ) : m_label( a_label ), m_boundaries( a_boundaries ) { } /* *********************************************************************************************************//** * @param a_group [in] The Group used to set *this*. ***********************************************************************************************************/ MultiGroup::MultiGroup( Group const &a_group ) : m_label( a_group.label( ) ), m_boundaries( a_group.data( ) ) { } /* *********************************************************************************************************//** * @param a_multiGroup [in] The MultiGroup instance to copy. ***********************************************************************************************************/ MultiGroup::MultiGroup( MultiGroup const &a_multiGroup ) : m_label( a_multiGroup.label( ) ), m_boundaries( a_multiGroup.boundaries( ) ) { } /* *********************************************************************************************************//** ***********************************************************************************************************/ MultiGroup::~MultiGroup( ) { } /* *********************************************************************************************************//** * Returns the multi-group index whose boundaries enclose *a_energy*. If *a_encloseOutOfRange* is true and * *a_energy* is below the lowest boundary, 0 is returned, otherwise -2 is returned. If *a_encloseOutOfRange* is true and * *a_energy* is above the highest boundary, the last multi-group index is returned, otherwise -1 is returned. * * @param a_energy [in] The energy of the whose index is to be returned. * @param a_encloseOutOfRange Determines the action if energy is below or above the domain of the boundaries. * @return The index whose boundaries enclose *a_energy*. ***********************************************************************************************************/ int MultiGroup::multiGroupIndexFromEnergy( double a_energy, bool a_encloseOutOfRange ) const { int iMin = 0, iMid, iMax = (int) m_boundaries.size( ), iMaxM1 = iMax - 1; if( iMax == 0 ) return( -3 ); if( a_energy < m_boundaries[0] ) { if( a_encloseOutOfRange ) return( 0 ); return( -2 ); } if( a_energy > m_boundaries[iMaxM1] ) { if( a_encloseOutOfRange ) return( iMax - 2 ); return( -1 ); } while( 1 ) { iMid = ( iMin + iMax ) >> 1; if( iMid == iMin ) break; if( a_energy < m_boundaries[iMid] ) { iMax = iMid; } else { iMin = iMid; } } if( iMin == iMaxM1 ) iMin--; return( iMin ); } /* *********************************************************************************************************//** * @param a_label [in] The label for *this*. * @param a_boundaries [in] The boundaries to set *this* to. ***********************************************************************************************************/ void MultiGroup::set( std::string const &a_label, std::vector<double> const &a_boundaries ) { m_label = a_label; m_boundaries = a_boundaries; } /* *********************************************************************************************************//** * Print the MultiGroup to std::cout. Mainly for debugging. * * @param a_indent [in] The std::string to print at the beginning. * @param a_outline [in] If true, does not print the flux values. * @param a_valuesPerLine [in] The number of points (i.e., energy, flux pairs) to print per line. ***********************************************************************************************************/ void MultiGroup::print( std::string const &a_indent, bool a_outline, int a_valuesPerLine ) const { int nbs = size( ); char buffer[128]; bool printIndent( true ); std::cout << a_indent << "GROUP: label = '" << m_label << "': length = " << nbs << std::endl; if( a_outline ) return; for( int ib = 0; ib < nbs; ib++ ) { if( printIndent ) std::cout << a_indent; printIndent = false; sprintf( buffer, "%16.8e", m_boundaries[ib] ); std::cout << buffer; if( ( ( ib + 1 ) % a_valuesPerLine ) == 0 ) { std::cout << std::endl; printIndent = true; } } if( nbs % a_valuesPerLine ) std::cout << std::endl; } /*! \class Groups_from_bdfls * Specifies the data for a specified Legendre order (see class Flux). */ /* *********************************************************************************************************//** * Reads in multi-group data from a *bdfls* file as a list of MultiGroup instances. * * @param a_fileName [in] The *bdfls* file name. ***********************************************************************************************************/ Groups_from_bdfls::Groups_from_bdfls( std::string const &a_fileName ) { initialize( a_fileName.c_str( ) ); } /* *********************************************************************************************************//** * Reads in multi-group data from a *bdfls* file as a list of MultiGroup instances. * * @param a_fileName [in] The *bdfls* file name. ***********************************************************************************************************/ Groups_from_bdfls::Groups_from_bdfls( char const *a_fileName ) { initialize( a_fileName ); } /* *********************************************************************************************************//** * Used by constructors to do most of the work. * * @param a_fileName [in] The *bdfls* file name. ***********************************************************************************************************/ void Groups_from_bdfls::initialize( char const *a_fileName ) { char buffer[132], *pEnd, cValue[16]; FILE *fIn = fopen( a_fileName, "r" ); if( fIn == nullptr ) throw Exception( "Groups_from_bdfls::initialize: Could not open bdfls file." ); while( true ) { int gid( -1 ); if( fgets( buffer, 132, fIn ) == nullptr ) throw Exception( "Groups_from_bdfls::initialize: fgets failed for gid." ); if( strlen( buffer ) > 73 ) { if( buffer[72] == '1' ) break; } gid = (int) strtol( buffer, &pEnd, 10 ); if( gid == -1 ) throw Exception( "Groups_from_bdfls::initialize: converting gid to long failed." ); std::string label( LLNL_gidToLabel( gid ) ); long numberOfBoundaries( -1 ); if( fgets( buffer, 132, fIn ) == nullptr ) throw Exception( "Groups_from_bdfls::initialize: fgets failed for numberOfBoundaries." ); numberOfBoundaries = strtol( buffer, &pEnd, 10 ); if( numberOfBoundaries == -1 ) throw Exception( "Groups_from_bdfls::initialize: converting gid to long failed." ); long index( 0 ); std::vector<double> boundaries( numberOfBoundaries ); while( numberOfBoundaries > 0 ) { long i1, n1( 6 ); if( numberOfBoundaries < 6 ) n1 = numberOfBoundaries; if( fgets( buffer, 132, fIn ) == nullptr ) throw Exception( "Groups_from_bdfls::initialize: fgets failed for boundaries." ); for( i1 = 0; i1 < n1; ++i1, ++index ) { strncpy( cValue, &buffer[12*i1], 12 ); cValue[12] = 0; boundaries[index] = strtod( cValue, &pEnd ); } numberOfBoundaries -= n1; } m_multiGroups.push_back( MultiGroup( label, boundaries ) ); } fclose( fIn ); } /* *********************************************************************************************************//** ***********************************************************************************************************/ Groups_from_bdfls::~Groups_from_bdfls( ) { } /* *********************************************************************************************************//** * Returns the MultiGroup whose *label* is *a_label*. * * @param a_label [in] The *label* of the MultiGroup to return. * @return Returns the MultiGroup whose *label* is *a_label*. ***********************************************************************************************************/ MultiGroup Groups_from_bdfls::viaLabel( std::string const &a_label ) const { for( int ig = 0; ig < (int) m_multiGroups.size( ); ++ig ) { if( m_multiGroups[ig].label( ) == a_label ) return( m_multiGroups[ig] ); } throw Exception( "Groups_from_bdfls::viaLabel: label not found." ); } /* *********************************************************************************************************//** * Returns the MultiGroup whose *gid* is *a_gid*. * * @param a_gid [in] The bdfls *gid*. * @return Returns the MultiGroup whose *label* is *a_label*. ***********************************************************************************************************/ MultiGroup Groups_from_bdfls::getViaGID( int a_gid ) const { std::string label( LLNL_gidToLabel( a_gid ) ); return( viaLabel( label ) ); } /* *********************************************************************************************************//** * Returns a list of *label*'s for all the MultiGroup's present in *this*. * * @return Returns the MultiGroup whose *label* is *a_label*. ***********************************************************************************************************/ std::vector<std::string> Groups_from_bdfls::labels( ) const { int size = (int) m_multiGroups.size( ); std::vector<std::string> _labels( size ); for( int if1 = 0; if1 < size; ++if1 ) _labels[if1] = m_multiGroups[if1].label( ); return( _labels ); } /* *********************************************************************************************************//** * Returns a list of *gid*'s for all the MultiGroup's present in *this*. * * @return The list of *gid*'s. ***********************************************************************************************************/ std::vector<int> Groups_from_bdfls::GIDs( ) const { int size = (int) m_multiGroups.size( ); std::vector<int> fids( size ); char *e; for( int if1 = 0; if1 < size; ++if1 ) { fids[if1] = (int) strtol( &(m_multiGroups[if1].label( ).c_str( )[9]), &e, 10 ); } return( fids ); } /* *********************************************************************************************************//** * Print each MultiGroup to std::cout in *this*. Mainly for debugging. * * @param a_outline [in] Passed to each MultiGroup print method. * @param a_valuesPerLine [in] Passed to each MultiGroup print method. ***********************************************************************************************************/ void Groups_from_bdfls::print( bool a_outline, int a_valuesPerLine ) const { int ngs = (int) m_multiGroups.size( ); std::cout << "BDFLS GROUPs: number of groups = " << ngs << std::endl; for( int if1 = 0; if1 < ngs ; ++if1 ) m_multiGroups[if1].print( " ", a_outline, a_valuesPerLine ); } } }
41.889241
140
0.422679
[ "vector" ]
791fc47e3779758b0dac704df183ffd3937bda13
934
cpp
C++
core/Storage.cpp
fyrdahl/gadgetron
4619ff9277758ed18787df23edc5b9fe40d38f95
[ "MIT" ]
null
null
null
core/Storage.cpp
fyrdahl/gadgetron
4619ff9277758ed18787df23edc5b9fe40d38f95
[ "MIT" ]
null
null
null
core/Storage.cpp
fyrdahl/gadgetron
4619ff9277758ed18787df23edc5b9fe40d38f95
[ "MIT" ]
null
null
null
#include "Storage.h" #include <boost/iostreams/device/array.hpp> #include <boost/iostreams/device/back_inserter.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <boost/iostreams/stream.hpp> namespace bio = boost::iostreams; namespace Gadgetron::Storage { GenericStorageSpace::GenericStorageSpace( std::shared_ptr<StreamProvider> provider, const Core::optional<std::string>& subject, boost::posix_time::time_duration default_duration ) : subject{subject},provider(std::move(provider)), default_duration{default_duration} {} std::unique_ptr<std::istream> istream_from_data(const std::vector<char> &data) { return std::make_unique<bio::stream<bio::array_source>>(data.data(),data.size()); } std::unique_ptr<std::ostream> ostream_view(std::vector<char> &data) { return std::make_unique<bio::stream<bio::back_insert_device<std::vector<char>>>>(data); } }
37.36
95
0.718415
[ "vector" ]
792219cb3a32d17b9e3ccb38ffe15cf17301a163
5,349
cpp
C++
simulation/robotVisualizationGR.cpp
lis-epfl/Tensoft-G21
7a83c5dabc12906c0a6bd1da0a28a131e9d5e144
[ "Apache-2.0" ]
1
2021-08-03T10:52:20.000Z
2021-08-03T10:52:20.000Z
simulation/robotVisualizationGR.cpp
lis-epfl/Tensoft-G21
7a83c5dabc12906c0a6bd1da0a28a131e9d5e144
[ "Apache-2.0" ]
null
null
null
simulation/robotVisualizationGR.cpp
lis-epfl/Tensoft-G21
7a83c5dabc12906c0a6bd1da0a28a131e9d5e144
[ "Apache-2.0" ]
1
2021-09-18T07:23:35.000Z
2021-09-18T07:23:35.000Z
/* * Copyright © 2012, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * All rights reserved. * * The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform is 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. */ /** * @author Enrico Zardini * @copyright Copyright (C) 2019 LIS * $Id$ */ // The C++ Standard Library #include <iostream> #include <fstream> #include <cstdlib> // NTRT core libraries for this app #include "ntrt/core/terrain/tgBoxGround.h" #include "ntrt/core/terrain/tgHillyGround.h" #include "ntrt/core/tgModel.h" #include "ntrt/core/tgSimViewGraphics.h" #include "ntrt/core/tgSimulation.h" #include "ntrt/core/tgWorld.h" // data logging libraries #include "ntrt/sensors/tgDataLogger2.h" #include "ntrt/sensors/tgRodSensorInfo.h" #include "ntrt/sensors/tgSpringCableActuatorSensorInfo.h" #include "robotModel.h" #include "targetModel.h" #include "robotControllerGR.h" /** * The entry point. * @param[in] argc the number of command-line arguments * @param[in] argv argv[0] is the executable name * @return 0 */ int main(int argc, char** argv) { const double yaw = 0.0; const double pitch = 0.0; const double roll = 0.0; const tgBoxGround::Config groundConfig(btVector3(yaw, pitch, roll)); tgBoxGround* ground = new tgBoxGround(groundConfig); const tgWorld::Config config(98.1); tgWorld world(config, ground); // set up simulation viewer const double timestep_physics = 0.001; // Seconds const double timestep_graphics = 1.f/60.f; // Seconds tgSimViewGraphics view(world, timestep_physics, timestep_graphics); tgSimulation simulation(view); // create the robot model (either from a conf file or from inline values) and the target model robotModel* rbModel = NULL; targetModel* tModel = NULL; // init time long init_time = 3000; if (argc >= 2) { // from conf files if (std::string(argv[1]) == "file") { // value 1 -> inform the model to read conf from file // advance argv of 2 to point to the conf filepath rbModel = new robotModel(1, argv + 2); if (argc >= 10) { int noiseType = atoi(argv[3]); double noiseLevel = atof(argv[4]); int seed = atoi(argv[5]); char *controller_path = argv[6]; rbModel->setMovDir(atoi(argv[7])); btVector3 targetPos(0.0, 0.0, 0.0); targetPos.setX(atof(argv[8])); targetPos.setZ(atof(argv[9])); tModel = new targetModel(targetPos); robotControllerGR *const pMuscleControl = new robotControllerGR(controller_path, tModel, init_time, noiseType, noiseLevel, seed); rbModel->attach(pMuscleControl); } else { std::cerr << "Wrong program usage." << "Review which parameters can be used." << std::endl; exit(2); } } else { // from command line if (std::string(argv[1]) == "in") { // Note: remember that this method requires also the position // where the robot will start moving as first parameter before its configuration rbModel = new robotModel(argc - 9, argv + 9); // noise related parameters int noiseType = atoi(argv[2]); double noiseLevel = atof(argv[3]); int seed = atoi(argv[4]); // controller path char* controller_path = argv[5]; // movement direction rbModel->setMovDir(atoi(argv[6])); // target position btVector3 targetPos(0.0, 0.0, 0.0); targetPos.setX(atof(argv[7])); targetPos.setZ(atof(argv[8])); tModel = new targetModel(targetPos); robotControllerGR* const pMuscleControl = new robotControllerGR(controller_path, tModel, init_time, noiseType, noiseLevel, seed); rbModel->attach(pMuscleControl); } else { std::cerr << "Wrong program usage." << "Review which parameters can be used." << std::endl; exit(2); } } } else { std::cerr << "Wrong program usage." << "Review which parameters can be used." << std::endl; exit(2); } // add the models to the simulation simulation.addModel(rbModel); simulation.addModel(tModel); // display the simulation and run it until exit key (q) is pressed simulation.run(); return 0; }
33.641509
111
0.596373
[ "model" ]
792d5d749015f019ea0bebe7cc919d15da2c721a
9,702
cpp
C++
cpp/oneapi/dal/algo/kmeans/test/spmd.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
188
2016-04-16T12:11:48.000Z
2018-01-12T12:42:55.000Z
cpp/oneapi/dal/algo/kmeans/test/spmd.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
1,198
2020-03-24T17:26:18.000Z
2022-03-31T08:06:15.000Z
cpp/oneapi/dal/algo/kmeans/test/spmd.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
93
2018-01-23T01:59:23.000Z
2020-03-16T11:04:19.000Z
/******************************************************************************* * Copyright 2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "oneapi/dal/algo/kmeans/test/data.hpp" #include "oneapi/dal/algo/kmeans/test/fixture.hpp" #include "oneapi/dal/test/engine/tables.hpp" #include "oneapi/dal/test/engine/io.hpp" namespace oneapi::dal::kmeans::test { template <typename TestType> class kmeans_spmd_test : public kmeans_test<TestType, kmeans_spmd_test<TestType>> { public: using base_t = kmeans_test<TestType, kmeans_spmd_test<TestType>>; using float_t = typename base_t::float_t; using train_input_t = typename base_t::train_input_t; using train_result_t = typename base_t::train_result_t; void set_rank_count(std::int64_t rank_count) { rank_count_ = rank_count; } template <typename... Args> train_result_t train_override(Args&&... args) { return this->train_via_spmd_threads_and_merge(rank_count_, std::forward<Args>(args)...); } template <typename... Args> std::vector<train_input_t> split_train_input_override(std::int64_t split_count, Args&&... args) { // Data table is distributed across the ranks, but // initial centroids are common for all the ranks const train_input_t input{ std::forward<Args>(args)... }; const auto split_data = te::split_table_by_rows<float_t>(this->get_policy(), input.get_data(), split_count); const auto common_centroids = input.get_initial_centroids(); std::vector<train_input_t> split_input; split_input.reserve(split_count); for (std::int64_t i = 0; i < split_count; i++) { split_input.push_back( // train_input_t{ split_data[i] } // .set_initial_centroids(common_centroids) // ); } return split_input; } train_result_t merge_train_result_override(const std::vector<train_result_t>& results) { // Responses are distributed accross the ranks, we combine them into one table; // Model, iteration_count, objective_function_value are the same for all ranks std::vector<table> responses; for (const auto& r : results) { responses.push_back(r.get_responses()); } const auto full_responses = te::stack_tables_by_rows<float_t>(responses); return train_result_t{} // .set_responses(full_responses) // .set_model(results[0].get_model()) // .set_iteration_count(results[0].get_iteration_count()) // .set_objective_function_value(results[0].get_objective_function_value()); } void check_if_results_same_on_all_ranks() { const auto table_id = this->get_homogen_table_id(); const auto data = gold_dataset::get_data().get_table(table_id); const auto initial_centroids = gold_dataset::get_initial_centroids().get_table(table_id); const std::int64_t cluster_count = gold_dataset::get_cluster_count(); const std::int64_t max_iteration_count = 100; const float_t accuracy_threshold = 0.0; INFO("create descriptor") const auto kmeans_desc = this->get_descriptor(cluster_count, max_iteration_count, accuracy_threshold); INFO("run training"); const auto train_results = this->train_via_spmd_threads(rank_count_, kmeans_desc, data, initial_centroids); INFO("check if all results bitwise equal on all ranks") { ONEDAL_ASSERT(train_results.size() > 0); const auto front_centroids = train_results.front().get_model().get_centroids(); const auto front_iteration_count = train_results.front().get_iteration_count(); const auto front_objective = train_results.front().get_objective_function_value(); for (const auto& result : train_results) { // We do not check responses as they are expected // to be different on each ranks INFO("check centroids") { const auto centroids = result.get_model().get_centroids(); te::check_if_tables_equal<float_t>(centroids, front_centroids); } INFO("check iterations") { REQUIRE(result.get_iteration_count() == front_iteration_count); } INFO("check objective function") { REQUIRE(result.get_objective_function_value() == front_objective); } } } } private: std::int64_t rank_count_ = 1; }; TEMPLATE_LIST_TEST_M(kmeans_spmd_test, "make sure results are the same on all ranks", "[spmd][smoke]", kmeans_types) { // SPMD mode is not implemented for CPU. The following `SKIP_IF` should be // removed once it's supported for CPU. The same for the rest of tests cases. SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->set_rank_count(GENERATE(2, 4)); this->check_if_results_same_on_all_ranks(); } TEMPLATE_LIST_TEST_M(kmeans_spmd_test, "distributed kmeans empty clusters test", "[spmd][smoke]", kmeans_types) { SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->set_rank_count(GENERATE(1, 2)); this->check_empty_clusters(); } TEMPLATE_LIST_TEST_M(kmeans_spmd_test, "distributed kmeans smoke train/infer test", "[spmd][smoke]", kmeans_types) { SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->set_rank_count(GENERATE(1, 2)); this->check_on_smoke_data(); } TEMPLATE_LIST_TEST_M(kmeans_spmd_test, "distributed kmeans train/infer on gold data", "[spmd][smoke]", kmeans_types) { SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->set_rank_count(GENERATE(1, 2, 4, 8)); this->check_on_gold_data(); } TEMPLATE_LIST_TEST_M(kmeans_spmd_test, "distributed kmeans block test", "[spmd][block][nightly]", kmeans_types) { SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->set_rank_count(GENERATE(1, 8)); this->check_on_large_data_with_one_cluster(); } TEMPLATE_LIST_TEST_M(kmeans_spmd_test, "distributed higgs: samples=1M, iters=3", "[kmeans][spmd][higgs][external-dataset]", kmeans_types) { SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->set_rank_count(10); const std::int64_t iters = 3; const std::string higgs_path = "workloads/higgs/dataset/higgs_1m_test.csv"; SECTION("clusters=10") { this->test_on_dataset(higgs_path, 10, iters, 3.1997724684, 14717484.0); } SECTION("clusters=100") { this->test_on_dataset(higgs_path, 100, iters, 2.7450205195, 10704352.0); } SECTION("cluster=250") { this->test_on_dataset(higgs_path, 250, iters, 2.5923397174, 9335216.0); } } TEMPLATE_LIST_TEST_M(kmeans_spmd_test, "distributed susy: samples=0.5M, iters=10", "[kmeans][nightly][spmd][susy][external-dataset]", kmeans_types) { SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->set_rank_count(10); const std::int64_t iters = 10; const std::string susy_path = "workloads/susy/dataset/susy_test.csv"; SECTION("clusters=10") { this->test_on_dataset(susy_path, 10, iters, 1.7730860782, 3183696.0); } SECTION("clusters=100") { this->test_on_dataset(susy_path, 100, iters, 1.9384844916, 1757022.625); } SECTION("cluster=250") { this->test_on_dataset(susy_path, 250, iters, 1.8950113604, 1400958.5); } } TEMPLATE_LIST_TEST_M(kmeans_spmd_test, "distributed epsilon: samples=80K, iters=2", "[kmeans][nightly][spmd][epsilon][external-dataset]", kmeans_types) { SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->set_rank_count(10); const std::int64_t iters = 2; const std::string epsilon_path = "workloads/epsilon/dataset/epsilon_80k_train.csv"; SECTION("clusters=512") { this->test_on_dataset(epsilon_path, 512, iters, 6.9367580565, 50128.640625, 1.0e-3); } // Disabled due to an issue /* SECTION("clusters=1024") { this->test_on_dataset(epsilon_path, 1024, iters, 5.59003873, 49518.75, 1.0e-3); } SECTION("cluster=2048") { this->test_on_dataset(epsilon_path, 2048, iters, 4.3202752143, 48437.6015625, 1.0e-3); } */ } } // namespace oneapi::dal::kmeans::test
37.030534
97
0.62616
[ "vector", "model" ]
79320e05891fb68971e4f9713a43b125a562a367
1,661
cxx
C++
mlearn/functional/CC_FUNC/src/conv.cxx
EequalsMCsquare/mlearn
bee79618fb80568b99bc2eefcd97dab33967ee12
[ "MIT" ]
2
2019-12-13T16:06:24.000Z
2020-01-04T13:44:08.000Z
mlearn/functional/CC_FUNC/src/conv.cxx
EequalsMCsquare/mlearn
bee79618fb80568b99bc2eefcd97dab33967ee12
[ "MIT" ]
null
null
null
mlearn/functional/CC_FUNC/src/conv.cxx
EequalsMCsquare/mlearn
bee79618fb80568b99bc2eefcd97dab33967ee12
[ "MIT" ]
null
null
null
#include <cstddef> #include <omp.h> #include <iostream> extern "C" { void dot_sum(double *result, double *x, double *w, std::size_t *length); } // inline void dotSum(double &result, double *t1, double *t2, std::size_t &length){ // result = 0; // std::size_t i; // // TODO: 这里用smid重写 // for(i = 0; i < length; i++) // result += t1[i] * t2[i]; // } inline void sampleConv2d(double *sample_result, double *x, double *w, std::size_t *shapes, std::size_t &out_channels){ // x shape => (24, 24, 3, 5, 5) // w shape => (16, 3, 5, 5) // b shape => (16) // sample_result已经被malloc过 std::size_t _temp_ = shapes[0] * shapes[1]; std::size_t _strides_ = shapes[2] * shapes[3] * shapes[4]; std::size_t idx_1, idx_2; for (std::size_t k = 0; k < out_channels; k++){ idx_1 = k * _temp_; idx_2 = k * _strides_; for(std::size_t i = 0; i < _temp_; i++) dot_sum(&sample_result[idx_1 + i], &x[i * _strides_], &w[idx_2], &_strides_); } } void batchConv2d(double *batch_result, double *x, double *w, std::size_t *shapes, std::size_t &out_channels){ // x_shape => (32,24,24,3,5,5) // result_shape => (32,16,24,24) // batch_result已经被malloc了 const unsigned int x_strides = shapes[1] * shapes[2] * shapes[3] * shapes[4] * shapes[5]; const unsigned int result_strides = out_channels * shapes[1] * shapes[2]; #pragma omp parallel for num_threads(omp_get_num_procs()) for (std::size_t i = 0; i < shapes[0]; i++) sampleConv2d(&batch_result[i * result_strides], &x[i * x_strides], w, &shapes[1], out_channels); }
29.140351
93
0.585792
[ "shape" ]
a6ad38c93c13e139cd8efb29196a6ef49aeeb2e8
727
hpp
C++
include/EmbGen/Utils.hpp
xxAtrain223/EmbGen
eeb949a3402b067960f3b577e4ece1757366fc16
[ "MIT" ]
null
null
null
include/EmbGen/Utils.hpp
xxAtrain223/EmbGen
eeb949a3402b067960f3b577e4ece1757366fc16
[ "MIT" ]
1
2020-01-09T03:12:58.000Z
2020-01-09T03:12:58.000Z
include/EmbGen/Utils.hpp
xxAtrain223/EmbGen
eeb949a3402b067960f3b577e4ece1757366fc16
[ "MIT" ]
null
null
null
#ifndef EMBGEN_UTILS_HPP #define EMBGEN_UTILS_HPP #include <algorithm> #include <vector> #include <map> namespace emb { namespace gen { template<typename K, typename V> K selectFirst(std::pair<K, V> pair) { return pair.first; } template<typename K, typename V> V selectSecond(std::pair<K, V> pair) { return pair.second; } template<typename K, typename V> std::vector<K> getMapKeys(std::map<K, V> map) { std::vector<K> keys; std::transform(map.begin(), map.end(), std::back_inserter(keys), selectFirst<K, V>); return keys; } } } #endif // EMBGEN_UTILS_HPP
21.382353
96
0.552957
[ "vector", "transform" ]
a6ad4d3993d1ab8ad63836429e5cd6024c176158
4,616
cc
C++
extensions/browser/extension_host_test_helper.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
extensions/browser/extension_host_test_helper.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
extensions/browser/extension_host_test_helper.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/extension_host_test_helper.h" #include "base/check.h" #include "base/containers/contains.h" #include "base/run_loop.h" #include "extensions/browser/extension_host.h" namespace extensions { ExtensionHostTestHelper::ExtensionHostTestHelper( content::BrowserContext* browser_context) : ExtensionHostTestHelper(browser_context, ExtensionId()) {} ExtensionHostTestHelper::ExtensionHostTestHelper( content::BrowserContext* browser_context, ExtensionId extension_id) : browser_context_(browser_context), extension_id_(std::move(extension_id)) { host_registry_observation_.Observe( ExtensionHostRegistry::Get(browser_context)); } ExtensionHostTestHelper::~ExtensionHostTestHelper() = default; void ExtensionHostTestHelper::RestrictToType(mojom::ViewType type) { // Restricting to both a specific host and a type is either redundant (if // the types match) or contradictory (if they don't). Don't allow it. DCHECK(!restrict_to_host_) << "Can't restrict to both a host and view type."; restrict_to_type_ = type; } void ExtensionHostTestHelper::RestrictToHost(const ExtensionHost* host) { // Restricting to both a specific host and a type is either redundant (if // the types match) or contradictory (if they don't). Don't allow it. DCHECK(!restrict_to_type_) << "Can't restrict to both a host and view type."; restrict_to_host_ = host; } void ExtensionHostTestHelper::OnExtensionHostRenderProcessReady( content::BrowserContext* browser_context, ExtensionHost* host) { EventSeen(host, HostEvent::kRenderProcessReady); } void ExtensionHostTestHelper::OnExtensionHostDocumentElementAvailable( content::BrowserContext* browser_context, ExtensionHost* host) { EventSeen(host, HostEvent::kDocumentElementAvailable); } void ExtensionHostTestHelper::OnExtensionHostCompletedFirstLoad( content::BrowserContext* browser_context, ExtensionHost* host) { EventSeen(host, HostEvent::kCompletedFirstLoad); } void ExtensionHostTestHelper::OnExtensionHostDestroyed( content::BrowserContext* browser_context, ExtensionHost* host) { EventSeen(host, HostEvent::kDestroyed); } void ExtensionHostTestHelper::OnExtensionHostRenderProcessGone( content::BrowserContext* browser_context, ExtensionHost* host) { EventSeen(host, HostEvent::kRenderProcessGone); } ExtensionHost* ExtensionHostTestHelper::WaitFor(HostEvent event) { DCHECK(!waiting_for_); auto iter = observed_events_.find(event); if (iter != observed_events_.end()) { // Note: This can be null if the host has been destroyed. return iter->second; } base::RunLoop run_loop; // Note: We use QuitWhenIdle (instead of Quit) so that any other listeners of // the relevant events get a chance to run first. quit_loop_ = run_loop.QuitWhenIdleClosure(); waiting_for_ = event; run_loop.Run(); DCHECK(base::Contains(observed_events_, event)); // Note: This can still be null here if the corresponding ExtensionHost was // destroyed. This is always true when waiting for // OnExtensionHostDestroyed(), but can also happen if the ExtensionHost is // destroyed while waiting for the run loop to idle. return observed_events_[event]; } void ExtensionHostTestHelper::EventSeen(ExtensionHost* host, HostEvent event) { // Check if the host matches our restrictions. // Note: We have to check the browser context explicitly because the // ExtensionHostRegistry is shared between on- and off-the-record profiles, // so the `host`'s browser context may not be the same as the one associated // with this object in the case of split mode extensions. if (host->browser_context() != browser_context_) return; if (!extension_id_.empty() && host->extension_id() != extension_id_) return; if (restrict_to_type_ && host->extension_host_type() != restrict_to_type_) return; if (restrict_to_host_ && host != restrict_to_host_) return; if (event == HostEvent::kDestroyed) { // Clean up all old pointers to the ExtensionHost on its destruction. for (auto& kv : observed_events_) { if (kv.second == host) kv.second = nullptr; } // Ensure we don't put a new pointer for the host into the map. host = nullptr; } observed_events_[event] = host; if (waiting_for_ == event) { DCHECK(quit_loop_); waiting_for_.reset(); std::move(quit_loop_).Run(); } } } // namespace extensions
34.706767
79
0.746967
[ "object" ]
a6b20dca132c902ab05f6d4c96e0860e63a37d8f
932
cpp
C++
BUAA/logic_continuous.cpp
nickYDQ/Interview
5e21969b779a83952ea52ba084301e4c53769679
[ "MIT" ]
4
2016-08-23T16:05:53.000Z
2018-03-05T01:52:57.000Z
BUAA/logic_continuous.cpp
nickYDQ/Interview
5e21969b779a83952ea52ba084301e4c53769679
[ "MIT" ]
null
null
null
BUAA/logic_continuous.cpp
nickYDQ/Interview
5e21969b779a83952ea52ba084301e4c53769679
[ "MIT" ]
null
null
null
Y欧尼 13:10:58 #include<stdio.h> #include<vector> using namespace std; int main() { int sum=3; vector<vector<int> > result; int tag =0; int small=1; int big=2; int middle=(1+sum)/2; int cursum=small+big; while(small<middle)//如果small>middle了得话,就不可能在就想家的100了。 { if(cursum==sum) { result.push_back(vector<int>()); for(int i=small;i<=big;i++) { //printf("%d",i); result[tag].push_back(i); } tag++; //printf("\n"); } while(cursum>sum&&small<middle)//sum { cursum-=small; small++; if(cursum==sum) { result.push_back(vector<int>()); for(int i=small;i<=big;i++) { //printf("%d",i); result[tag].push_back(i); } //printf("\n"); tag++; } } big++; cursum+=big; } //return result; return 0; }
18.64
57
0.47103
[ "vector" ]
a6b259616091af8c0f85e45aab37ebb3f261bb22
627
cpp
C++
codenation-contest/intelligent-robots.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
null
null
null
codenation-contest/intelligent-robots.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
null
null
null
codenation-contest/intelligent-robots.cpp
sounishnath003/practice-180D-strategy
2778c861407a2be04168d5dfa6135a4b624029fc
[ "Apache-2.0" ]
1
2020-10-07T15:02:09.000Z
2020-10-07T15:02:09.000Z
#include <bits/stdc++.h> using namespace std ; int main() { srand(time(NULL)) ; ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); int n, k; cin >> n >> k; vector<int> powers(n); fo(i, n){ cin >> powers[i]; } int sum = accumulate(powers.begin(), powers.end(), 0); int maxelem = *max_element(powers.begin(), powers.end()); int minelem = *min_element(powers.begin(), powers.end()); int cost = (sum - (maxelem * minelem) ); cout << "minimum operations: " << cost << endl ; double f = 1.0 + (double) (cost * (k / 100) * (1/2)); cout << "hence total max power: " << f << endl ; }
26.125
59
0.559809
[ "vector" ]
a6b7e0ba81d16ccb7e8cb75ab39b3fa446fafb92
4,640
cpp
C++
source/slang/slang-serialize-factory.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
895
2017-06-10T13:38:39.000Z
2022-03-31T02:29:15.000Z
source/slang/slang-serialize-factory.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
708
2017-06-15T16:03:12.000Z
2022-03-28T19:01:37.000Z
source/slang/slang-serialize-factory.cpp
JKot-Coder/slang
1a1b2a0de67dccc1102449b8620830131d569cde
[ "MIT" ]
80
2017-06-12T15:36:58.000Z
2022-03-23T12:04:24.000Z
// slang-serialize-factory.cpp #include "slang-serialize-factory.h" #include "../core/slang-math.h" #include "slang-ast-builder.h" #include "slang-ref-object-reflect.h" #include "slang-ast-reflect.h" #include "slang-serialize-ast.h" #include "slang-ref-object-reflect.h" // Needed for ModuleSerialFilter // Needed for 'findModuleForDecl' #include "slang-legalize-types.h" #include "slang-mangle.h" namespace Slang { /* !!!!!!!!!!!!!!!!!!!!!! DefaultSerialObjectFactory !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ void* DefaultSerialObjectFactory::create(SerialTypeKind typeKind, SerialSubType subType) { switch (typeKind) { case SerialTypeKind::NodeBase: { return m_astBuilder->createByNodeType(ASTNodeType(subType)); } case SerialTypeKind::RefObject: { const ReflectClassInfo* info = SerialRefObjects::getClassInfo(RefObjectType(subType)); if (info && info->m_createFunc) { RefObject* obj = reinterpret_cast<RefObject*>(info->m_createFunc(nullptr)); return _add(obj); } return nullptr; } default: break; } return nullptr; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ModuleSerialFilter !!!!!!!!!!!!!!!!!!!!!!!! SerialIndex ModuleSerialFilter::writePointer(SerialWriter* writer, const RefObject* inPtr) { // We don't serialize Module if (as<Module>(inPtr)) { writer->setPointerIndex(inPtr, SerialIndex(0)); return SerialIndex(0); } // For now for everything else just write it return writer->writeObject(inPtr); } SerialIndex ModuleSerialFilter::writePointer(SerialWriter* writer, const NodeBase* inPtr) { NodeBase* ptr = const_cast<NodeBase*>(inPtr); SLANG_ASSERT(ptr); // We don't serialize Scope if (as<Scope>(ptr)) { writer->setPointerIndex(inPtr, SerialIndex(0)); return SerialIndex(0); } if (Decl* decl = as<Decl>(ptr)) { ModuleDecl* moduleDecl = findModuleForDecl(decl); SLANG_ASSERT(moduleDecl); if (moduleDecl && moduleDecl != m_moduleDecl) { ASTBuilder* astBuilder = m_moduleDecl->module->getASTBuilder(); // It's a reference to a declaration in another module, so first get the symbol name. String mangledName = getMangledName(astBuilder, decl); // Add as an import symbol return writer->addImportSymbol(mangledName); } else { // Okay... we can just write it out then return writer->writeObject(ptr); } } // TODO(JS): If I enable this section then the stdlib doesn't work correctly, it appears to be because of // `addCatchAllIntrinsicDecorationIfNeeded`. If this is enabled when AST is serialized, the 'body' (ie Stmt) // will not be serialized. When serialized back in, it will appear to be a function without a body. // In that case `addCatchAllIntrinsicDecorationIfNeeded` will add an intrinsic which in some cases is incorrect. // This happens during lowering. // // So it seems the fix is for some other mechanism. Another solution is perhaps to run something like `addCatchAllIntrinsicDecorationIfNeeded` // on the stdlib after compilation, and before serialization. Then removing it from lowering. #if 0 // TODO(JS): What we really want to do here is to ignore bodies functions. // It's not 100% clear if this is even right though - for example does type inference // imply the body is needed to say infer a return type? // Also not clear if statements in other scenarios (if there are others) might need to be kept. // // For now we just ignore all stmts if (Stmt* stmt = as<Stmt>(ptr)) { // writer->setPointerIndex(stmt, SerialIndex(0)); return SerialIndex(0); } #endif // For now for everything else just write it return writer->writeObject(ptr); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! SerialClassesUtil !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ /* static */SlangResult SerialClassesUtil::addSerialClasses(SerialClasses* serialClasses) { ASTSerialUtil::addSerialClasses(serialClasses); SerialRefObjects::addSerialClasses(serialClasses); // Check if it seems ok SLANG_ASSERT(serialClasses->isOk()); return SLANG_OK; } /* static */SlangResult SerialClassesUtil::create(RefPtr<SerialClasses>& out) { RefPtr<SerialClasses> classes(new SerialClasses); SLANG_RETURN_ON_FAIL(addSerialClasses(classes)); out = classes; return SLANG_OK; } } // namespace Slang
31.351351
146
0.641379
[ "object" ]
a6b905cec138fbd9480991011e2b40707854cfc4
1,604
cpp
C++
Stack & Heap/735. Asteroid Collision/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Stack & Heap/735. Asteroid Collision/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Stack & Heap/735. Asteroid Collision/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 735. Asteroid Collision // // Created by 边俊林 on 2019/10/10. // Copyright © 2019 Minecode.Link. All rights reserved. // /* ------------------------------------------------------ *\ https://leetcode-cn.com/problems/Sample/description/ \* ------------------------------------------------------ */ #include <map> #include <set> #include <queue> #include <string> #include <stack> #include <vector> #include <cstdio> #include <numeric> #include <cstdlib> #include <utility> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // class Solution { public: vector<int> asteroidCollision(vector<int>& asteroids) { int n = asteroids.size(); stack<int> st; for (int& item: asteroids) { while (item < 0 && st.size() && st.top() > 0) { int pre = st.top(); st.pop(); if (pre == -item) { item = 0; break; } else if (pre > -item) { item = pre; } } if (item != 0) st.push(item); } vector<int> res (st.size()); for (int i = res.size()-1; i >= 0; --i) res[i] = st.top(), st.pop(); return res; } }; int main() { Solution sol = Solution(); vector<int> nums = { // 5, 10, -5 // 8, -8 // 10, 2, -5 }; auto res = sol.asteroidCollision(nums); auto f = [](int elem) { cout << elem << ", "; }; for_each(res.begin(), res.end(), f); return 0; }
23.588235
61
0.465711
[ "vector" ]
a6bfd5f9121c4e3fba89742a66ea500ec9ef9296
39,476
cxx
C++
main/codemaker/source/idlmaker/idltype.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/codemaker/source/idlmaker/idltype.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/codemaker/source/idlmaker/idltype.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_codemaker.hxx" #include <stdio.h> #include <rtl/alloc.h> #include <rtl/ustring.hxx> #include <rtl/strbuf.hxx> #include "idltype.hxx" #include "idloptions.hxx" using namespace rtl; //************************************************************************* // IdlType //************************************************************************* IdlType::IdlType(TypeReader& typeReader, const OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies) : m_inheritedMemberCount(0) , m_indentLength(0) , m_typeName(typeName) , m_reader(typeReader) , m_typeMgr((TypeManager&)typeMgr) , m_dependencies(typeDependencies) { sal_Int32 i = typeName.lastIndexOf('/'); m_name = typeName.copy( i != -1 ? i+1 : 0 ); } IdlType::~IdlType() { } sal_Bool IdlType::dump(IdlOptions* pOptions) throw( CannotDumpException ) { sal_Bool ret = sal_False; OString outPath; if (pOptions->isValid("-O")) outPath = pOptions->getOption("-O"); OString tmpFileName; OString hFileName = createFileNameFromType(outPath, m_typeName, ".idl"); sal_Bool bFileExists = sal_False; sal_Bool bFileCheck = sal_False; if ( pOptions->isValid("-G") || pOptions->isValid("-Gc") ) { bFileExists = fileExists( hFileName ); ret = sal_True; } if ( bFileExists && pOptions->isValid("-Gc") ) { tmpFileName = createFileNameFromType(outPath, m_typeName, ".tml"); bFileCheck = sal_True; } if ( !bFileExists || bFileCheck ) { FileStream hFile; if ( bFileCheck ) hFile.open(tmpFileName); else hFile.open(hFileName); if(!hFile.isValid()) { OString message("cannot open "); message += hFileName + " for writing"; throw CannotDumpException(message); } ret = dumpHFile(hFile); hFile.close(); if (ret && bFileCheck) { ret = checkFileContent(hFileName, tmpFileName); } } return ret; } sal_Bool IdlType::dumpDependedTypes(IdlOptions* pOptions) throw( CannotDumpException ) { sal_Bool ret = sal_True; TypeUsingSet usingSet(m_dependencies.getDependencies(m_typeName)); TypeUsingSet::const_iterator iter = usingSet.begin(); OString typeName; sal_uInt32 index = 0; while (iter != usingSet.end()) { typeName = (*iter).m_type; if ((index = typeName.lastIndexOf(']')) > 0) typeName = typeName.copy(index + 1); if ( getBaseType(typeName).isEmpty() ) { if (!produceType(typeName, m_typeMgr, m_dependencies, pOptions)) { fprintf(stderr, "%s ERROR: %s\n", pOptions->getProgramName().getStr(), OString("cannot dump Type '" + typeName + "'").getStr()); exit(99); } } ++iter; } return ret; } OString IdlType::dumpHeaderDefine(FileStream& o, sal_Char* prefix ) { if (m_typeName.equals("/")) { m_typeName = "global"; } sal_uInt32 length = 3 + m_typeName.getLength() + strlen(prefix); OStringBuffer tmpBuf(length); tmpBuf.append('_'); tmpBuf.append(m_typeName); tmpBuf.append('_'); tmpBuf.append(prefix); tmpBuf.append('_'); OString tmp(tmpBuf.makeStringAndClear().replace('/', '_').toAsciiUpperCase()); o << "#ifndef " << tmp << "\n#define " << tmp << "\n"; return tmp; } void IdlType::dumpDefaultHIncludes(FileStream& o) { } void IdlType::dumpInclude(FileStream& o, const OString& genTypeName, const OString& typeName, sal_Char* prefix ) { sal_uInt32 length = 3+ m_typeName.getLength() + strlen(prefix); OStringBuffer tmpBuf(length); tmpBuf.append('_'); tmpBuf.append(typeName); tmpBuf.append('_'); tmpBuf.append(prefix); tmpBuf.append('_'); OString tmp(tmpBuf.makeStringAndClear().replace('/', '_').toAsciiUpperCase()); length = 1 + typeName.getLength() + strlen(prefix); tmpBuf.ensureCapacity(length); tmpBuf.append(typeName); tmpBuf.append('.'); tmpBuf.append(prefix); o << "#ifndef " << tmp << "\n#include <"; tmp = tmpBuf.makeStringAndClear(); sal_Int32 nIndex = 0; do { genTypeName.getToken(0, '/', nIndex); o << "../"; } while( nIndex != -1 ); // sal_Int32 nSlashes = genTypeName.getTokenCount( '/'); // for( sal_Int32 i = 1; i < nSlashes; i++ ) // o << "../"; o << tmp; o << ">\n#endif\n"; } void IdlType::dumpDepIncludes(FileStream& o, const OString& typeName, sal_Char* prefix) { TypeUsingSet usingSet(m_dependencies.getDependencies(typeName)); TypeUsingSet::const_iterator iter = usingSet.begin(); OString sPrefix(OString(prefix).toAsciiUpperCase()); sal_uInt32 index = 0; sal_uInt32 seqNum = 0; OString relType; while (iter != usingSet.end()) { index = (*iter).m_type.lastIndexOf(']'); seqNum = (index > 0 ? ((index+1) / 2) : 0); relType = (*iter).m_type; if (index > 0) relType = relType.copy(index+1); OString defPrefix("IDL"); if ( getBaseType(relType).isEmpty() && m_typeName != relType) { if (m_typeMgr.getTypeClass(relType) == RT_TYPE_INTERFACE) { if (!((*iter).m_use & TYPEUSE_SUPER)) { o << "\n"; dumpNameSpace(o, sal_True, sal_False, relType); o << "\ninterface " << scopedName(m_typeName, relType, sal_True) << ";\n"; dumpNameSpace(o, sal_False, sal_False, relType); o << "\n\n"; } } dumpInclude(o, typeName, relType, prefix); } else if (relType == "type") { o << "module CORBA {\n" << "\tinterface TypeCode;\n" << "};\n\n"; } if( seqNum != 0 ) { // write typedef for sequences to support Rational Rose 2000 import OString aST = relType; OString aScope; dumpNameSpace( o, sal_True, sal_False, relType ); for( sal_uInt32 i = 0; i < seqNum; i++ ) { o << "typedef sequence< " << scopedName("", aST) << " > "; if( i == 0 ) { aST = aST.replace( '/', '_' ); aST = aST.replace( ' ', '_' ); } aST = aST + "_Sequence" ; o << aST << ";\n"; } dumpNameSpace( o, sal_False, sal_False, relType ); } ++iter; } } void IdlType::dumpNameSpace(FileStream& o, sal_Bool bOpen, sal_Bool bFull, const OString& type) { OString typeName(type); sal_Bool bOneLine = sal_True; if ( typeName.isEmpty() ) { typeName = m_typeName; bOneLine = sal_False; } if (typeName == "/") return; if (typeName.indexOf( '/' ) == -1 && !bFull) return; if (!bFull) typeName = typeName.copy( 0, typeName.lastIndexOf( '/' ) ); if (bOpen) { sal_Int32 nIndex = 0; do { o << "module " << typeName.getToken(0, '/', nIndex); if (bOneLine) o << " { "; else o << "\n{\n"; } while( nIndex != -1 ); } else { sal_Int32 nPos = 0; do { nPos = typeName.lastIndexOf( '/' ); o << "};"; if( bOneLine ) o << " "; else o << " /* " << typeName.copy( nPos+1 ) << " */\n"; if( nPos != -1 ) typeName = typeName.copy( 0, nPos ); } while( nPos != -1 ); } } sal_uInt32 IdlType::getMemberCount() { sal_uInt32 count = m_reader.getMethodCount(); sal_uInt32 fieldCount = m_reader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; for (sal_uInt16 i=0; i < fieldCount; i++) { access = m_reader.getFieldAccess(i); if (access != RT_ACCESS_CONST && access != RT_ACCESS_INVALID) count++; } return count; } sal_uInt32 IdlType::checkInheritedMemberCount(const TypeReader* pReader) { sal_Bool bSelfCheck = sal_True; if (!pReader) { bSelfCheck = sal_False; pReader = &m_reader; } sal_uInt32 count = 0; OString superType(pReader->getSuperTypeName()); if ( !superType.isEmpty() ) { TypeReader aSuperReader(m_typeMgr.getTypeReader(superType)); if ( aSuperReader.isValid() ) { count = checkInheritedMemberCount(&aSuperReader); } } if (bSelfCheck) { count += pReader->getMethodCount(); sal_uInt32 fieldCount = pReader->getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; for (sal_uInt16 i=0; i < fieldCount; i++) { access = pReader->getFieldAccess(i); if (access != RT_ACCESS_CONST && access != RT_ACCESS_INVALID) { count++; } } } return count; } sal_uInt32 IdlType::getInheritedMemberCount() { if (m_inheritedMemberCount == 0) { m_inheritedMemberCount = checkInheritedMemberCount(0); } return m_inheritedMemberCount; } void IdlType::dumpType(FileStream& o, const OString& type ) throw( CannotDumpException ) { OString sType(checkRealBaseType(type, sal_True)); sal_uInt32 index = sType.lastIndexOf(']'); sal_uInt32 seqNum = (index > 0 ? ((index+1) / 2) : 0); OString relType = (index > 0 ? (sType).copy(index+1) : type); RTTypeClass typeClass = m_typeMgr.getTypeClass(relType); sal_uInt32 i; /* for (i=0; i < seqNum; i++) { //o << "sequence< "; } */ switch (typeClass) { case RT_TYPE_INVALID: { OString tmp(getBaseType(relType)); if ( !tmp.isEmpty() ) { tmp = tmp.replace( ' ', '_' ); o << tmp; } else throw CannotDumpException("Unknown type '" + relType + "', incomplete type library."); } break; case RT_TYPE_INTERFACE: case RT_TYPE_STRUCT: case RT_TYPE_ENUM: case RT_TYPE_TYPEDEF: case RT_TYPE_EXCEPTION: if( seqNum ) { OString aST = relType.replace( '/', '_' ); aST = aST.replace( ' ', '_' ); o << aST; } else o << scopedName(m_typeName, relType); break; } for (i=0; i < seqNum; i++) { //o << " >"; // use typedef for sequences to support Rational Rose 2000 import o << "_Sequence"; } } OString IdlType::getBaseType(const OString& type) { if (type.equals("long")) return type; if (type.equals("short")) return type; if (type.equals("hyper")) return "long long"; if (type.equals("string")) return "string"; if (type.equals("boolean")) return type; if (type.equals("char")) return "char"; if (type.equals("byte")) return "byte"; if (type.equals("any")) return type; if (type.equals("type")) return "CORBA::TypeCode"; if (type.equals("float")) return type; if (type.equals("double")) return type; if (type.equals("octet")) return type; if (type.equals("void")) return type; if (type.equals("unsigned long")) return type; if (type.equals("unsigned short")) return type; if (type.equals("unsigned hyper")) return "unsigned long long"; return OString(); } void IdlType::dumpIdlGetType(FileStream& o, const OString& type, sal_Bool bDecl, IdlTypeDecl eDeclFlag) { OString sType( checkRealBaseType(type, sal_True) ); sal_uInt32 index = sType.lastIndexOf(']'); OString relType = (index > 0 ? (sType).copy(index+1) : type); if (eDeclFlag == CPPUTYPEDECL_ONLYINTERFACES) { if (m_typeMgr.getTypeClass(relType) == RT_TYPE_INTERFACE) { o << indent() << "getIdlType( ("; dumpType(o, type); o << "*)0 )"; if (bDecl) o << ";\n"; } } else { if (isBaseType(type)) { return; } else { if (eDeclFlag == CPPUTYPEDECL_NOINTERFACES && m_typeMgr.getTypeClass(relType) == RT_TYPE_INTERFACE) return; // if (m_typeMgr.getTypeClass(type) == RT_TYPE_TYPEDEF) // { // o << indent() << "get_" << type.replace('/', '_') << "_Type()"; // } else // { o << indent() << "getIdlType( ("; dumpType(o, type); o << "*)0 )"; // } } if (bDecl) o << ";\n"; } } BASETYPE IdlType::isBaseType(const OString& type) { if (type.equals("long")) return BT_LONG; if (type.equals("short")) return BT_SHORT; if (type.equals("hyper")) return BT_HYPER; if (type.equals("string")) return BT_STRING; if (type.equals("boolean")) return BT_BOOLEAN; if (type.equals("char")) return BT_CHAR; if (type.equals("byte")) return BT_BYTE; if (type.equals("any")) return BT_ANY; if (type.equals("float")) return BT_FLOAT; if (type.equals("double")) return BT_DOUBLE; if (type.equals("void")) return BT_VOID; if (type.equals("unsigned long")) return BT_UNSIGNED_LONG; if (type.equals("unsigned short")) return BT_UNSIGNED_SHORT; if (type.equals("unsigned hyper")) return BT_UNSIGNED_HYPER; return BT_INVALID; } OString IdlType::checkSpecialIdlType(const OString& type) { OString baseType(type); RegistryTypeReaderLoader & rReaderLoader = getRegistryTypeReaderLoader(); RegistryKey key; sal_uInt8* pBuffer=NULL; RTTypeClass typeClass; sal_Bool isTypeDef = (m_typeMgr.getTypeClass(baseType) == RT_TYPE_TYPEDEF); TypeReader reader; while (isTypeDef) { reader = m_typeMgr.getTypeReader(baseType); if (reader.isValid()) { typeClass = reader.getTypeClass(); if (typeClass == RT_TYPE_TYPEDEF) baseType = reader.getSuperTypeName(); else isTypeDef = sal_False; } else { break; } } return baseType; } OString IdlType::checkRealBaseType(const OString& type, sal_Bool bResolveTypeOnly) { sal_uInt32 index = type.lastIndexOf(']'); OString baseType = (index > 0 ? ((OString)type).copy(index+1) : type); OString seqPrefix = (index > 0 ? ((OString)type).copy(0, index+1) : OString()); RegistryTypeReaderLoader & rReaderLoader = getRegistryTypeReaderLoader(); RegistryKey key; sal_uInt8* pBuffer=NULL; RTTypeClass typeClass; sal_Bool mustBeChecked = (m_typeMgr.getTypeClass(baseType) == RT_TYPE_TYPEDEF); TypeReader reader; while (mustBeChecked) { reader = m_typeMgr.getTypeReader(baseType); if (reader.isValid()) { typeClass = reader.getTypeClass(); if (typeClass == RT_TYPE_TYPEDEF) { baseType = reader.getSuperTypeName(); index = baseType.lastIndexOf(']'); if (index > 0) { seqPrefix += baseType.copy(0, index+1); baseType = baseType.copy(index+1); } } else mustBeChecked = sal_False; } else { break; } } if ( bResolveTypeOnly ) baseType = seqPrefix + baseType; return baseType; } void IdlType::dumpConstantValue(FileStream& o, sal_uInt16 index) { RTConstValue constValue = m_reader.getFieldConstValue(index); switch (constValue.m_type) { case RT_TYPE_BOOL: if (constValue.m_value.aBool) o << "true"; else o << "false"; break; case RT_TYPE_BYTE: { char tmp[16]; snprintf(tmp, sizeof(tmp), "0x%x", (sal_Int8)constValue.m_value.aByte); o << tmp; } break; case RT_TYPE_INT16: o << constValue.m_value.aShort; break; case RT_TYPE_UINT16: o << constValue.m_value.aUShort; break; case RT_TYPE_INT32: o << constValue.m_value.aLong; break; case RT_TYPE_UINT32: o << constValue.m_value.aULong; break; case RT_TYPE_INT64: { ::rtl::OString tmp( OString::valueOf(constValue.m_value.aHyper) ); o << tmp.getStr(); } break; case RT_TYPE_UINT64: { ::rtl::OString tmp( OString::valueOf((sal_Int64)constValue.m_value.aUHyper) ); o << tmp.getStr(); } break; case RT_TYPE_FLOAT: { ::rtl::OString tmp( OString::valueOf(constValue.m_value.aFloat) ); o << tmp.getStr(); } break; case RT_TYPE_DOUBLE: { ::rtl::OString tmp( OString::valueOf(constValue.m_value.aDouble) ); o << tmp.getStr(); } break; case RT_TYPE_STRING: { ::rtl::OUString aUStr(constValue.m_value.aString); ::rtl::OString aStr = ::rtl::OUStringToOString(aUStr, RTL_TEXTENCODING_ASCII_US); o << "\"" << aStr.getStr() << "\")"; } break; } } void IdlType::inc(sal_uInt32 num) { m_indentLength += num; } void IdlType::dec(sal_uInt32 num) { if (m_indentLength - num < 0) m_indentLength = 0; else m_indentLength -= num; } OString IdlType::indent() { OStringBuffer tmp(m_indentLength); for (sal_uInt32 i=0; i < m_indentLength; i++) { tmp.append(' '); } return tmp.makeStringAndClear(); } OString IdlType::indent(sal_uInt32 num) { OStringBuffer tmp(m_indentLength + num); for (sal_uInt32 i=0; i < m_indentLength + num; i++) { tmp.append(' '); } return tmp.makeStringAndClear(); } //************************************************************************* // InterfaceType //************************************************************************* InterfaceType::InterfaceType(TypeReader& typeReader, const OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies) : IdlType(typeReader, typeName, typeMgr, typeDependencies) { m_inheritedMemberCount = 0; m_hasAttributes = sal_False; m_hasMethods = sal_False; } InterfaceType::~InterfaceType() { } sal_Bool InterfaceType::dumpHFile(FileStream& o) throw( CannotDumpException ) { OString headerDefine(dumpHeaderDefine(o, "IDL")); o << "\n"; dumpDefaultHIncludes(o); o << "\n"; dumpDepIncludes(o, m_typeName, "idl"); o << "\n"; dumpNameSpace(o); // write documentation OString aDoc = m_reader.getDoku(); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/"; o << "\ninterface " << m_name; OString superType(m_reader.getSuperTypeName()); if ( !superType.isEmpty() ) o << " : " << scopedName(m_typeName, superType); o << "\n{\n"; inc(); dumpAttributes(o); dumpMethods(o); dec(); o << "};\n\n"; dumpNameSpace(o, sal_False); // o << "\nnamespace com { namespace sun { namespace star { namespace uno {\n" // << "class Type;\n} } } }\n\n"; o << "#endif /* "<< headerDefine << "*/" << "\n"; return sal_True; } void InterfaceType::dumpAttributes(FileStream& o) { sal_uInt32 fieldCount = m_reader.getFieldCount(); sal_Bool first=sal_True; RTFieldAccess access = RT_ACCESS_INVALID; OString fieldName; OString fieldType; for (sal_uInt16 i=0; i < fieldCount; i++) { access = m_reader.getFieldAccess(i); if (access == RT_ACCESS_CONST || access == RT_ACCESS_INVALID) continue; fieldName = m_reader.getFieldName(i); fieldType = m_reader.getFieldType(i); if (first) { first = sal_False; o << "\n"; } // write documentation OString aDoc = m_reader.getFieldDoku(i); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/\n"; if (access == RT_ACCESS_READONLY) o << indent() << "readonly attribute "; else o << indent() << "attribute "; dumpType(o, fieldType); o << " " << fieldName << ";\n"; } } void InterfaceType::dumpMethods(FileStream& o) { sal_uInt32 methodCount = m_reader.getMethodCount(); OString methodName, returnType, paramType, paramName; sal_uInt32 paramCount = 0; sal_uInt32 excCount = 0; RTMethodMode methodMode = RT_MODE_INVALID; RTParamMode paramMode = RT_PARAM_INVALID; sal_Bool bRef = sal_False; sal_Bool bConst = sal_False; sal_Bool bWithRunTimeExcp = sal_True; for (sal_Int16 i=0; i < methodCount; i++) { methodName = m_reader.getMethodName(i); returnType = m_reader.getMethodReturnType(i); paramCount = m_reader.getMethodParamCount(i); excCount = m_reader.getMethodExcCount(i); methodMode = m_reader.getMethodMode(i); if ( methodName.equals("acquire") || methodName.equals("release") ) { bWithRunTimeExcp = sal_False; } // write documentation OString aDoc = m_reader.getMethodDoku(i); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/\n"; o << indent(); dumpType(o, returnType); o << " " << methodName << "( "; sal_uInt16 j; for (j=0; j < paramCount; j++) { paramName = m_reader.getMethodParamName(i, j); paramType = m_reader.getMethodParamType(i, j); paramMode = m_reader.getMethodParamMode(i, j); switch (paramMode) { case RT_PARAM_IN: o << "in "; break; case RT_PARAM_OUT: o << "out "; break; case RT_PARAM_INOUT: o << "inout "; break; break; } dumpType(o, paramType); if( paramName == "Object" ) o << " _Object"; else o << " " << paramName; if (j+1 < paramCount) o << ", "; } o << " )"; if( excCount ) { o << " raises("; OString excpName; sal_Bool bWriteComma = sal_False; sal_Bool bRTExceptionWritten = sal_False; for (j=0; j < excCount; j++) { excpName = m_reader.getMethodExcType(i, j); if( bWriteComma ) o << ", "; o << scopedName(m_typeName, excpName); bWriteComma = sal_True; if(excpName == "com/sun/star/uno/RuntimeException") bRTExceptionWritten = sal_True; } if ( bWithRunTimeExcp && !bRTExceptionWritten ) { if( bWriteComma ) o << ", "; o << "::com::sun::star::uno::RuntimeException"; } o << ");\n"; } else if ( bWithRunTimeExcp ) { o << "raises( ::com::sun::star::uno::RuntimeException );\n"; } else { o << ";\n"; } } } sal_uInt32 InterfaceType::getMemberCount() { sal_uInt32 count = m_reader.getMethodCount(); if (count) m_hasMethods = sal_True; sal_uInt32 fieldCount = m_reader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; for (sal_uInt16 i=0; i < fieldCount; i++) { access = m_reader.getFieldAccess(i); if (access != RT_ACCESS_CONST && access != RT_ACCESS_INVALID) { m_hasAttributes = sal_True; count++; } } return count; } sal_uInt32 InterfaceType::checkInheritedMemberCount(const TypeReader* pReader) { sal_uInt32 cout = 0; sal_Bool bSelfCheck = sal_True; if (!pReader) { bSelfCheck = sal_False; pReader = &m_reader; } sal_uInt32 count = 0; OString superType(pReader->getSuperTypeName()); if ( !superType.isEmpty() ) { TypeReader aSuperReader(m_typeMgr.getTypeReader(superType)); if (aSuperReader.isValid()) { count = checkInheritedMemberCount(&aSuperReader); } } if (bSelfCheck) { count += pReader->getMethodCount(); sal_uInt32 fieldCount = pReader->getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; for (sal_uInt16 i=0; i < fieldCount; i++) { access = pReader->getFieldAccess(i); if (access != RT_ACCESS_CONST && access != RT_ACCESS_INVALID) { count++; } } } return count; } sal_uInt32 InterfaceType::getInheritedMemberCount() { if (m_inheritedMemberCount == 0) { m_inheritedMemberCount = checkInheritedMemberCount(0); } return m_inheritedMemberCount; } //************************************************************************* // ModuleType //************************************************************************* ModuleType::ModuleType(TypeReader& typeReader, const OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies) : IdlType(typeReader, typeName, typeMgr, typeDependencies) { } ModuleType::~ModuleType() { } sal_Bool ModuleType::dump(IdlOptions* pOptions) throw( CannotDumpException ) { sal_Bool ret = sal_False; OString outPath; if (pOptions->isValid("-O")) outPath = pOptions->getOption("-O"); OString tmpName(m_typeName); if (tmpName.equals("/")) tmpName = "global"; else // tmpName += "/" + m_typeName.getToken(m_typeName.getTokenCount('/') - 1, '/'); tmpName += "/" + m_name; OString tmpFileName; OString hFileName = createFileNameFromType(outPath, tmpName, ".idl"); sal_Bool bFileExists = sal_False; sal_Bool bFileCheck = sal_False; if ( pOptions->isValid("-G") || pOptions->isValid("-Gc") ) { bFileExists = fileExists( hFileName ); ret = sal_True; } if ( bFileExists && pOptions->isValid("-Gc") ) { tmpFileName = createFileNameFromType(outPath, m_typeName, ".tml"); bFileCheck = sal_True; } if ( !bFileExists || bFileCheck ) { FileStream hFile; if ( bFileCheck ) hFile.open(tmpFileName); else hFile.open(hFileName); if(!hFile.isValid()) { OString message("cannot open "); message += hFileName + " for writing"; throw CannotDumpException(message); } ret = dumpHFile(hFile); hFile.close(); if (ret && bFileCheck) { ret = checkFileContent(hFileName, tmpFileName); } } return ret; } sal_Bool ModuleType::dumpHFile(FileStream& o) throw( CannotDumpException ) { OString headerDefine(dumpHeaderDefine(o, "IDL")); o << "\n"; dumpDefaultHIncludes(o); o << "\n"; dumpDepIncludes(o, m_typeName, "idl"); o << "\n"; dumpNameSpace(o, sal_True, sal_True); o << "\n"; sal_uInt32 fieldCount = m_reader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; OString fieldName; OString fieldType; for (sal_uInt16 i=0; i < fieldCount; i++) { access = m_reader.getFieldAccess(i); if (access == RT_ACCESS_CONST) { fieldName = m_reader.getFieldName(i); fieldType = m_reader.getFieldType(i); o << "const "; dumpType(o, fieldType); o << " " << fieldName << " = "; dumpConstantValue(o, i); o << ";\n"; } } o << "\n"; dumpNameSpace(o, sal_False, sal_True); o << "\n#endif /* "<< headerDefine << "*/" << "\n"; return sal_True; } sal_Bool ModuleType::hasConstants() { sal_uInt32 fieldCount = m_reader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; for (sal_uInt16 i=0; i < fieldCount; i++) { access = m_reader.getFieldAccess(i); if (access == RT_ACCESS_CONST) return sal_True; } return sal_False; } //************************************************************************* // ConstantsType //************************************************************************* ConstantsType::ConstantsType(TypeReader& typeReader, const OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies) : ModuleType(typeReader, typeName, typeMgr, typeDependencies) { } ConstantsType::~ConstantsType() { } sal_Bool ConstantsType::dump(IdlOptions* pOptions) throw( CannotDumpException ) { sal_Bool ret = sal_False; OString outPath; if (pOptions->isValid("-O")) outPath = pOptions->getOption("-O"); OString tmpFileName; OString hFileName = createFileNameFromType(outPath, m_typeName, ".idl"); sal_Bool bFileExists = sal_False; sal_Bool bFileCheck = sal_False; if ( pOptions->isValid("-G") || pOptions->isValid("-Gc") ) { bFileExists = fileExists( hFileName ); ret = sal_True; } if ( bFileExists && pOptions->isValid("-Gc") ) { tmpFileName = createFileNameFromType(outPath, m_typeName, ".tml"); bFileCheck = sal_True; } if ( !bFileExists || bFileCheck ) { FileStream hFile; if ( bFileCheck ) hFile.open(tmpFileName); else hFile.open(hFileName); if(!hFile.isValid()) { OString message("cannot open "); message += hFileName + " for writing"; throw CannotDumpException(message); } ret = dumpHFile(hFile); hFile.close(); if (ret && bFileCheck) { ret = checkFileContent(hFileName, tmpFileName); } } return ret; } //************************************************************************* // StructureType //************************************************************************* StructureType::StructureType(TypeReader& typeReader, const OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies) : IdlType(typeReader, typeName, typeMgr, typeDependencies) { } StructureType::~StructureType() { } sal_Bool StructureType::dumpHFile(FileStream& o) throw( CannotDumpException ) { OString headerDefine(dumpHeaderDefine(o, "IDL")); o << "\n"; dumpDefaultHIncludes(o); o << "\n"; dumpDepIncludes(o, m_typeName, "idl"); o << "\n"; dumpNameSpace(o); // write documentation OString aDoc = m_reader.getDoku(); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/"; o << "\nstruct " << m_name; o << "\n{\n"; inc(); OString superType(m_reader.getSuperTypeName()); if ( !superType.isEmpty() ) dumpSuperMember(o, superType); sal_uInt32 fieldCount = m_reader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; OString fieldName; OString fieldType; sal_uInt16 i=0; for (i=0; i < fieldCount; i++) { access = m_reader.getFieldAccess(i); if (access == RT_ACCESS_CONST || access == RT_ACCESS_INVALID) continue; fieldName = m_reader.getFieldName(i); fieldType = m_reader.getFieldType(i); // write documentation OString aDoc = m_reader.getFieldDoku(i); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/"; o << indent(); dumpType(o, fieldType); o << " " << fieldName << ";\n"; } dec(); o << "};\n\n"; dumpNameSpace(o, sal_False); o << "#endif /* "<< headerDefine << "*/" << "\n"; return sal_True; } void StructureType::dumpSuperMember(FileStream& o, const OString& superType) { if ( !superType.isEmpty() ) { TypeReader aSuperReader(m_typeMgr.getTypeReader(superType)); if (aSuperReader.isValid()) { dumpSuperMember(o, aSuperReader.getSuperTypeName()); sal_uInt32 fieldCount = aSuperReader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; OString fieldName; OString fieldType; for (sal_uInt16 i=0; i < fieldCount; i++) { access = aSuperReader.getFieldAccess(i); if (access == RT_ACCESS_CONST || access == RT_ACCESS_INVALID) continue; fieldName = aSuperReader.getFieldName(i); fieldType = aSuperReader.getFieldType(i); // write documentation OString aDoc = aSuperReader.getFieldDoku(i); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/"; o << indent(); dumpType(o, fieldType); o << " "; o << fieldName << ";\n"; } } } } //************************************************************************* // ExceptionType //************************************************************************* ExceptionType::ExceptionType(TypeReader& typeReader, const OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies) : IdlType(typeReader, typeName, typeMgr, typeDependencies) { } ExceptionType::~ExceptionType() { } sal_Bool ExceptionType::dumpHFile(FileStream& o) throw( CannotDumpException ) { OString headerDefine(dumpHeaderDefine(o, "IDL")); o << "\n"; dumpDefaultHIncludes(o); o << "\n"; dumpDepIncludes(o, m_typeName, "idl"); o << "\n"; dumpNameSpace(o); // write documentation OString aDoc = m_reader.getDoku(); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/"; o << "\nexception " << m_name; o << "\n{\n"; inc(); // Write extra member for derived exceptions o << indent() << "/*extra member to hold a derived exception */\n"; o << indent() << "any _derivedException;\n"; OString superType(m_reader.getSuperTypeName()); if ( !superType.isEmpty() ) dumpSuperMember(o, superType); sal_uInt32 fieldCount = m_reader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; OString fieldName; OString fieldType; sal_uInt16 i = 0; for (i=0; i < fieldCount; i++) { access = m_reader.getFieldAccess(i); if (access == RT_ACCESS_CONST || access == RT_ACCESS_INVALID) continue; fieldName = m_reader.getFieldName(i); fieldType = m_reader.getFieldType(i); // write documentation OString aDoc = m_reader.getFieldDoku(i); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/"; o << indent(); dumpType(o, fieldType); o << " " << fieldName << ";\n"; } dec(); o << "};\n\n"; dumpNameSpace(o, sal_False); o << "#endif /* "<< headerDefine << "*/" << "\n"; return sal_True; } void ExceptionType::dumpSuperMember(FileStream& o, const OString& superType) { if ( !superType.isEmpty() ) { TypeReader aSuperReader(m_typeMgr.getTypeReader(superType)); if (aSuperReader.isValid()) { dumpSuperMember(o, aSuperReader.getSuperTypeName()); sal_uInt32 fieldCount = aSuperReader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; OString fieldName; OString fieldType; for (sal_uInt16 i=0; i < fieldCount; i++) { access = aSuperReader.getFieldAccess(i); if (access == RT_ACCESS_CONST || access == RT_ACCESS_INVALID) continue; fieldName = aSuperReader.getFieldName(i); fieldType = aSuperReader.getFieldType(i); // write documentation OString aDoc = aSuperReader.getFieldDoku(i); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/"; o << indent(); dumpType(o, fieldType); o << " "; o << fieldName << ";\n"; } } } } //************************************************************************* // EnumType //************************************************************************* EnumType::EnumType(TypeReader& typeReader, const OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies) : IdlType(typeReader, typeName, typeMgr, typeDependencies) { } EnumType::~EnumType() { } sal_Bool EnumType::dumpHFile(FileStream& o) throw( CannotDumpException ) { OString headerDefine(dumpHeaderDefine(o, "IDL")); o << "\n"; dumpDefaultHIncludes(o); o << "\n"; dumpNameSpace(o); // write documentation OString aDoc = m_reader.getDoku(); if( !aDoc.isEmpty() ) o << "/**\n" << aDoc << "\n*/"; o << "\nenum " << m_name << "\n{\n"; inc(); sal_uInt32 fieldCount = m_reader.getFieldCount(); RTFieldAccess access = RT_ACCESS_INVALID; RTConstValue constValue; OString fieldName; sal_uInt32 value=0; for (sal_uInt16 i=0; i < fieldCount; i++) { access = m_reader.getFieldAccess(i); if (access != RT_ACCESS_CONST) continue; fieldName = m_reader.getFieldName(i); constValue = m_reader.getFieldConstValue(i); if (constValue.m_type == RT_TYPE_INT32) value = constValue.m_value.aLong; else value++; /* doesn't work with rational rose 2000 // write documentation OString aDoc = m_reader.getFieldDoku(i); if( aDoc.getLength() ) */ // o << "/**\n" << aDoc << "\n*/\n"; o << indent() << fieldName; if( i +1 < fieldCount ) o << ",\n"; } dec(); o << "\n};\n\n"; dumpNameSpace(o, sal_False); o << "#endif /* "<< headerDefine << "*/" << "\n"; return sal_True; } //************************************************************************* // TypeDefType //************************************************************************* TypeDefType::TypeDefType(TypeReader& typeReader, const OString& typeName, const TypeManager& typeMgr, const TypeDependency& typeDependencies) : IdlType(typeReader, typeName, typeMgr, typeDependencies) { } TypeDefType::~TypeDefType() { } sal_Bool TypeDefType::dumpHFile(FileStream& o) throw( CannotDumpException ) { OString headerDefine(dumpHeaderDefine(o, "IDL")); o << "\n"; dumpDefaultHIncludes(o); o << "\n"; dumpDepIncludes(o, m_typeName, "idl"); o << "\n"; dumpNameSpace(o); o << "\ntypedef "; dumpType(o, m_reader.getSuperTypeName()); o << " " << m_name << ";\n\n"; dumpNameSpace(o, sal_False); o << "#endif /* "<< headerDefine << "*/" << "\n"; return sal_True; } //************************************************************************* // produceType //************************************************************************* sal_Bool produceType(const OString& typeName, TypeManager& typeMgr, TypeDependency& typeDependencies, IdlOptions* pOptions) throw( CannotDumpException ) { if (typeDependencies.isGenerated(typeName)) return sal_True; TypeReader reader(typeMgr.getTypeReader(typeName)); if (!reader.isValid()) { if (typeName.equals("/")) return sal_True; else return sal_False; } if( !checkTypeDependencies(typeMgr, typeDependencies, typeName)) return sal_False; RTTypeClass typeClass = reader.getTypeClass(); sal_Bool ret = sal_False; switch (typeClass) { case RT_TYPE_INTERFACE: { InterfaceType iType(reader, typeName, typeMgr, typeDependencies); ret = iType.dump(pOptions); if (ret) typeDependencies.setGenerated(typeName); ret = iType.dumpDependedTypes(pOptions); } break; case RT_TYPE_MODULE: { ModuleType mType(reader, typeName, typeMgr, typeDependencies); if (mType.hasConstants()) { ret = mType.dump(pOptions); if (ret) typeDependencies.setGenerated(typeName); // ret = mType.dumpDependedTypes(pOptions); } else { typeDependencies.setGenerated(typeName); ret = sal_True; } } break; case RT_TYPE_STRUCT: { StructureType sType(reader, typeName, typeMgr, typeDependencies); ret = sType.dump(pOptions); if (ret) typeDependencies.setGenerated(typeName); ret = sType.dumpDependedTypes(pOptions); } break; case RT_TYPE_ENUM: { EnumType enType(reader, typeName, typeMgr, typeDependencies); ret = enType.dump(pOptions); if (ret) typeDependencies.setGenerated(typeName); ret = enType.dumpDependedTypes(pOptions); } break; case RT_TYPE_EXCEPTION: { ExceptionType eType(reader, typeName, typeMgr, typeDependencies); ret = eType.dump(pOptions); if (ret) typeDependencies.setGenerated(typeName); ret = eType.dumpDependedTypes(pOptions); } break; case RT_TYPE_TYPEDEF: { TypeDefType tdType(reader, typeName, typeMgr, typeDependencies); ret = tdType.dump(pOptions); if (ret) typeDependencies.setGenerated(typeName); ret = tdType.dumpDependedTypes(pOptions); } break; case RT_TYPE_CONSTANTS: { ConstantsType cType(reader, typeName, typeMgr, typeDependencies); if (cType.hasConstants()) { ret = cType.dump(pOptions); if (ret) typeDependencies.setGenerated(typeName); // ret = cType.dumpDependedTypes(pOptions); } else { typeDependencies.setGenerated(typeName); ret = sal_True; } } break; case RT_TYPE_SERVICE: case RT_TYPE_OBJECT: ret = sal_True; break; } return ret; } //************************************************************************* // scopedName //************************************************************************* OString scopedName(const OString& scope, const OString& type, sal_Bool bNoNameSpace) { sal_Int32 nPos = type.lastIndexOf( '/' ); if (nPos == -1) return type; if (bNoNameSpace) return type.copy(nPos+1); OStringBuffer tmpBuf(type.getLength()*2); nPos = 0; do { tmpBuf.append("::"); tmpBuf.append(type.getToken(0, '/', nPos)); } while( nPos != -1 ); return tmpBuf.makeStringAndClear(); } //************************************************************************* // shortScopedName //************************************************************************* OString scope(const OString& scope, const OString& type ) { sal_Int32 nPos = type.lastIndexOf( '/' ); if( nPos == -1 ) return OString(); // scoped name only if the namespace is not equal if (scope.lastIndexOf('/') > 0) { OString tmpScp(scope.copy(0, scope.lastIndexOf('/'))); OString tmpScp2(type.copy(0, nPos)); if (tmpScp == tmpScp2) return OString(); } OString aScope( type.copy( 0, nPos ) ); OStringBuffer tmpBuf(aScope.getLength()*2); nPos = 0; do { tmpBuf.append("::"); tmpBuf.append(aScope.getToken(0, '/', nPos)); } while( nPos != -1 ); return tmpBuf.makeStringAndClear(); }
22.570612
112
0.618705
[ "object" ]
a6c1cb016c2aa0d8b665d9dc9f7af142f42e7348
2,311
cpp
C++
RepriseMySponza/source/MeshData.cpp
HJBell/RepriseMySponza
8d851b374d51d4b57d19f0c56bba795beb5e19e5
[ "Unlicense", "MIT" ]
null
null
null
RepriseMySponza/source/MeshData.cpp
HJBell/RepriseMySponza
8d851b374d51d4b57d19f0c56bba795beb5e19e5
[ "Unlicense", "MIT" ]
null
null
null
RepriseMySponza/source/MeshData.cpp
HJBell/RepriseMySponza
8d851b374d51d4b57d19f0c56bba795beb5e19e5
[ "Unlicense", "MIT" ]
null
null
null
#include "MeshData.hpp" #include <sponza/sponza.hpp> #include <glm/glm.hpp> MeshData::MeshData() { } MeshData::~MeshData() { glDeleteBuffers(1, &positionVBO); glDeleteBuffers(1, &normalVBO); if(textureCoordVBO!=0) glDeleteBuffers(1, &textureCoordVBO); glDeleteBuffers(1, &elementVBO); glDeleteVertexArrays(1, &vao); } void MeshData::Init(const sponza::Mesh& mesh) { // Break the mesh down into its components. const auto& positions = mesh.getPositionArray(); const auto& normals = mesh.getNormalArray(); const auto& elements = mesh.getElementArray(); const auto& textureCoords = mesh.getTextureCoordinateArray(); // Create the VBOs. GenerateBuffer(positionVBO, positions.data(), positions.size() * sizeof(glm::vec3), GL_ARRAY_BUFFER, GL_STATIC_DRAW); GenerateBuffer(normalVBO, normals.data(), normals.size() * sizeof(glm::vec3), GL_ARRAY_BUFFER, GL_STATIC_DRAW); GenerateBuffer(elementVBO, elements.data(), elements.size() * sizeof(unsigned int), GL_ELEMENT_ARRAY_BUFFER, GL_STATIC_DRAW); if(textureCoords.size() > 0) GenerateBuffer(textureCoordVBO, textureCoords.data(), textureCoords.size() * sizeof(glm::vec2), GL_ARRAY_BUFFER, GL_STATIC_DRAW); // Record the element count. elementCount = elements.size(); // Create the vertex array object. glGenVertexArrays(1, &vao); glBindVertexArray(vao); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementVBO); glBindBuffer(GL_ARRAY_BUFFER, positionVBO); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), TGL_BUFFER_OFFSET(0)); glBindBuffer(GL_ARRAY_BUFFER, normalVBO); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(glm::vec3), TGL_BUFFER_OFFSET(0)); if (textureCoords.size() > 0) { glBindBuffer(GL_ARRAY_BUFFER, textureCoordVBO); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), TGL_BUFFER_OFFSET(0)); } glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void MeshData::BindVAO() const { glBindVertexArray(vao); } void MeshData::GenerateBuffer(GLuint& buffer, const void* data, GLsizeiptr size, GLenum bufferType, GLenum drawType) { glGenBuffers(1, &buffer); glBindBuffer(bufferType, buffer); glBufferData(bufferType, size, data, drawType); glBindBuffer(bufferType, 0); }
30.813333
131
0.761575
[ "mesh", "object" ]
a6c4e95b6c63a34364a9a0d2ddf18337bf881ecf
8,195
cpp
C++
src/flexible_type/flexible_type.cpp
fossabot/turicreate
a500d5e52143ad15ebdf771d9f74198982c7c45c
[ "BSD-3-Clause" ]
1
2019-04-16T19:51:18.000Z
2019-04-16T19:51:18.000Z
src/flexible_type/flexible_type.cpp
tashby/turicreate
7f07ce795833d0c56c72b3a1fb9339bed6d178d1
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
src/flexible_type/flexible_type.cpp
tashby/turicreate
7f07ce795833d0c56c72b3a1fb9339bed6d178d1
[ "BSD-3-Clause" ]
1
2020-10-21T17:46:28.000Z
2020-10-21T17:46:28.000Z
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <string> #include <boost/date_time/posix_time/posix_time.hpp> #include <flexible_type/flexible_type.hpp> #include <logger/assertions.hpp> // contains some of the bigger functions I do not want to inline namespace turi { constexpr int64_t flex_date_time::MICROSECONDS_PER_SECOND; constexpr double flex_date_time::MICROSECOND_EPSILON; constexpr int32_t flex_date_time::TIMEZONE_LOW; constexpr int32_t flex_date_time::TIMEZONE_HIGH; constexpr int32_t flex_date_time::EMPTY_TIMEZONE; constexpr int32_t flex_date_time::TIMEZONE_RESOLUTION_IN_SECONDS; constexpr int32_t flex_date_time::TIMEZONE_RESOLUTION_IN_MINUTES; constexpr double flex_date_time::TIMEZONE_RESOLUTION_IN_HOURS; constexpr int32_t flex_date_time::_LEGACY_TIMEZONE_SHIFT; namespace flexible_type_impl { boost::posix_time::ptime ptime_from_time_t(std::time_t offset, int32_t microseconds){ static const boost::posix_time::ptime time_t_epoch = boost::posix_time::from_time_t(0); static const int32_t max_int32 = std::numeric_limits<int32_t>::max(); static const int32_t min_int32 = (std::numeric_limits<int32_t>::min() + 1); boost::posix_time::ptime accum = time_t_epoch; // this is really ugly but boost posix time has some annoying 32 bit issues if(offset < 0 ){ while (offset < min_int32) { accum += boost::posix_time::seconds(min_int32); offset -= min_int32; } accum += boost::posix_time::seconds(offset); } else { while (offset > max_int32) { accum += boost::posix_time::seconds(max_int32); offset -= max_int32; } accum += boost::posix_time::seconds(offset); } accum += boost::posix_time::microseconds(microseconds); return accum; } flex_int ptime_to_time_t(const boost::posix_time::ptime & time) { boost::posix_time::time_duration dur = time - boost::posix_time::from_time_t(0); return static_cast<flex_int>(dur.ticks() / dur.ticks_per_second()); } flex_int ptime_to_fractional_microseconds(const boost::posix_time::ptime & time) { // get the time difference between the time and the integer rounded time_t // time boost::posix_time::time_duration dur = time - boost::posix_time::from_time_t(ptime_to_time_t(time)); double fractional_seconds = double(dur.ticks()) / dur.ticks_per_second(); return fractional_seconds * flex_date_time::MICROSECONDS_PER_SECOND; } std::string date_time_to_string(const flex_date_time& i) { return boost::posix_time::to_iso_string( ptime_from_time_t(i.shifted_posix_timestamp(), i.microsecond())); } flex_string get_string_visitor::operator()(const flex_vec& vec) const { std::stringstream strm; strm << "["; for (size_t i = 0; i < vec.size(); ++i) { strm << vec[i]; if (i + 1 < vec.size()) strm << " "; } strm << "]"; return strm.str(); } flex_string get_string_visitor::operator()(const flex_date_time& i) const { return date_time_to_string(i); } flex_string get_string_visitor::operator()(const flex_list& vec) const { std::stringstream strm; strm << "["; for (size_t i = 0; i < vec.size(); ++i) { if (vec[i].get_type() == flex_type_enum::STRING) { strm << "\"" << (flex_string)(vec[i]) << "\""; } else { strm << (flex_string)(vec[i]); } if (i + 1 < vec.size()) strm << ","; } strm << "]"; return strm.str(); } flex_string get_string_visitor::operator()(const flex_dict& vec) const { std::stringstream strm; strm << "{"; size_t vecsize = vec.size(); size_t i = 0; for(const auto& val: vec) { if (val.first.get_type() == flex_type_enum::STRING) { strm << "\"" << (flex_string)(val.first) << "\""; } else { strm << (flex_string)(val.first); } strm << ":"; if (val.second.get_type() == flex_type_enum::STRING) { strm << "\"" << (flex_string)(val.second) << "\""; } else { strm << (flex_string)(val.second); } if (i + 1 < vecsize) strm << ", "; ++i; } strm << "}"; return strm.str(); } flex_string get_string_visitor::operator() (const flex_image& img) const { std::stringstream strm; strm << "Height: " << img.m_height; strm << " Width: " << img.m_width; return strm.str(); } flex_vec get_vec_visitor::operator() (const flex_image& img) const { flex_vec vec; ASSERT_MSG(img.m_format == Format::RAW_ARRAY, "Cannot convert encoded image to array"); for (size_t i = 0 ; i < img.m_image_data_size; ++i){ vec.push_back(static_cast<double>(static_cast<unsigned char>(img.m_image_data[i]))); } return vec; } void soft_assignment_visitor::operator()(flex_vec& t, const flex_list& u) const { t.resize(u.size()); flexible_type ft = flex_float(); for (size_t i = 0; i < u.size(); ++i) { ft.soft_assign(u[i]); t[i] = ft.get<flex_float>(); } } bool approx_equality_operator::operator()(const flex_dict& t, const flex_dict& u) const { if (t.size() != u.size()) return false; std::unordered_multimap<flexible_type, flexible_type> d1(t.begin(), t.end()); std::unordered_multimap<flexible_type, flexible_type> d2(u.begin(), u.end()); return d1 == d2; } bool approx_equality_operator::operator()(const flex_list& t, const flex_list& u) const { if (t.size() != u.size()) return false; for (size_t i = 0; i < t.size(); ++i) if (t[i] != u[i]) return false; return true; } size_t city_hash_visitor::operator()(const flex_list& t) const { size_t h = 0; for (size_t i = 0; i < t.size(); ++i) { h = hash64_combine(h, t[i].hash()); } // The final hash is needed to distinguish nested types return turi::hash64(h); } size_t city_hash_visitor::operator()(const flex_dict& t) const { size_t key_hash = 0; size_t value_hash = 0; for(const auto& val: t) { // Use xor to ignore the order of the pairs. key_hash |= val.first.hash(); value_hash |= val.first.hash(); } return turi::hash64_combine(key_hash, value_hash); } uint128_t city_hash128_visitor::operator()(const flex_list& t) const { uint128_t h = 0; for (size_t i = 0; i < t.size(); ++i) { h = hash128_combine(h, t[i].hash128()); } // The final hash is needed to distinguish nested types return turi::hash128(h); } uint128_t city_hash128_visitor::operator()(const flex_dict& t) const { uint128_t key_hash = 0; uint128_t value_hash = 0; for(const auto& val: t) { // Use xor to ignore the order of the pairs. key_hash |= val.first.hash128(); value_hash |= val.first.hash128(); } return turi::hash128_combine(key_hash, value_hash); } } // namespace flexible_type_impl void flexible_type::erase(const flexible_type& index) { ensure_unique(); switch(get_type()) { case flex_type_enum::DICT: { flex_dict& value = val.dictval->second; for(auto iter = value.begin(); iter != value.end(); iter++) { if ((*iter).first == index) { value.erase(iter); break; } } return; } default: FLEX_TYPE_ASSERT(false); } } bool flexible_type::is_zero() const { switch(get_type()) { case flex_type_enum::INTEGER: return get<flex_int>() == 0; case flex_type_enum::FLOAT: return get<flex_float>() == 0.0; case flex_type_enum::STRING: return get<flex_string>().empty(); case flex_type_enum::VECTOR: return get<flex_vec>().empty(); case flex_type_enum::LIST: return get<flex_list>().empty(); case flex_type_enum::DICT: return get<flex_dict>().empty(); case flex_type_enum::IMAGE: return get<flex_image>().m_format == Format::UNDEFINED; case flex_type_enum::UNDEFINED: return true; default: log_and_throw("Unexpected type!"); }; __builtin_unreachable(); } bool flexible_type::is_na() const { auto the_type = get_type(); return (the_type == flex_type_enum::UNDEFINED) || (the_type == flex_type_enum::FLOAT && std::isnan(get<flex_float>())); } void flexible_type_fail(bool success) { if(!success) { log_and_throw("Invalid type conversion"); } } } // namespace turi
31.278626
89
0.669311
[ "vector" ]
a6c5b92391cbc183b891310c26271e95f8df4678
806
cpp
C++
lib/vector/VectorOperators.cpp
frndmg/simplex-method
0fe509d43ac794344b5d95f7e4faacd0dd444d56
[ "MIT" ]
2
2019-11-25T20:54:56.000Z
2019-11-25T20:55:20.000Z
lib/vector/VectorOperators.cpp
frndmg/simplex-method
0fe509d43ac794344b5d95f7e4faacd0dd444d56
[ "MIT" ]
null
null
null
lib/vector/VectorOperators.cpp
frndmg/simplex-method
0fe509d43ac794344b5d95f7e4faacd0dd444d56
[ "MIT" ]
1
2019-11-25T23:14:18.000Z
2019-11-25T23:14:18.000Z
#include "Vector.hpp" Vector Vector::operator+ () const { return *this; } Vector Vector::operator- () const { return operator*(real_t(-1)); } Vector Vector::operator+ (const real_t scalar) const { return Map([scalar](real_t val) {return val + scalar;}); } Vector Vector::operator- (const real_t scalar) const { return operator+(-scalar); } Vector Vector::operator* (const real_t scalar) const { return Map([scalar](real_t val) {return val * scalar;}); } Vector Vector::operator/ (const real_t scalar) const { ASSERT_DOMAIN(scalar != real_t(0)); return operator*(1 / scalar); } Vector Vector::operator+ (const Vector &B) const { ASSERT_DOMAIN(Size() == B.Size()); return Map(*this, B, std::plus <real_t>()); } Vector Vector::operator- (const Vector &B) const { return operator+(-B); }
20.15
57
0.679901
[ "vector" ]
a6c80511a037dc546aac1baccf3eb2bd1d6c8e90
10,708
cpp
C++
PlanarSelect.cpp
Qt-Widgets/PothosWidgets
df3ee1fa012556a0095a4bd449f2ed0ffdc50e65
[ "BSL-1.0" ]
5
2017-12-22T08:04:44.000Z
2020-07-29T09:22:47.000Z
PlanarSelect.cpp
Qt-Widgets/PothosWidgets
df3ee1fa012556a0095a4bd449f2ed0ffdc50e65
[ "BSL-1.0" ]
null
null
null
PlanarSelect.cpp
Qt-Widgets/PothosWidgets
df3ee1fa012556a0095a4bd449f2ed0ffdc50e65
[ "BSL-1.0" ]
7
2018-05-24T21:28:46.000Z
2022-03-24T06:19:51.000Z
// Copyright (c) 2014-2021 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include <Pothos/Framework.hpp> #include <QGroupBox> #include <QGraphicsView> #include <QGraphicsScene> #include <QGraphicsObject> #include <QHBoxLayout> #include <QResizeEvent> #include <QMouseEvent> #include <QPainter> #include <vector> #include <complex> #include <iostream> #include <algorithm> //min/max /*********************************************************************** * Draggable crosshairs for point selection **********************************************************************/ class PlanarSelectCrossHairs : public QGraphicsObject { Q_OBJECT public: PlanarSelectCrossHairs(void): _length(10) { this->setFlag(QGraphicsItem::ItemIsMovable); this->setFlag(QGraphicsItem::ItemIsSelectable); this->setFlag(QGraphicsItem::ItemSendsGeometryChanges); } QRectF boundingRect(void) const { return QRectF(QPointF(-_length/2, -_length/2), QSizeF(_length, _length)); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { painter->setPen(Qt::black); painter->drawLine(QPointF(0, -_length/2), QPointF(0, _length/2)); painter->drawLine(QPointF(-_length/2, 0), QPointF(_length/2, 0)); } signals: void positionChanged(const QPointF &); protected: QVariant itemChange(GraphicsItemChange change, const QVariant &value) { if (change == ItemPositionChange) emit this->positionChanged(value.toPointF()); return QGraphicsObject::itemChange(change, value); } private: qreal _length; }; /*********************************************************************** * Custom scene with axis background **********************************************************************/ class PlanarSelectGraphicsScene : public QGraphicsScene { Q_OBJECT public: PlanarSelectGraphicsScene(QObject *parent): QGraphicsScene(parent) { return; } void drawBackground(QPainter *painter, const QRectF &rect) { QGraphicsScene::drawBackground(painter, rect); static const QColor lightGray("#D0D0D0"); painter->setPen(lightGray); qreal x = this->sceneRect().center().x(); qreal y = this->sceneRect().center().y(); qreal width = this->sceneRect().width(); qreal height = this->sceneRect().height(); //main center lines painter->drawLine(QPointF(x, y-height/2), QPointF(x, y+height/2)); painter->drawLine(QPointF(x-width/2, y), QPointF(x+width/2, y)); //half-way lines qreal length = 5; painter->drawLine(QPointF(x-width/4, y-length), QPointF(x-width/4, y+length)); painter->drawLine(QPointF(x+width/4, y-length), QPointF(x+width/4, y+length)); painter->drawLine(QPointF(x-length, y-height/4), QPointF(x+length, y-height/4)); painter->drawLine(QPointF(x-length, y+height/4), QPointF(x+length, y+height/4)); } }; /*********************************************************************** * Custom view with scene resize **********************************************************************/ class PlanarSelectGraphicsView : public QGraphicsView { Q_OBJECT public: PlanarSelectGraphicsView(QWidget *parent): QGraphicsView(parent), _crossHairs(new PlanarSelectCrossHairs()) { this->setScene(new PlanarSelectGraphicsScene(this)); this->scene()->setBackgroundBrush(Qt::white); this->scene()->addItem(_crossHairs); //set high quality rendering this->setRenderHint(QPainter::Antialiasing); this->setRenderHint(QPainter::SmoothPixmapTransform); //forward position changed signal connect(_crossHairs, &PlanarSelectCrossHairs::positionChanged, this, &PlanarSelectGraphicsView::handleCrossHairsPointChanged); } QPointF getPosition(void) const { return this->scenePosToRelPos(_crossHairs->pos()); } public slots: void setPosition(const QPointF &rel_) { //clip to 0.0 -> 1.0 to keep in bounds QPointF rel( std::max(std::min(rel_.x(), 1.0), 0.0), std::max(std::min(rel_.y(), 1.0), 0.0)); const auto sr = this->scene()->sceneRect(); const auto p = QPointF(rel.x()*sr.width(), (1.0-rel.y())*sr.height()); _crossHairs->setPos(p + sr.topLeft()); } signals: void positionChanged(const QPointF &); private slots: void handleCrossHairsPointChanged(const QPointF &pos) { emit this->positionChanged(this->scenePosToRelPos(pos)); } protected: void resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); bool oldState = this->blockSignals(true); const auto p = this->getPosition(); this->scene()->setSceneRect(QRectF(QPointF(), event->size())); this->setPosition(p); this->blockSignals(oldState); } void mousePressEvent(QMouseEvent *mouseEvent) { QGraphicsView::mousePressEvent(mouseEvent); if (mouseEvent->button() == Qt::LeftButton) { mouseEvent->accept(); const auto pos = this->scenePosToRelPos(this->mapToScene(mouseEvent->pos())); this->setPosition(pos); emit this->positionChanged(pos); } } private: QPointF scenePosToRelPos(const QPointF &scenePos) const { const auto sr = this->scene()->sceneRect(); auto p = scenePos - sr.topLeft(); return QPointF(p.x()/sr.width(), 1.0-(p.y()/sr.height())); } PlanarSelectCrossHairs *_crossHairs; }; /*********************************************************************** * |PothosDoc Planar Select * * A two-dimensional point selection widget. * The point is changed graphically by dragging a crosshair across a rectangular region. * When the crosshair point is changed, the new value is emitted * as a two dimensional vector of doubles through the "valueChanged" signal, * and as a complex number through the "complexValueChanged" signal. * * |category /Widgets * |keywords 2d plane cartesian complex * * |param title The name of the value displayed by this widget * |default "My Coordinate" * |widget StringEntry() * * |param value The initial value of this slider. * |default [0.0, 0.0] * * |param minimum The smallest X and Y bounds of the selection. * |default [-1.0, -1.0] * * |param maximum The largest X and Y bounds of the selection. * |default [1.0, 1.0] * * |mode graphWidget * |factory /widgets/planar_select() * |setter setTitle(title) * |setter setMinimum(minimum) * |setter setMaximum(maximum) * |setter setValue(value) **********************************************************************/ class PlanarSelect : public QGroupBox, public Pothos::Block { Q_OBJECT public: static Block *make(void) { return new PlanarSelect(); } PlanarSelect(void): _view(new PlanarSelectGraphicsView(this)), _layout(new QHBoxLayout(this)) { this->setStyleSheet("QGroupBox {font-weight: bold;}"); this->registerCall(this, POTHOS_FCN_TUPLE(PlanarSelect, widget)); this->registerCall(this, POTHOS_FCN_TUPLE(PlanarSelect, value)); this->registerCall(this, POTHOS_FCN_TUPLE(PlanarSelect, setTitle)); this->registerCall(this, POTHOS_FCN_TUPLE(PlanarSelect, setValue)); this->registerCall(this, POTHOS_FCN_TUPLE(PlanarSelect, setMinimum)); this->registerCall(this, POTHOS_FCN_TUPLE(PlanarSelect, setMaximum)); this->registerSignal("valueChanged"); this->registerSignal("complexValueChanged"); _layout->addWidget(_view); _layout->setContentsMargins(QMargins()); _layout->setSpacing(0); connect(_view, &PlanarSelectGraphicsView::positionChanged, this, &PlanarSelect::handlePositionChanged); } QWidget *widget(void) { return this; } void setTitle(const QString &title) { QMetaObject::invokeMethod(this, "handleSetTitle", Qt::QueuedConnection, Q_ARG(QString, title)); } std::vector<double> value(void) const { std::vector<double> vals(2); vals[0] = _value.x(); vals[1] = _value.y(); return vals; } std::complex<double> complexValue(void) const { return std::complex<double>(_value.x(), _value.y()); } void setValue(const std::vector<double> &value) { if (value.size() != 2) throw Pothos::RangeException("PlanarSelect::setValue()", "value size must be 2"); _value = QPointF(value[0], value[1]); const auto pos = _value - _minimum; const auto range = _maximum - _minimum; const QPointF viewPos(pos.x()/range.x(), pos.y()/range.y()); QMetaObject::invokeMethod(_view, "setPosition", Qt::QueuedConnection, Q_ARG(QPointF, viewPos)); } void setMinimum(const std::vector<double> &minimum) { if (minimum.size() != 2) throw Pothos::RangeException("PlanarSelect::setMinimum()", "minimum size must be 2"); _minimum = QPointF(minimum[0], minimum[1]); } void setMaximum(const std::vector<double> &maximum) { if (maximum.size() != 2) throw Pothos::RangeException("PlanarSelect::setMaximum()", "maximum size must be 2"); _maximum = QPointF(maximum[0], maximum[1]); } void activate(void) { //emit current value when design becomes active this->emitValuesChanged(); } public slots: QVariant saveState(void) const { return _value; } void restoreState(const QVariant &state) { _value = state.toPointF(); this->setValue(this->value()); } private slots: void handlePositionChanged(const QPointF &pos) { const auto range = _maximum - _minimum; _value = QPointF(pos.x()*range.x(), pos.y()*range.y()) + _minimum; this->emitValuesChanged(); } void handleSetTitle(const QString &title) { QGroupBox::setTitle(title); } protected: void mousePressEvent(QMouseEvent *event) { QGroupBox::mousePressEvent(event); event->ignore(); //allows for dragging from QGroupBox title } private: void emitValuesChanged(void) { this->emitSignal("valueChanged", this->value()); this->emitSignal("complexValueChanged", this->complexValue()); } QPointF _minimum; QPointF _maximum; QPointF _value; PlanarSelectGraphicsView *_view; QHBoxLayout *_layout; }; static Pothos::BlockRegistry registerPlanarSelect( "/widgets/planar_select", &PlanarSelect::make); #include "PlanarSelect.moc"
30.770115
134
0.615334
[ "vector" ]
a6ce46a2ee17747b9f66748e0b4ad6e4938ffb01
2,339
hpp
C++
src/formula_tokenizer.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
src/formula_tokenizer.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
src/formula_tokenizer.hpp
sweetkristas/anura
5e8cbcfc7b761c5c01e5c5509a0fb159b8fb60cd
[ "CC0-1.0" ]
null
null
null
/* Copyright (C) 2003-2013 by David White <davewx7@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FORMULA_TOKENIZER_HPP_INCLUDED #define FORMULA_TOKENIZER_HPP_INCLUDED #include <string.h> #include <algorithm> #include <string> #include <vector> namespace formula_tokenizer { typedef std::string::const_iterator iterator; enum FFL_TOKEN_TYPE { TOKEN_OPERATOR, TOKEN_STRING_LITERAL, TOKEN_CONST_IDENTIFIER, TOKEN_IDENTIFIER, TOKEN_INTEGER, TOKEN_DECIMAL, TOKEN_LPARENS, TOKEN_RPARENS, TOKEN_LSQUARE, TOKEN_RSQUARE, TOKEN_LBRACKET, TOKEN_RBRACKET, TOKEN_LDUBANGLE, TOKEN_RDUBANGLE, TOKEN_COMMA, TOKEN_SEMICOLON, TOKEN_COLON, TOKEN_WHITESPACE, TOKEN_KEYWORD, TOKEN_COMMENT, TOKEN_POINTER, TOKEN_LEFT_POINTER, TOKEN_PIPE, TOKEN_ELLIPSIS, TOKEN_INVALID }; struct token { FFL_TOKEN_TYPE type; iterator begin, end; bool equals(const char* s) const { return end - begin == strlen(s) && std::equal(begin, end, s); } }; token get_token(iterator& i1, iterator i2); struct token_error { token_error(const std::string& m); std::string msg; }; //A special interface for searching for and matching tokens. class token_matcher { public: token_matcher(); explicit token_matcher(FFL_TOKEN_TYPE type); token_matcher& add(FFL_TOKEN_TYPE type); token_matcher& add(const std::string& str); bool match(const token& t) const; //Find the first matching token within the given range and return it. //Does not return tokens that are inside any kinds of brackets. bool find_match(const token*& i1, const token* i2) const; private: std::vector<FFL_TOKEN_TYPE> types_; std::vector<std::string> str_; }; } #endif
29.607595
99
0.735785
[ "vector" ]
a6d6356c2829b6f61451fbf95c8683b8610d3802
1,351
cpp
C++
plugin/gui/line_wrap.cpp
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
2
2018-03-19T23:27:47.000Z
2018-06-24T16:15:19.000Z
plugin/gui/line_wrap.cpp
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
null
null
null
plugin/gui/line_wrap.cpp
cristivlas/zerobugs
5f080c8645b123d7887fd8a64f60e8d226e3b1d5
[ "BSL-1.0" ]
1
2021-11-28T05:39:05.000Z
2021-11-28T05:39:05.000Z
// ------------------------------------------------------------------------- // This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // ------------------------------------------------------------------------- // // $Id$ // #include <cassert> #include <vector> #include "line_wrap.h" std::string line_wrap(const std::string& message, size_t maxw) { if (message.length() < maxw) { return message; } else { const size_t length = message.length(); const size_t count = length / maxw; std::vector<std::string> lines(count); for (size_t i = 0; i != count; ++i) { lines[i] = message.substr(maxw * i, maxw); } std::string result; for (size_t i = 0;;) { result += lines[i]; if (++i == count) { if ((i = length % maxw) != 0) { result += "\n"; result += message.substr(length - i); } break; } result += "\n"; } return result; } } // vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
27.02
76
0.440415
[ "vector" ]
a6db7f9a56e880ccbb60131016b7e9f04ebed61e
1,781
hpp
C++
utils.hpp
cmazieri-hcl/phosphor-bmc-code-mgmt
16aa28a057a3d8036ea5a0e963ebb731c3a6ab43
[ "Apache-2.0" ]
null
null
null
utils.hpp
cmazieri-hcl/phosphor-bmc-code-mgmt
16aa28a057a3d8036ea5a0e963ebb731c3a6ab43
[ "Apache-2.0" ]
null
null
null
utils.hpp
cmazieri-hcl/phosphor-bmc-code-mgmt
16aa28a057a3d8036ea5a0e963ebb731c3a6ab43
[ "Apache-2.0" ]
1
2021-08-16T12:55:54.000Z
2021-08-16T12:55:54.000Z
#include "config.h" #include <sdbusplus/server.hpp> #include <fstream> #include <map> #include <string> namespace utils { /** * @brief Get the bus service * * @return the bus service as a string **/ std::string getService(sdbusplus::bus::bus& bus, const std::string& path, const std::string& interface); /** * @brief Merge more files * * @param[in] srcFiles - source files * @param[out] dstFile - destination file * @return **/ void mergeFiles(std::vector<std::string>& srcFiles, std::string& dstFile); namespace internal { /** * @brief Construct an argument vector to be used with an exec command, which * requires the name of the executable to be the first argument, and a * null terminator to be the last. * @param[in] name - Name of the executable * @param[in] args - Optional arguments * @return char* vector */ template <typename... Arg> constexpr auto constructArgv(const char* name, Arg&&... args) { std::vector<char*> argV{ {const_cast<char*>(name), const_cast<char*>(args)..., nullptr}}; return argV; } /** * @brief Helper function to execute command in child process * @param[in] path - Fully qualified name of the executable to run * @param[in] args - Optional arguments * @return 0 on success */ int executeCmd(const char* path, char** args); } // namespace internal /** * @brief Execute command in child process * @param[in] path - Fully qualified name of the executable to run * @param[in] args - Optional arguments * @return 0 on success */ template <typename... Arg> int execute(const char* path, Arg&&... args) { auto argArray = internal::constructArgv(path, std::forward<Arg>(args)...); return internal::executeCmd(path, argArray.data()); } } // namespace utils
24.39726
78
0.670971
[ "vector" ]
a6de3b1f7ec061cd9ef4904958ef6298f58de96c
1,979
cpp
C++
aws-cpp-sdk-lightsail/source/model/InputOrigin.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-lightsail/source/model/InputOrigin.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-lightsail/source/model/InputOrigin.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/lightsail/model/InputOrigin.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Lightsail { namespace Model { InputOrigin::InputOrigin() : m_nameHasBeenSet(false), m_regionName(RegionName::NOT_SET), m_regionNameHasBeenSet(false), m_protocolPolicy(OriginProtocolPolicyEnum::NOT_SET), m_protocolPolicyHasBeenSet(false) { } InputOrigin::InputOrigin(JsonView jsonValue) : m_nameHasBeenSet(false), m_regionName(RegionName::NOT_SET), m_regionNameHasBeenSet(false), m_protocolPolicy(OriginProtocolPolicyEnum::NOT_SET), m_protocolPolicyHasBeenSet(false) { *this = jsonValue; } InputOrigin& InputOrigin::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("name")) { m_name = jsonValue.GetString("name"); m_nameHasBeenSet = true; } if(jsonValue.ValueExists("regionName")) { m_regionName = RegionNameMapper::GetRegionNameForName(jsonValue.GetString("regionName")); m_regionNameHasBeenSet = true; } if(jsonValue.ValueExists("protocolPolicy")) { m_protocolPolicy = OriginProtocolPolicyEnumMapper::GetOriginProtocolPolicyEnumForName(jsonValue.GetString("protocolPolicy")); m_protocolPolicyHasBeenSet = true; } return *this; } JsonValue InputOrigin::Jsonize() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("name", m_name); } if(m_regionNameHasBeenSet) { payload.WithString("regionName", RegionNameMapper::GetNameForRegionName(m_regionName)); } if(m_protocolPolicyHasBeenSet) { payload.WithString("protocolPolicy", OriginProtocolPolicyEnumMapper::GetNameForOriginProtocolPolicyEnum(m_protocolPolicy)); } return payload; } } // namespace Model } // namespace Lightsail } // namespace Aws
21.51087
129
0.746337
[ "model" ]
a6de8445c265aecadefeeb34280719e9ac810f1d
10,576
cpp
C++
ares/component/processor/sm83/instructions.cpp
moon-chilled/Ares
909fb098c292f8336d0502dc677050312d8b5c81
[ "0BSD" ]
7
2020-07-25T11:44:39.000Z
2021-01-29T13:21:31.000Z
ares/component/processor/sm83/instructions.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
null
null
null
ares/component/processor/sm83/instructions.cpp
jchw-forks/ares
d78298a1e95fd0ce65feabfd4f13b60e31210a7a
[ "0BSD" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
auto SM83::instructionADC_Direct_Data(uint8& target) -> void { target = ADD(target, operand(), CF); } auto SM83::instructionADC_Direct_Direct(uint8& target, uint8& source) -> void { target = ADD(target, source, CF); } auto SM83::instructionADC_Direct_Indirect(uint8& target, uint16& source) -> void { target = ADD(target, read(source), CF); } auto SM83::instructionADD_Direct_Data(uint8& target) -> void { target = ADD(target, operand()); } auto SM83::instructionADD_Direct_Direct(uint8& target, uint8& source) -> void { target = ADD(target, source); } auto SM83::instructionADD_Direct_Direct(uint16& target, uint16& source) -> void { idle(); uint32 x = target + source; uint32 y = (uint12)target + (uint12)source; target = x; CF = x > 0xffff; HF = y > 0x0fff; NF = 0; } auto SM83::instructionADD_Direct_Indirect(uint8& target, uint16& source) -> void { target = ADD(target, read(source)); } auto SM83::instructionADD_Direct_Relative(uint16& target) -> void { auto data = operand(); idle(); idle(); CF = (uint8)target + (uint8)data > 0xff; HF = (uint4)target + (uint4)data > 0x0f; NF = ZF = 0; target += (int8)data; } auto SM83::instructionAND_Direct_Data(uint8& target) -> void { target = AND(target, operand()); } auto SM83::instructionAND_Direct_Direct(uint8& target, uint8& source) -> void { target = AND(target, source); } auto SM83::instructionAND_Direct_Indirect(uint8& target, uint16& source) -> void { target = AND(target, read(source)); } auto SM83::instructionBIT_Index_Direct(uint3 index, uint8& data) -> void { BIT(index, data); } auto SM83::instructionBIT_Index_Indirect(uint3 index, uint16& address) -> void { auto data = read(address); BIT(index, data); } auto SM83::instructionCALL_Condition_Address(bool take) -> void { auto address = operands(); if(!take) return; idle(); push(PC); PC = address; } auto SM83::instructionCCF() -> void { CF = !CF; HF = NF = 0; } auto SM83::instructionCP_Direct_Data(uint8& target) -> void { CP(target, operand()); } auto SM83::instructionCP_Direct_Direct(uint8& target, uint8& source) -> void { CP(target, source); } auto SM83::instructionCP_Direct_Indirect(uint8& target, uint16& source) -> void { CP(target, read(source)); } auto SM83::instructionCPL() -> void { A = ~A; HF = NF = 1; } auto SM83::instructionDAA() -> void { uint16 a = A; if(!NF) { if(HF || (uint4)a > 0x09) a += 0x06; if(CF || (uint8)a > 0x9f) a += 0x60; } else { if(HF) { a -= 0x06; if(!CF) a &= 0xff; } if(CF) a -= 0x60; } A = a; CF |= a.bit(8); HF = 0; ZF = A == 0; } auto SM83::instructionDEC_Direct(uint8& data) -> void { data = DEC(data); } auto SM83::instructionDEC_Direct(uint16& data) -> void { idle(); data--; } auto SM83::instructionDEC_Indirect(uint16& address) -> void { auto data = read(address); write(address, DEC(data)); } auto SM83::instructionDI() -> void { r.ime = 0; } auto SM83::instructionEI() -> void { r.ei = 1; } auto SM83::instructionHALT() -> void { r.halt = 1; while(r.halt) halt(); } auto SM83::instructionINC_Direct(uint8& data) -> void { data = INC(data); } auto SM83::instructionINC_Direct(uint16& data) -> void { idle(); data++; } auto SM83::instructionINC_Indirect(uint16& address) -> void { auto data = read(address); write(address, INC(data)); } auto SM83::instructionJP_Condition_Address(bool take) -> void { auto address = operands(); if(!take) return; idle(); PC = address; } auto SM83::instructionJP_Direct(uint16& data) -> void { PC = data; } auto SM83::instructionJR_Condition_Relative(bool take) -> void { auto data = operand(); if(!take) return; idle(); PC += (int8)data; } auto SM83::instructionLD_Address_Direct(uint8& data) -> void { write(operands(), data); } auto SM83::instructionLD_Address_Direct(uint16& data) -> void { store(operands(), data); } auto SM83::instructionLD_Direct_Address(uint8& data) -> void { data = read(operands()); } auto SM83::instructionLD_Direct_Data(uint8& target) -> void { target = operand(); } auto SM83::instructionLD_Direct_Data(uint16& target) -> void { target = operands(); } auto SM83::instructionLD_Direct_Direct(uint8& target, uint8& source) -> void { target = source; } auto SM83::instructionLD_Direct_Direct(uint16& target, uint16& source) -> void { idle(); target = source; } auto SM83::instructionLD_Direct_DirectRelative(uint16& target, uint16& source) -> void { auto data = operand(); idle(); CF = (uint8)source + (uint8)data > 0xff; HF = (uint4)source + (uint4)data > 0x0f; NF = ZF = 0; target = source + (int8)data; } auto SM83::instructionLD_Direct_Indirect(uint8& target, uint16& source) -> void { target = read(source); } auto SM83::instructionLD_Direct_IndirectDecrement(uint8& target, uint16& source) -> void { target = read(source--); } auto SM83::instructionLD_Direct_IndirectIncrement(uint8& target, uint16& source) -> void { target = read(source++); } auto SM83::instructionLD_Indirect_Data(uint16& target) -> void { write(target, operand()); } auto SM83::instructionLD_Indirect_Direct(uint16& target, uint8& source) -> void { write(target, source); } auto SM83::instructionLD_IndirectDecrement_Direct(uint16& target, uint8& source) -> void { write(target--, source); } auto SM83::instructionLD_IndirectIncrement_Direct(uint16& target, uint8& source) -> void { write(target++, source); } auto SM83::instructionLDH_Address_Direct(uint8& data) -> void { write(0xff00 | operand(), data); } auto SM83::instructionLDH_Direct_Address(uint8& data) -> void { data = read(0xff00 | operand()); } auto SM83::instructionLDH_Direct_Indirect(uint8& target, uint8& source) -> void { target = read(0xff00 | source); } auto SM83::instructionLDH_Indirect_Direct(uint8& target, uint8& source) -> void { write(0xff00 | target, source); } auto SM83::instructionNOP() -> void { } auto SM83::instructionOR_Direct_Data(uint8& target) -> void { target = OR(target, operand()); } auto SM83::instructionOR_Direct_Direct(uint8& target, uint8& source) -> void { target = OR(target, source); } auto SM83::instructionOR_Direct_Indirect(uint8& target, uint16& source) -> void { target = OR(target, read(source)); } auto SM83::instructionPOP_Direct(uint16& data) -> void { data = pop(); } auto SM83::instructionPOP_Direct_AF(uint16& data) -> void { data = pop() & ~15; //flag bits 0-3 are forced to zero } auto SM83::instructionPUSH_Direct(uint16& data) -> void { idle(); push(data); } auto SM83::instructionRES_Index_Direct(uint3 index, uint8& data) -> void { data.bit(index) = 0; } auto SM83::instructionRES_Index_Indirect(uint3 index, uint16& address) -> void { auto data = read(address); data.bit(index) = 0; write(address, data); } auto SM83::instructionRET() -> void { auto address = pop(); idle(); PC = address; } auto SM83::instructionRET_Condition(bool take) -> void { idle(); if(!take) return; PC = pop(); idle(); } auto SM83::instructionRETI() -> void { auto address = pop(); idle(); PC = address; r.ime = 1; } auto SM83::instructionRL_Direct(uint8& data) -> void { data = RL(data); } auto SM83::instructionRL_Indirect(uint16& address) -> void { auto data = read(address); write(address, RL(data)); } auto SM83::instructionRLA() -> void { A = RL(A); ZF = 0; } auto SM83::instructionRLC_Direct(uint8& data) -> void { data = RLC(data); } auto SM83::instructionRLC_Indirect(uint16& address) -> void { auto data = read(address); write(address, RLC(data)); } auto SM83::instructionRLCA() -> void { A = RLC(A); ZF = 0; } auto SM83::instructionRR_Direct(uint8& data) -> void { data = RR(data); } auto SM83::instructionRR_Indirect(uint16& address) -> void { auto data = read(address); write(address, RR(data)); } auto SM83::instructionRRA() -> void { A = RR(A); ZF = 0; } auto SM83::instructionRRC_Direct(uint8& data) -> void { data = RRC(data); } auto SM83::instructionRRC_Indirect(uint16& address) -> void { auto data = read(address); write(address, RRC(data)); } auto SM83::instructionRRCA() -> void { A = RRC(A); ZF = 0; } auto SM83::instructionRST_Implied(uint8 vector) -> void { idle(); push(PC); PC = vector; } auto SM83::instructionSBC_Direct_Data(uint8& target) -> void { target = SUB(target, operand(), CF); } auto SM83::instructionSBC_Direct_Direct(uint8& target, uint8& source) -> void { target = SUB(target, source, CF); } auto SM83::instructionSBC_Direct_Indirect(uint8& target, uint16& source) -> void { target = SUB(target, read(source), CF); } auto SM83::instructionSCF() -> void { CF = 1; HF = NF = 0; } auto SM83::instructionSET_Index_Direct(uint3 index, uint8& data) -> void { data.bit(index) = 1; } auto SM83::instructionSET_Index_Indirect(uint3 index, uint16& address) -> void { auto data = read(address); data.bit(index) = 1; write(address, data); } auto SM83::instructionSLA_Direct(uint8& data) -> void { data = SLA(data); } auto SM83::instructionSLA_Indirect(uint16& address) -> void { auto data = read(address); write(address, SLA(data)); } auto SM83::instructionSRA_Direct(uint8& data) -> void { data = SRA(data); } auto SM83::instructionSRA_Indirect(uint16& address) -> void { auto data = read(address); write(address, SRA(data)); } auto SM83::instructionSRL_Direct(uint8& data) -> void { data = SRL(data); } auto SM83::instructionSRL_Indirect(uint16& address) -> void { auto data = read(address); write(address, SRL(data)); } auto SM83::instructionSTOP() -> void { if(!stoppable()) return; r.stop = 1; while(r.stop) stop(); } auto SM83::instructionSUB_Direct_Data(uint8& target) -> void { target = SUB(target, operand()); } auto SM83::instructionSUB_Direct_Direct(uint8& target, uint8& source) -> void { target = SUB(target, source); } auto SM83::instructionSUB_Direct_Indirect(uint8& target, uint16& source) -> void { target = SUB(target, read(source)); } auto SM83::instructionSWAP_Direct(uint8& data) -> void { data = SWAP(data); } auto SM83::instructionSWAP_Indirect(uint16& address) -> void { auto data = read(address); write(address, SWAP(data)); } auto SM83::instructionXOR_Direct_Data(uint8& target) -> void { target = XOR(target, operand()); } auto SM83::instructionXOR_Direct_Direct(uint8& target, uint8& source) -> void { target = XOR(target, source); } auto SM83::instructionXOR_Direct_Indirect(uint8& target, uint16& source) -> void { target = XOR(target, read(source)); }
22.646681
90
0.673033
[ "vector" ]
a6defbf18a663e62b9bb9ba51dba4e69ef022eb0
31,980
cc
C++
src/tools/builder/pipelines/material_pipeline.cc
ProjectSulphur/ProjectSulphur
cb9ee8298f5020fda4a9130802e72034408f050f
[ "Apache-2.0" ]
11
2017-12-19T14:33:02.000Z
2022-03-26T00:34:48.000Z
src/tools/builder/pipelines/material_pipeline.cc
ProjectSulphur/ProjectSulphur
cb9ee8298f5020fda4a9130802e72034408f050f
[ "Apache-2.0" ]
1
2018-05-28T10:32:32.000Z
2018-05-28T10:32:35.000Z
src/tools/builder/pipelines/material_pipeline.cc
ProjectSulphur/ProjectSulphur
cb9ee8298f5020fda4a9130802e72034408f050f
[ "Apache-2.0" ]
1
2021-01-25T11:31:57.000Z
2021-01-25T11:31:57.000Z
#include "tools/builder/pipelines/material_pipeline.h" #include "tools/builder/pipelines/texture_pipeline.h" #include "tools/builder/pipelines/shader_pipeline.h" #include "tools/builder/shared/util.h" #include "tools/builder/pipelines/scene_loader.h" #include <foundation/io/binary_writer.h> #include <foundation/logging/logger.h> #include <foundation/pipeline-assets/shader.h> #include <foundation/pipeline-assets/model.h> #include <assimp/scene.h> #include <glm/glm.hpp> namespace sulphur { namespace builder { //-------------------------------------------------------------------------------- bool MaterialPipeline::Create(const aiScene* scene, const foundation::Path& scene_directory, ModelFileType model_file_type, ShaderPipeline& shader_pipeline, foundation::ModelTextureCache& texture_cache, const foundation::AssetName& vertex_shader, const foundation::AssetName& pixel_shader, foundation::Vector<foundation::MaterialAsset>& materials) const { if (scene == nullptr) { PS_LOG_BUILDER(Error, "scene == nullptr. No materials created."); return false; } foundation::AssetID vertex_shader_id = foundation::GenerateId(vertex_shader); foundation::AssetID geometry_shader_id = 0; foundation::AssetID pixel_shader_id = foundation::GenerateId(pixel_shader); // Get shader reflection data foundation::Vector<foundation::ShaderResource> uniform_buffers = {}; foundation::Vector<foundation::ShaderResource> textures = {}; foundation::Vector<foundation::ShaderResource> samplers = {}; if (GetCombinedReflectedShaderData(shader_pipeline, vertex_shader_id, geometry_shader_id, pixel_shader_id, uniform_buffers, textures, samplers) == false) { PS_LOG_BUILDER(Error, "Vertex and fragment shader are incompatible."); return false; } const size_t initial_size = materials.size(); materials.reserve(initial_size + scene->mNumMaterials); for (unsigned int i = 0u; i < scene->mNumMaterials; ++i) { const aiMaterial* ai_mat = scene->mMaterials[i]; foundation::MaterialAsset material = {}; // Get the name aiString ai_string = {}; if (ai_mat->Get(AI_MATKEY_NAME, ai_string) != AI_SUCCESS) { PS_LOG_BUILDER(Error, "Material has no name. All assets must have names. Results should be discarded."); return false; } material.name = ai_string.C_Str(); // Set the shaders material.data.vertex_shader_id = vertex_shader_id; material.data.pixel_shader_id = pixel_shader_id; // Create shader resources material.data.uniform_buffers.resize(uniform_buffers.size()); for(int j = 0; j < uniform_buffers.size(); ++j) { material.data.uniform_buffers[j].data.resize(uniform_buffers[j].size); } material.data.separate_images.resize(textures.size(), 0); material.data.separate_samplers.resize(samplers.size()); // Model type specific data if(model_file_type == ModelFileType::kFBX) { } else if(model_file_type == ModelFileType::kOBJ) { } else if(model_file_type == ModelFileType::kglTF) { float ai_float = 0.0f; if (ai_mat->Get("$mat.gltf.pbrMetallicRoughness.metallicFactor", 0, 0, ai_float) == AI_SUCCESS) { FindAndSetUniform(uniform_buffers, material.data.uniform_buffers, "ps_float_metallic", ai_float); } if (ai_mat->Get("$mat.gltf.pbrMetallicRoughness.roughnessFactor", 0, 0, ai_float) == AI_SUCCESS) { FindAndSetUniform(uniform_buffers, material.data.uniform_buffers, "ps_float_roughness", ai_float); } } { // Get ambient color aiColor4D ai_color4d = {}; if (ai_mat->Get(AI_MATKEY_COLOR_AMBIENT, ai_color4d) == AI_SUCCESS) { FindAndSetUniform(uniform_buffers, material.data.uniform_buffers, "ps_color_ambient", *reinterpret_cast<glm::vec4*>(&ai_color4d)); } // Get diffuse color if (ai_mat->Get(AI_MATKEY_COLOR_DIFFUSE, ai_color4d) == AI_SUCCESS) { FindAndSetUniform(uniform_buffers, material.data.uniform_buffers, "ps_color_diffuse", *reinterpret_cast<glm::vec4*>(&ai_color4d)); } // Get specular color if (ai_mat->Get(AI_MATKEY_COLOR_SPECULAR, ai_color4d) == AI_SUCCESS) { FindAndSetUniform(uniform_buffers, material.data.uniform_buffers, "ps_color_specular", *reinterpret_cast<glm::vec4*>(&ai_color4d)); } // Get emissive color if (ai_mat->Get(AI_MATKEY_COLOR_EMISSIVE, ai_color4d) == AI_SUCCESS) { FindAndSetUniform(uniform_buffers, material.data.uniform_buffers, "ps_color_emissive", *reinterpret_cast<glm::vec4*>(&ai_color4d)); } // Get wireframe enabled int ai_int = 0; if (ai_mat->Get(AI_MATKEY_ENABLE_WIREFRAME, ai_int) == AI_SUCCESS) { material.data.wireframe = ai_int > 0; } // Get backface_culling if (ai_mat->Get(AI_MATKEY_TWOSIDED, ai_int) == AI_SUCCESS) { material.data.backface_culling = ai_int <= 0; } // Get blend function if (ai_mat->Get(AI_MATKEY_BLEND_FUNC, ai_int) == AI_SUCCESS) { switch(ai_int) { case aiBlendMode_Default: material.data.blend_function = foundation::BlendMode::kDefault; break; case aiBlendMode_Additive: material.data.blend_function = foundation::BlendMode::kAdditive; break; default: material.data.blend_function = foundation::BlendMode::kNone; break; } } // Get opacity float ai_float = 0.0f; if (ai_mat->Get(AI_MATKEY_OPACITY, ai_float) == AI_SUCCESS) { FindAndSetUniform(uniform_buffers, material.data.uniform_buffers, "ps_float_opacity", ai_float); if(ai_float >= 1.0f) material.data.blend_function = foundation::BlendMode::kNone; else if(material.data.blend_function == foundation::BlendMode::kNone) material.data.blend_function = foundation::BlendMode::kDefault; } // Get roughness if (ai_mat->Get(AI_MATKEY_SHININESS, ai_float) == AI_SUCCESS) { ai_float = 1.0f - ai_float * 0.001f; // Shininess is oposite of roughness FindAndSetUniform(uniform_buffers, material.data.uniform_buffers, "ps_float_roughness", ai_float); } } { // Get albedo texture if (LoadTexture(ai_mat, aiTextureType_DIFFUSE, scene_directory, texture_cache, textures, material.data) == false) { return false; } // Get normal texture if (LoadTexture(ai_mat, aiTextureType_NORMALS, scene_directory, texture_cache, textures, material.data) == false) { return false; } // Get metallic texture if (LoadTexture(ai_mat, aiTextureType_SPECULAR, scene_directory, texture_cache, textures, material.data) == false) { return false; } // Get roughness texture if (LoadTexture(ai_mat, aiTextureType_SHININESS, scene_directory, texture_cache, textures, material.data) == false) { return false; } } materials.push_back(material); } return true; } //-------------------------------------------------------------------------------- bool MaterialPipeline::Create(const foundation::String& name, ShaderPipeline& shader_pipeline, TexturePipeline& texture_pipeline, const foundation::AssetName& vertex_shader, const foundation::AssetName& pixel_shader, const foundation::Vector<foundation::UniformBufferData>& uniform_buffer_data, const foundation::Vector<foundation::AssetID>& textures, const foundation::Vector<foundation::SamplerData>& sampler_data, foundation::MaterialAsset& material) { return Create(name, shader_pipeline, texture_pipeline, foundation::GenerateId(vertex_shader), 0, foundation::GenerateId(pixel_shader), uniform_buffer_data, textures, sampler_data, material); } //-------------------------------------------------------------------------------- bool MaterialPipeline::Create(const foundation::String& name, ShaderPipeline& shader_pipeline, TexturePipeline& texture_pipeline, const foundation::AssetName& vertex_shader, const foundation::AssetName& geometry_shader, const foundation::AssetName& pixel_shader, const foundation::Vector<foundation::UniformBufferData>& uniform_buffer_data, const foundation::Vector<foundation::AssetID>& textures, const foundation::Vector<foundation::SamplerData>& sampler_data, foundation::MaterialAsset& material) { return Create(name, shader_pipeline, texture_pipeline, foundation::GenerateId(vertex_shader), foundation::GenerateId(geometry_shader), foundation::GenerateId(pixel_shader), uniform_buffer_data, textures, sampler_data, material); } //-------------------------------------------------------------------------------- bool MaterialPipeline::Create(const foundation::String& name, ShaderPipeline& shader_pipeline, TexturePipeline& texture_pipeline, foundation::AssetID vertex_shader, foundation::AssetID pixel_shader, const foundation::Vector<foundation::UniformBufferData>& uniform_buffer_data, const foundation::Vector<foundation::AssetID>& textures, const foundation::Vector<foundation::SamplerData>& sampler_data, foundation::MaterialAsset& material) { return Create(name, shader_pipeline, texture_pipeline, vertex_shader, 0, pixel_shader, uniform_buffer_data, textures, sampler_data, material); } //-------------------------------------------------------------------------------- bool MaterialPipeline::Create(const foundation::String& name, ShaderPipeline& shader_pipeline, TexturePipeline& texture_pipeline, foundation::AssetID vertex_shader, foundation::AssetID geometry_shader, foundation::AssetID pixel_shader, const foundation::Vector<foundation::UniformBufferData>& uniform_buffer_data, const foundation::Vector<foundation::AssetID>& textures, const foundation::Vector<foundation::SamplerData>& sampler_data, foundation::MaterialAsset& material) { foundation::ShaderData vertex_shader_asset = {}; if(shader_pipeline.LoadAssetFromPackage(vertex_shader, vertex_shader_asset) == false) { PS_LOG_BUILDER(Error, "Vertex shader with id(%llu) couldn't be loaded from package.", vertex_shader); return false; } foundation::ShaderData geometry_shader_asset = {}; if (geometry_shader != 0) { if (shader_pipeline.LoadAssetFromPackage(geometry_shader, geometry_shader_asset) == false) { PS_LOG_BUILDER(Error, "Geometry shader with id(%llu) couldn't be loaded from package.", geometry_shader); return false; } } foundation::ShaderData pixel_shader_asset = {}; if (shader_pipeline.LoadAssetFromPackage(pixel_shader, pixel_shader_asset) == false) { PS_LOG_BUILDER(Error, "Pixel shader with id(%llu) couldn't be loaded from package.", pixel_shader); return false; } foundation::Vector<foundation::TextureData> texture_assets(textures.size()); for(int i = 0; i < textures.size(); ++i) { foundation::AssetID id = textures[i]; if (texture_pipeline.LoadAssetFromPackage(id, texture_assets[i]) == false) { PS_LOG_BUILDER(Error, "Texture with id(%llu) couldn't be loaded from package.", id); return false; } } material.name = name; material.data.vertex_shader_id = vertex_shader; material.data.geometry_shader_id = geometry_shader; material.data.pixel_shader_id = pixel_shader; material.data.uniform_buffers = uniform_buffer_data; material.data.separate_images = textures; material.data.separate_samplers = sampler_data; return true; } //-------------------------------------------------------------------------------- bool MaterialPipeline::CreateTextureCache(const aiScene* scene, const foundation::Path& scene_directory, TexturePipeline& texture_pipeline, foundation::ModelTextureCache& texture_cache) const { const auto create_texture_func = [](const foundation::Path& scene_directory, foundation::ModelTextureCache& texture_cache, TexturePipeline& texture_pipeline, const aiMaterial* ai_mat, aiTextureType texture_type) { if (ai_mat->GetTextureCount(texture_type) > 0) { aiString ai_string = {}; ai_mat->GetTexture(texture_type, 0, &ai_string); const foundation::Path texture_filepath = scene_directory.GetString() + foundation::String(ai_string.C_Str()); if (texture_cache.texture_lookup.find(texture_filepath.GetString()) == texture_cache.texture_lookup.end()) { foundation::TextureAsset texture = {}; if (texture_pipeline.Create(texture_filepath, texture) == true) { texture_cache.textures.push_back(eastl::move(texture)); texture_cache.texture_lookup[texture_filepath] = static_cast<int>(texture_cache.textures.size()) - 1; } } } }; for (unsigned int i = 0u; i < scene->mNumMaterials; ++i) { const aiMaterial* ai_mat = scene->mMaterials[i]; // Get albedo texture create_texture_func(scene_directory, texture_cache, texture_pipeline, ai_mat, aiTextureType_DIFFUSE); // Get normal texture create_texture_func(scene_directory, texture_cache, texture_pipeline, ai_mat, aiTextureType_NORMALS); // Get metallic texture create_texture_func(scene_directory, texture_cache, texture_pipeline, ai_mat, aiTextureType_SPECULAR); // Get roughness texture create_texture_func(scene_directory, texture_cache, texture_pipeline, ai_mat, aiTextureType_SHININESS); } return true; } //-------------------------------------------------------------------------------- bool MaterialPipeline::PackageMaterial(const foundation::Path& asset_origin, foundation::MaterialAsset& material) { if (material.name.get_length() == 0) { PS_LOG_BUILDER(Error, "Material name not initialized. The material will not be packaged."); return false; } foundation::Path output_file = ""; if(RegisterAsset(asset_origin, material.name, output_file, material.id) == false) { PS_LOG_BUILDER(Error, "Failed to register the material. The material will not be packaged."); return false; } foundation::BinaryWriter writer(output_file); writer.Write(material.data); if (writer.Save() == false) { PS_LOG_BUILDER(Error, "Failed to package material."); return false; } return true; } //-------------------------------------------------------------------------------- bool MaterialPipeline::PackageTextureCache(foundation::ModelTextureCache& texture_cache, TexturePipeline& texture_pipeline, foundation::Vector<foundation::MaterialAsset>& materials) const { for(const eastl::pair<foundation::Path, int> it : texture_cache.texture_lookup) { for(foundation::MaterialAsset& material: materials) { for(foundation::AssetID& texture_id : material.data.separate_images) { if(texture_id == it.second) { if(texture_id == 0) { if(texture_pipeline.AssetExists("ps_default_texture") == false) { PS_LOG_BUILDER(Error, "Default material is not in the cache."); return false; } texture_id = foundation::GenerateId("ps_default_texture"); } else { foundation::TextureAsset& texture = texture_cache.textures[it.second]; if (texture.id == 0) { if (texture_pipeline.PackageTexture(it.first, texture) == false) { PS_LOG_BUILDER(Error, "Failed to package texture cache."); return false; } } texture_id = texture.id; } } } } } return true; } //-------------------------------------------------------------------------------- foundation::String MaterialPipeline::GetPackageExtension() const { return "sma"; } //-------------------------------------------------------------------------------- bool MaterialPipeline::PackageDefaultAssets() { if (AssetExists("ps_default_material") == false) { foundation::MaterialAsset asset = {}; asset.name = "ps_default_material"; asset.data.vertex_shader_id = foundation::GenerateId("ps_default_vertex_shader"); asset.data.pixel_shader_id = foundation::GenerateId("ps_default_pixel_shader"); if (PackageMaterial(ASSET_ORIGIN_USER, asset) == false) { PS_LOG_BUILDER(Error, "Failed to package default asset."); return false; } } return true; } //-------------------------------------------------------------------------------- foundation::String MaterialPipeline::GetCacheName() const { return "material_package"; } //-------------------------------------------------------------------------------- bool MaterialPipeline::LoadTexture(const aiMaterial* ai_mat, aiTextureType texture_type, const foundation::Path& scene_directory, foundation::ModelTextureCache& texture_cache, const foundation::Vector<foundation::ShaderResource>& textures, foundation::MaterialData& material) const { if (ai_mat->GetTextureCount(texture_type) > 0) { foundation::String texture_name = ""; switch (texture_type) { case aiTextureType_DIFFUSE: texture_name = "ps_texture_albedo"; break; case aiTextureType_SPECULAR: texture_name = "ps_texture_metallic"; break; case aiTextureType_AMBIENT: texture_name = "ps_texture_occlusion"; break; case aiTextureType_EMISSIVE: texture_name = "ps_texture_emissive"; break; case aiTextureType_SHININESS: texture_name = "ps_texture_roughness"; break; case aiTextureType_NORMALS: texture_name = "ps_texture_normals"; break; default: { PS_LOG_BUILDER(Error, "Trying to load a texture of an unknown type."); return false; } } aiString ai_string = {}; ai_mat->GetTexture(texture_type, 0, &ai_string); const foundation::Path texture_filepath = scene_directory + foundation::Path(ai_string.C_Str()); const eastl::map<foundation::Path, int>::iterator it = texture_cache.texture_lookup.find(texture_filepath); foundation::AssetID texture_id = 0; if(it != texture_cache.texture_lookup.end()) { texture_id = it->second; } FindAndSetTexture(textures, material.separate_images, texture_name, texture_id); } return true; } //-------------------------------------------------------------------------------- bool MaterialPipeline::GetCombinedReflectedShaderData(ShaderPipeline& shader_pipeline, foundation::AssetID& vertex_shader, foundation::AssetID& geometry_shader, foundation::AssetID& pixel_shader, foundation::Vector<foundation::ShaderResource>& uniform_buffers, foundation::Vector<foundation::ShaderResource>& textures, foundation::Vector<foundation::ShaderResource>& samplers) const { // Load the shaders from the package foundation::ShaderData vertex_shader_asset = {}; if (shader_pipeline.LoadAssetFromPackage(vertex_shader, vertex_shader_asset) == false) { PS_LOG_BUILDER(Warning, "Vertex shader with id(%llu) couldn't be loaded from package. Using default shaders instead.", vertex_shader); vertex_shader = foundation::GenerateId("ps_default_vertex_shader"); geometry_shader = 0; pixel_shader = foundation::GenerateId("ps_default_pixel_shader"); vertex_shader_asset = {}; if (shader_pipeline.LoadAssetFromPackage(vertex_shader, vertex_shader_asset) == false) { PS_LOG_BUILDER(Error, "Default vertex shader is not in the cache."); return false; } } foundation::ShaderData geometry_shader_asset = {}; if (geometry_shader != 0) { if (shader_pipeline.LoadAssetFromPackage(geometry_shader, geometry_shader_asset) == false) { PS_LOG_BUILDER(Error, "Geometry shader with id(%llu) couldn't be loaded from package.", geometry_shader); return false; } } foundation::ShaderData pixel_shader_asset = {}; if (shader_pipeline.LoadAssetFromPackage(pixel_shader, pixel_shader_asset) == false) { PS_LOG_BUILDER(Warning, "Pixel shader with id(%llu) couldn't be loaded from package. Using default shaders instead.", pixel_shader); vertex_shader = foundation::GenerateId("ps_default_vertex_shader"); geometry_shader = 0; pixel_shader = foundation::GenerateId("ps_default_pixel_shader"); vertex_shader_asset = {}; if (shader_pipeline.LoadAssetFromPackage(vertex_shader, vertex_shader_asset) == false) { PS_LOG_BUILDER(Error, "Default vertex shader is not in the cache."); return false; } pixel_shader_asset = {}; if(shader_pipeline.LoadAssetFromPackage(pixel_shader, pixel_shader_asset) == false) { PS_LOG_BUILDER(Error, "Default pixel shader is not in the cache."); return false; } } // Check the shader stages if (vertex_shader_asset.stage != foundation::ShaderData::ShaderStage::kVertex) { PS_LOG_BUILDER(Error, "Vertex shader(%lli) is not a vertex shader.", vertex_shader); return false; } if (geometry_shader != 0) { if (geometry_shader_asset.stage != foundation::ShaderData::ShaderStage::kGeometry) { PS_LOG_BUILDER(Error, "Geometry shader(%lli) is not a geometry shader.", geometry_shader); return false; } } if (pixel_shader_asset.stage != foundation::ShaderData::ShaderStage::kPixel) { PS_LOG_BUILDER(Error, "Pixel shader(%lli) is not a pixel shader.", pixel_shader); return false; } // Create list of unique uniform buffers GetShaderResourceCount get_shader_resource_count = [](const foundation::ShaderData& shader) { return shader.uniform_buffers.size(); }; GetShaderResource get_shader_resource = [](const foundation::ShaderData& shader, int i) { return shader.uniform_buffers[i]; }; if(ShaderResourceLoop(vertex_shader_asset, (geometry_shader != 0) ? &geometry_shader_asset : nullptr, pixel_shader_asset, get_shader_resource_count, get_shader_resource, uniform_buffers) == false) { return false; } // Create list of unique texture units get_shader_resource_count = [](const foundation::ShaderData& shader) { return shader.separate_images.size(); }; get_shader_resource = [](const foundation::ShaderData& shader, int i) { return shader.separate_images[i]; }; if(ShaderResourceLoop(vertex_shader_asset, (geometry_shader != 0) ? &geometry_shader_asset : nullptr, pixel_shader_asset, get_shader_resource_count, get_shader_resource, textures) == false) { return false; } // Create list of unique sampler units get_shader_resource_count = [](const foundation::ShaderData& shader) { return shader.separate_samplers.size(); }; get_shader_resource = [](const foundation::ShaderData& shader, int i) { return shader.separate_samplers[i]; }; if(ShaderResourceLoop(vertex_shader_asset, (geometry_shader != 0) ? &geometry_shader_asset : nullptr, pixel_shader_asset, get_shader_resource_count, get_shader_resource, samplers) == false) { return false; } return true; } //-------------------------------------------------------------------------------- bool MaterialPipeline::ShaderResourceLoop(const foundation::ShaderData& vertex_shader_asset, const foundation::ShaderData* geometry_shader_asset, const foundation::ShaderData& pixel_shader_asset, GetShaderResourceCount get_shader_resource_count, GetShaderResource get_shader_resource, foundation::Vector<foundation::ShaderResource>& unique_resource_list) const { size_t vertex_shader_resource_count = get_shader_resource_count(vertex_shader_asset); unique_resource_list.resize(vertex_shader_resource_count); for(int i = 0; i < vertex_shader_resource_count; ++i) { unique_resource_list[i] = get_shader_resource(vertex_shader_asset, i); } if (geometry_shader_asset != nullptr) { for (int i = 0; i < get_shader_resource_count(*geometry_shader_asset); ++i) { const foundation::ShaderResource geom_resource = get_shader_resource(*geometry_shader_asset, i); bool is_unique = true; for (const foundation::ShaderResource& unique_resource : unique_resource_list) { if (geom_resource.LinkerCheck(unique_resource) == false) { PS_LOG_BUILDER(Error, "Geometry shader has resource that is incompatible with the resources defined in the other shaders."); return false; } if (geom_resource.binding == unique_resource.binding && geom_resource.desc_set == unique_resource.desc_set) { is_unique = false; break; } } if (is_unique == true) { unique_resource_list.push_back(geom_resource); } } } for (int i = 0; i < get_shader_resource_count(pixel_shader_asset); ++i) { const foundation::ShaderResource pixel_resource = get_shader_resource(pixel_shader_asset, i); bool is_unique = true; for (const foundation::ShaderResource& unique_resource : unique_resource_list) { if (pixel_resource.LinkerCheck(unique_resource) == false) { PS_LOG_BUILDER(Error, "Pixel shader has resource that is incompatible with the resources defined in the other shaders."); return false; } if (pixel_resource.binding == unique_resource.binding) { is_unique = false; break; } } if (is_unique == true) { unique_resource_list.push_back(pixel_resource); } } return true; } //-------------------------------------------------------------------------------- foundation::Vector<foundation::ShaderResource> MaterialPipeline::FindShaderResources( const foundation::Vector<foundation::ShaderResource>& shader_resources, const foundation::String& name) const { foundation::Vector<foundation::ShaderResource> result = {}; for(const foundation::ShaderResource& resource : shader_resources) { if(resource.name == name) { result.push_back(resource); } } return result; } //-------------------------------------------------------------------------------- void MaterialPipeline::FindAndSetUniform( const foundation::Vector<foundation::ShaderResource>& uniform_buffers, foundation::Vector<foundation::UniformBufferData>& uniform_buffer_data, const foundation::String& uniform_name, float v) const { FindAndSetUniformInternal(uniform_buffers, uniform_buffer_data, uniform_name, v, foundation::ShaderResource::ConcreteType::kFloat, "float"); } //-------------------------------------------------------------------------------- void MaterialPipeline::FindAndSetUniform( const foundation::Vector<foundation::ShaderResource>& uniform_buffers, foundation::Vector<foundation::UniformBufferData>& uniform_buffer_data, const foundation::String& uniform_name, const glm::vec2& v) const { FindAndSetUniformInternal(uniform_buffers, uniform_buffer_data, uniform_name, v, foundation::ShaderResource::ConcreteType::kVec2, "float2"); } //-------------------------------------------------------------------------------- void MaterialPipeline::FindAndSetUniform( const foundation::Vector<foundation::ShaderResource>& uniform_buffers, foundation::Vector<foundation::UniformBufferData>& uniform_buffer_data, const foundation::String& uniform_name, const glm::vec3& v) const { FindAndSetUniformInternal(uniform_buffers, uniform_buffer_data, uniform_name, v, foundation::ShaderResource::ConcreteType::kVec3, "float3"); } //-------------------------------------------------------------------------------- void MaterialPipeline::FindAndSetUniform( const foundation::Vector<foundation::ShaderResource>& uniform_buffers, foundation::Vector<foundation::UniformBufferData>& uniform_buffer_data, const foundation::String& uniform_name, const glm::vec4& v) const { FindAndSetUniformInternal(uniform_buffers, uniform_buffer_data, uniform_name, v, foundation::ShaderResource::ConcreteType::kVec4, "float4"); } //-------------------------------------------------------------------------------- void MaterialPipeline::FindAndSetTexture( const foundation::Vector<foundation::ShaderResource>& textures, foundation::Vector<foundation::AssetID>& texture_data, const foundation::String& texture_name, foundation::AssetID texture_id) const { for(int i = 0; i < textures.size(); ++i) { if(textures[i].name == texture_name && textures[i].image.dimension == foundation::ShaderResource::Image::Dimensions::k2D) { texture_data[i] = texture_id; } } } } }
36.800921
118
0.601157
[ "geometry", "vector", "model" ]
a6e2d7acabb3526d729229da951b266a90f88a30
1,854
cpp
C++
3/g3.cpp
gorbunov-dmitry/rucode-spring-2021-d
6930895b62458f48fda3a9c99f00dd13b1a6b75c
[ "MIT" ]
null
null
null
3/g3.cpp
gorbunov-dmitry/rucode-spring-2021-d
6930895b62458f48fda3a9c99f00dd13b1a6b75c
[ "MIT" ]
null
null
null
3/g3.cpp
gorbunov-dmitry/rucode-spring-2021-d
6930895b62458f48fda3a9c99f00dd13b1a6b75c
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> struct Point { long long x, y; }; struct Angle { long long a, b; }; bool operator < (const Angle& p, const Angle& q) { if (p.b == 0 && q.b == 0) { return p.a < q.a; } return p.a * 1ll * q.b < p.b * 1ll * q.a; } long long sq(Point& a, Point& b, Point& c) { return a.x * 1ll * (b.y - c.y) + b.x * 1ll * (c.y - a.y) + c.x * 1ll * (a.y - b.y); } int main() { size_t n, m, k; std::cin >> n >> m >> k; std::vector<Point> points(n); int zero_id = 0; for (size_t i = 0; i < n; i++) { std::cin >> points[i].x >> points[i].y; if (points[i].x < points[zero_id].x || points[i].x == points[zero_id].x && points[i].y < points[zero_id].y) { zero_id = i; } } Point zero = points[zero_id]; rotate(points.begin(), points.begin() + zero_id, points.end()); points.erase(points.begin()); --n; std::vector<Angle> a(n); for (size_t i = 0; i < n; i++) { a[i].a = points[i].y - zero.y; a[i].b = points[i].x - zero.x; if (a[i].a == 0) { a[i].b = a[i].b < 0 ? -1 : 1; } } size_t in_count = 0; for (size_t i = 0; i < m; i++) { Point q; std::cin >> q.x >> q.y; bool in = false; if (q.x >= zero.x) { if (q.x == zero.x && q.y == zero.y) { in = true; } else { Angle my = { q.y - zero.y, q.x - zero.x }; if (my.a == 0) { my.b = my.b < 0 ? -1 : 1; } auto it = upper_bound(a.begin(), a.end(), my); if (it == a.end() && my.a == a[n - 1].a && my.b == a[n - 1].b) { it = a.end() - 1; } if (it != a.end() && it != a.begin()) { int p1 = int(it - a.begin()); if (sq(points[p1], points[p1 - 1], q) <= 0) { in = true; } } } } if (in) { in_count++; } } if (in_count >= k) { std::cout << "YES" << '\n'; } else { std::cout << "NO" << '\n'; } }
16.854545
109
0.457389
[ "vector" ]
a6e3c710974b24cee97069d468258d4c1b048c00
1,683
cpp
C++
template/conv/fft.cpp
ganmodokix/ysn
74cad18941102539493dda821e17e767bbecde89
[ "MIT" ]
null
null
null
template/conv/fft.cpp
ganmodokix/ysn
74cad18941102539493dda821e17e767bbecde89
[ "MIT" ]
null
null
null
template/conv/fft.cpp
ganmodokix/ysn
74cad18941102539493dda821e17e767bbecde89
[ "MIT" ]
null
null
null
// #REQ: base_template // Cooley-Tukey型 高速フーリエ変換 O(NlogN) template <typename T> void fft_inplace(vector<complex<T>> &a, const bool inv = false) { ll n = 1, h = 0; while (n < a.size()) n <<= 1, h++; a.resize(n, 0); // Cooley-Tukey sort for (size_t i = 0; i < n; i++) { size_t j = 0; for (size_t k = 0; k < h; k++) { j |= (i >> k & 1) << (h-1 - k); } if (i < j) swap(a[i], a[j]); } // butterfly diagram constexpr T dpi = static_cast<T>(acosl(-1) * 2); for (size_t b = 1; b < n; b <<= 1) { for (size_t j = 0; j < b; j++) { auto w = polar<T>(1, -dpi / (b << 1) * j * (inv ? -1 : 1)); for (size_t k = 0; k < n; k += b << 1) { auto s = a[j+k ]; auto t = a[j+k+b] * w; a[j+k ] = s+t; a[j+k+b] = s-t; } } } if (inv) { T inv_n = (T)1 / n; for (ll i = n; i--; ) a[i] *= inv_n; } } template <typename T> inline vector<complex<T>> fft(vector<complex<T>> a, const bool inv = false) { fft_inplace(a, inv); return a; } // long double配列同士の畳み込み O((N+M)log(N+M)) template <typename T> vector<T> convolve(const vector<T> &x, const vector<T> &y) { size_t m = x.size() + y.size() - 1; size_t t = 1; while(t < m) t <<= 1; vector<complex<T>> xc(t, 0), yc(t, 0); REP(i, x.size()) xc[i] = x[i]; REP(i, y.size()) yc[i] = y[i]; fft_inplace(xc, false); fft_inplace(yc, false); REP(i, t) xc[i] *= yc[i]; fft_inplace(xc, true); vector<T> r(m, 0); REP(i, m) r[i] = xc[i].real(); return r; }
33
111
0.438503
[ "vector" ]
a6ec131cb219f4be867441a734e5f9f46a0c60f6
12,884
cpp
C++
src/Config.cpp
connorcl/genetic-simulation
0af17ad6645f16817b2855a20ff81b07750d2377
[ "MIT" ]
null
null
null
src/Config.cpp
connorcl/genetic-simulation
0af17ad6645f16817b2855a20ff81b07750d2377
[ "MIT" ]
null
null
null
src/Config.cpp
connorcl/genetic-simulation
0af17ad6645f16817b2855a20ff81b07750d2377
[ "MIT" ]
null
null
null
#include "Config.h" #include "helper/platform.h" #include <cstdlib> #include <string> #include <limits> #include <iostream> #include <vector> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/ini_parser.hpp> using std::string; using std::numeric_limits; using std::cout; using std::cerr; using std::vector; namespace po = boost::program_options; namespace fs = boost::filesystem; namespace pt = boost::property_tree; // initialize config from command line and config file void GeneticSimulation::Config::init(int argc, char* argv[]) { // set up program options and descriptions po::options_description desc("Recognised options"); set_up_options_description(desc); // parse command line into variables map po::variables_map vm; auto valid_options_given = parse_command_line(argc, argv, desc, vm); // attempt to set config file path from command line or known locations auto config_file_path = get_config_file_location(valid_options_given, vm); // load configuration options from config file (if path is invalid/empty, default values will be used) parse_config_file(config_file_path.string()); // parse rest of command line arguments (and override config file) if (valid_options_given) { parse_command_line_options(vm); } } // set up command line options description void GeneticSimulation::Config::set_up_options_description(po::options_description& desc) { // add descriptions for each option desc.add_options() ("help,h", "Produce help message") ("run_mode,m", po::value<unsigned int>(), "Select which task to run: \n" "0 = run simulation\n" "1 = benchmark simulation\n" "2 = benchmark temperature computation") ("config_file,i", po::value<string>(), "Set path to config file") ("simulation_threads,s", po::value<unsigned int>(), "Set number of simulation threads") #ifdef GPU_SUPPORT ("planet_gpu,g", po::value<bool>(), "Set whether to precompute temperatures using GPU") #endif ("planet_cpu_threads,c", po::value<unsigned int>(), "Set number of threads to use when precomputing temperatures on CPU") ("benchmark_timesteps,t", po::value<unsigned int>(), "Set number of timesteps in simulation benchmark period") ("planet_benchmark_samples,p", po::value<unsigned int>(), "Set number of samples when benchmarking temperature computation"); } // parse program command line and store in variables map bool GeneticSimulation::Config::parse_command_line(int argc, char* argv[], const po::options_description& desc, po::variables_map& vm) { // whether a valid set of options were passed on the command line bool valid_options_given = true; // attempt to parse command line try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (const po::error& e) { // if parsing fails, log error and do not use command line arguments cerr << "Parsing command line options failed: " << e.what() << "\n"; valid_options_given = false; } // if help option given, print usage info and exit if (valid_options_given && vm.count("help")) { cout << desc << "\n"; exit(0); } // return whether parsing was successful return valid_options_given; } // get config file location from command line options or default locations (empty if none found) fs::path GeneticSimulation::Config::get_config_file_location(bool valid_options, const po::variables_map& vm) { // config file path fs::path config_file_path; // check command line options for a specified config file location if (valid_options && vm.count("config_file")) { config_file_path = vm["config_file"].as<string>(); } else { // default locations vector<fs::path> default_config_locations = { "./", "config/", "../config/" }; // path being checked fs::path current_config_path; // check for config file in default locations for (auto& p : default_config_locations) { current_config_path = p / "config.ini"; if (fs::exists(current_config_path)) { config_file_path = current_config_path; break; } } } // output error message if no config file was specified or found if (config_file_path.empty()) { cerr << "No config file was specified or found, falling back to internal default config\n"; } // return path return config_file_path; } // load config from file void GeneticSimulation::Config::parse_config_file(const std::string& config_file) { // property tree of config options pt::ptree config_pt; // check if config file was specified if (!config_file.empty()) { // parse config file try { cout << "Reading config file " << config_file << "\n"; pt::ini_parser::read_ini(config_file, config_pt); } catch (const pt::ini_parser::ini_parser_error& e) { // if reading config file fails, log error cerr << "Reading config file failed: " << e.message() << "\n"; } } // set compute options run_mode = get_option<unsigned int>(config_pt, "Compute.run_mode", 0); performance_framerate = get_numerical_option<unsigned int>(config_pt, "Compute.performance_framerate", 1, 250, 36); standard_framerate = get_numerical_option<unsigned int>(config_pt, "Compute.standard_framerate", 1, 250, 90); simulation_threads = get_numerical_option<unsigned int>(config_pt, "Compute.simulation_threads", 0, 256, 4); #ifdef GPU_SUPPORT precompute_temperatures_gpu = get_option<bool>(config_pt, "Compute.precompute_temperatures_gpu", false); #endif precompute_temperatures_cpu_threads = get_numerical_option<unsigned int>(config_pt, "Compute.precompute_temperatures_cpu_threads", 0, 256, 4); simulation_benchmark_timesteps = get_numerical_option<unsigned int>(config_pt, "Compute.simulation_benchmark_timesteps", 1u, 1e6, 30000); planet_benchmark_samples = get_numerical_option<unsigned int>(config_pt, "Compute.planet_benchmark_samples", 1, 1e3, 50); random_seed_factor = get_numerical_option<int>(config_pt, "Compute.random_seed_factor", -1000000, 1000000, 1); results_path = get_option<std::string>(config_pt, "Compute.results_path", "./"); // set area options area_width = get_numerical_option<unsigned int>(config_pt, "Area.width", 300, 1e4, 1600); area_height = get_numerical_option<unsigned int>(config_pt, "Area.height", 300, 1e4, 1200); latitude_range = get_numerical_option<float>(config_pt, "Area.latitude_range", 1, 90, 90); viewport_width = get_numerical_option<unsigned int>(config_pt, "Area.viewport_width", 300, 1e4, 800); viewport_height = get_numerical_option<unsigned int>(config_pt, "Area.viewport_height", 300, 1e4, 600); title = get_option<string>(config_pt, "Area.title", "Genetic Simulation"); background_color = parse_hex_color(get_option<string>(config_pt, "Area.background_color", "ffffff")); // set planet options orbital_period = get_numerical_option<unsigned int>(config_pt, "Planet.orbital_period", 1e3, 1e6, 36000); orbit_center_offset_x = get_numerical_option<double>(config_pt, "Planet.orbit_center_offset_x", 0, numeric_limits<double>::max(), 0); orbit_center_offset_y = get_numerical_option<double>(config_pt, "Planet.orbit_center_offset_y", 0, numeric_limits<double>::max(), 0); orbit_radius_x = get_numerical_option<double>(config_pt, "Planet.orbit_radius_x", 1e8, numeric_limits<double>::max(), 172e9); orbit_radius_y = get_numerical_option<double>(config_pt, "Planet.orbit_radius_y", 1e8, numeric_limits<double>::max(), 138e9); orbit_rotation = get_numerical_option<double>(config_pt, "Planet.orbit_rotation", numeric_limits<double>::min(), numeric_limits<double>::max(), 0); star_luminosity = get_numerical_option<double>(config_pt, "Planet.star_luminosity", 0, numeric_limits<double>::max(), 3.846e26); albedo = get_numerical_option<double>(config_pt, "Planet.albedo", 0, 1, 0.29); axial_tilt = get_numerical_option<double>(config_pt, "Planet.axial_tilt", 0, 45, 23); radius = get_numerical_option<double>(config_pt, "Planet.radius", 1e3, 1e7, 6371e3); atmosphere_optical_thickness = get_numerical_option<double>(config_pt, "Planet.atmosphere_optical_thickness", 0, 10, 1.3); temperature_moderation_factor = get_numerical_option<double>(config_pt, "Planet.temperature_moderation_factor", 1, 10, 4.0); temperature_moderation_bias = get_numerical_option<double>(config_pt, "Planet.temperature_moderation_bias", 0, 1, 0.8); // set food options food_pool_size = get_numerical_option<unsigned int>(config_pt, "Food.pool_size", 1, 8192, 148); food_max_val = get_numerical_option<unsigned int>(config_pt, "Food.max_val", 10000, 1000000, 250000); food_pool_pos_margin = get_numerical_option<float>(config_pt, "Food.pool_pos_margin", 0, 150, 10); food_pool_init = get_numerical_option<unsigned int>(config_pt, "Food.pool_init", 1, 8192, 148); // set water options water_pool_size = get_numerical_option<unsigned int>(config_pt, "Water.pool_size", 1, 8192, 148); water_max_val = get_numerical_option<unsigned int>(config_pt, "Water.max_val", 10000, 1000000, 250000); water_pool_pos_margin = get_numerical_option<float>(config_pt, "Water.pool_pos_margin", 0, 150, 10); water_pool_init = get_numerical_option<unsigned int>(config_pt, "Water.pool_init", 1, 8192, 148); // set population options population_size = get_numerical_option<unsigned int>(config_pt, "Population.pool_size", 1, 8192, 512); population_pos_margin = get_numerical_option<float>(config_pt, "Population.pool_pos_margin", 0, 150, 20); area_of_influence_mean = get_numerical_option<float>(config_pt, "Population.area_of_influence_mean", 1, 100, 8); area_of_influence_sigma = get_numerical_option<float>(config_pt, "Population.area_of_influence_sigma", 0, area_of_influence_mean / 4, 2); speed_mean = get_numerical_option<float>(config_pt, "Population.speed_mean", 0.1f, 100, 1); speed_sigma = get_numerical_option<float>(config_pt, "Population.speed_sigma", 0, speed_mean / 5, 0.1f); health_rate_mean = get_numerical_option<float>(config_pt, "Population.health_rate_mean", 1, 1e6f, 220); health_rate_sigma = get_numerical_option<float>(config_pt, "Population.health_rate_sigma", 0, health_rate_mean / 5, 30); ideal_temp_mean = get_numerical_option<float>(config_pt, "Population.ideal_temp_mean", 0, 1e3, 260); ideal_temp_sigma = get_numerical_option<float>(config_pt, "Population.ideal_temp_sigma", 0, ideal_temp_mean / 5, 30); temp_range_mean = get_numerical_option<float>(config_pt, "Population.temp_range_mean", 0, 100, 10); temp_range_sigma = get_numerical_option<float>(config_pt, "Population.temp_range_sigma", 0, temp_range_mean / 5, 2); behaviour_net_weight_range = get_numerical_option<float>(config_pt, "Population.behaviour_net_weight_range", 1e-4f, 10, 2); behaviour_net_weight_range_bias = get_numerical_option<float>(config_pt, "Population.behaviour_net_weight_range_bias", 1, 10, 1); behaviour_net_layer_1_units = get_numerical_option<unsigned int>(config_pt, "Population.behaviour_net_layer_1_units", 1, 128, 16); behaviour_net_layer_2_units = get_numerical_option<unsigned int>(config_pt, "Population.behaviour_net_layer_2_units", 1, 128, 8); population_init = get_numerical_option<unsigned int>(config_pt, "Population.pool_init", 1, 8192, 512); replication_rate = get_numerical_option<float>(config_pt, "Population.replication_rate", 0, 1, 0.0001f); behaviour_net_mutation_prob = get_numerical_option<float>(config_pt, "Population.behaviour_net_mutation_prob", 0, 1, 0.1f); behaviour_net_mutation_sigma = get_numerical_option<float>(config_pt, "Population.behaviour_net_mutation_sigma", 0, 10, 0.2f); trait_genes_mutation_prob = get_numerical_option<float>(config_pt, "Population.trait_genes_mutation_prob", 0, 1, 0.1f); trait_genes_mutation_sigma = get_numerical_option<float>(config_pt, "Population.trait_genes_mutation_sigma", 0, 2, 0.01f); } // parse command line options excluding config file void GeneticSimulation::Config::parse_command_line_options(const po::variables_map& vm) { if (vm.count("run_mode")) { run_mode = vm["run_mode"].as<unsigned int>(); } if (vm.count("simulation_threads")) { simulation_threads = vm["simulation_threads"].as<unsigned int>(); } #ifdef GPU_SUPPORT if (vm.count("planet_gpu")) { precompute_temperatures_gpu = vm["planet_gpu"].as<bool>(); } #endif if (vm.count("planet_cpu_threads")) { precompute_temperatures_cpu_threads = vm["planet_cpu_threads"].as<unsigned int>(); } if (vm.count("benchmark_timesteps")) { simulation_benchmark_timesteps = vm["benchmark_timesteps"].as<unsigned int>(); } if (vm.count("planet_benchmark_samples")) { planet_benchmark_samples = vm["planet_benchmark_samples"].as<unsigned int>(); } } // convert a 3-byte hex string into a 32-bit color value uint32_t GeneticSimulation::Config::parse_hex_color(const string& color_string) { uint32_t color_value = 255; for (int i = 0; i < 3; i++) { color_value |= (stoi(color_string.substr(i * 2, 2), nullptr, 16) << ((3 - i) * 8)); } return color_value; }
48.43609
138
0.760866
[ "vector" ]
a6ef2d6af808dc1779c8dae95e05629ccd7e90c8
2,002
cpp
C++
binary-tree/rotting-oranges.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
binary-tree/rotting-oranges.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
binary-tree/rotting-oranges.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int orangesRotting(vector<vector<int>> &grid) { //number of valid cells (cells with some orange) int ct = 0; //result int res = -1; //actually queue of pairs of coord i and j queue<vector<int>> q; //ways to move vector<vector<int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; //create staring nodes to queue to do bfs for (int i = 0; i < grid.size(); i++) { for (int j = 0; j < grid[0].size(); j++) { //increasing number of valid cells if (grid[i][j] > 0) ct++; //only rotten oranges must be on initial step of queue if (grid[i][j] == 2) q.push({i, j}); } } //bfs while (!q.empty()) { //we do one step from rotten res++; //see next comment int size = q.size(); //need to start from all rotten nodes at one moment for (int k = 0; k < size; k++) { //take node from head vector<int> cur = q.front(); q.pop(); //number of valid decreasing ct--; //need to look through all four directions for (int i = 0; i < 4; i++) { //taking coords int x = cur[0] + dir[i][0]; int y = cur[1] + dir[i][1]; //if we go out of border or find non-fresh orange, we skip this iteration if (x >= grid.size() || x < 0 || y >= grid[0].size() || y < 0 || grid[x][y] != 1) continue; //orange becomes rotten grid[x][y] = 2; //this orange will make neighbor orange rotten q.push({x, y}); } } } //if we looked through all oranges, return result, else -1 return (ct == 0) ? max(0, res) : -1; }
27.054054
98
0.433067
[ "vector" ]
a6f36b64560398c915470c33f4a3786cf1fdffd3
24,579
cpp
C++
applications/MultiScaleApplication/custom_python/add_utilities_to_python.cpp
lcirrott/Kratos
8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea
[ "BSD-4-Clause" ]
2
2020-04-30T19:13:08.000Z
2021-04-14T19:40:47.000Z
applications/MultiScaleApplication/custom_python/add_utilities_to_python.cpp
lcirrott/Kratos
8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea
[ "BSD-4-Clause" ]
1
2020-04-30T19:19:09.000Z
2020-05-02T14:22:36.000Z
applications/MultiScaleApplication/custom_python/add_utilities_to_python.cpp
lcirrott/Kratos
8406e73e0ad214c4f89df4e75e9b29d0eb4a47ea
[ "BSD-4-Clause" ]
1
2020-06-12T08:51:24.000Z
2020-06-12T08:51:24.000Z
/* ============================================================================== KratosMultiScaleApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel pooyan@cimne.upc.edu rrossi@cimne.upc.edu janosch.stascheit@rub.de nagel@sd.rub.de - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain - Ruhr-University Bochum, Institute for Structural Mechanics, Germany Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================================================================== */ // // Project Name: Kratos // Last Modified by: $Author: Massimo Petracca $ // Date: $Date: 2013-10-03 19:37:00 $ // Revision: $Revision: 1.00 $ // // // System includes #include <iostream> // External includes #include <boost/python.hpp> #include "includes/constitutive_law.h" #include "includes/properties.h" #include "includes/model_part.h" #include "spaces/ublas_space.h" #include "linear_solvers/linear_solver.h" // Project includes #include "add_utilities_to_python.h" #include "custom_utilities/load_function.h" #include "custom_utilities/rve_utilities_model_part.h" #include "custom_utilities/rve_utilities_element_info.h" #include "custom_utilities/rve_adapter_v2.h" #include "constitutive_laws/rve_constitutive_law.h" #include "custom_utilities/rve_macroscale_data.h" #include "custom_utilities/rve_geometry_descriptor.h" #include "custom_utilities/rve_linear_system_of_equations.h" #include "custom_utilities/rve_constraint_handler.h" #include "custom_utilities/rve_constraint_handler_zbf_sd.h" #include "custom_utilities/rve_constraint_handler_pbf_sd.h" #include "custom_utilities/rve_constraint_handler_wpbf_sd.h" #include "custom_utilities/rve_constraint_handler_zbf_sd_thick_shell.h" #include "custom_utilities/rve_constraint_handler_pbf_sd_thick_shell.h" #include "custom_utilities/rve_constraint_handler_pbfzu_sd_thick_shell.h" #include "custom_utilities/rve_constraint_handler_pbfzr_sd_thick_shell.h" #include "custom_utilities/rve_constraint_handler_pbfwts_sd_thick_shell.h" #include "custom_utilities/rve_constraint_handler_zbf_sd_thermal.h" #include "custom_utilities/rve_constraint_handler_pbf_sd_thermal.h" #include "custom_utilities/rve_constraint_handler_wpbf_sd_thermal.h" #include "custom_utilities/rve_homogenizer.h" #include "custom_utilities/rve_homogenizer_thermal.h" #include "custom_utilities/rve_homogenizer_thick_shell.h" #include "custom_utilities/rve_predictor_calculator.h" #include "custom_conditions/periodic_condition_lm_2D2N.h" #include "geometries/line_2d_2.h" #include "custom_utilities/rve_material_database.h" #include "custom_utilities/rve_material_database_3D.h" #ifdef _OPENMP #include <omp.h> #endif #include "includes/table.h" namespace Kratos { namespace Python { using namespace boost::python; void TestOpenMP(int omp_max_num_threads, int nested) { #ifdef _OPENMP std::stringstream ss; ss << "SETTING OPENMP PARAMS\n"; ss << "before:\n"; ss << " - num: " << omp_get_num_threads() << std::endl; ss << " - nested: " << omp_get_nested() << std::endl; ss << "SETTING: " << omp_max_num_threads << ", " << nested << std::endl; omp_set_num_threads(omp_max_num_threads); omp_set_nested(nested); ss << " - num: " << omp_get_num_threads() << std::endl; ss << " - nested: " << omp_get_nested() << std::endl; std::cout << ss.str(); #endif } template<class Tobj, class T> T ConstitutiveLawGetValue(Tobj& obj, const Variable<T>& a, T& b) { return obj.GetValue(a, b); } void RveGeometryDescriptor_SetUserCornerNodes_Helper(RveGeometryDescriptor& self, const boost::python::list & values) { size_t n = len(values); RveGeometryDescriptor::IndexContainerType ids(n); for(size_t i = 0; i < n; i++) ids[i] = boost::python::extract<double>(values[i]); self.SetUserCornerNodes(ids); } void Table_example_cpp_01() { // define a table of double(key) and double(values) // here we use DISTANCE and PRESSURE as an example typedef Table<double,double> TableType; TableType aTable; // let's fill the table. // we will create a gaussian function, centered at DISTANCE=0.0, // with a half-width=20.0, and a peak-value=50.0 // since the table is not a real function, we need to discretize the function. double a = 50.0; // height of the bell (peak-value) double b = 0.0; // abscissa of the peak-value double c = 20.0; // half width of the bell unsigned int num_samples = 10; double distance_increment = c / double(num_samples); double current_distance = 0.0; // add the first point aTable.PushBack(current_distance, a); // add the other points until we reach the half-distance of 20.0 units for(unsigned int i = 0; i < num_samples; i++) { current_distance += distance_increment; double val = a*std::exp(-std::pow(current_distance-b, 2)/(2.0*c)); aTable.PushBack(current_distance, val); } // this function doesn't acutally reach the Zero-value. And since the table // will interpolate the results if we are at an Abscissa greater than the last one, // we will obtain (very small) negative values. // to avoid this let's add two extra points with a Zero-value. current_distance += distance_increment; aTable.PushBack(current_distance, 0.0); current_distance += distance_increment; aTable.PushBack(current_distance, 0.0); // one the table has been created, we can access it as follows: // note: we want to use a linear interpolation in this example, so we use the function GetValue(X). // If one doesn't want to interpolate the results, the function GetNearestValue(X) can be used. unsigned int num_samples_for_output = 20; distance_increment = c / double(num_samples_for_output); current_distance = 0.0; std::stringstream outbuffer; // get the first value outbuffer << "DISTANCE\tPRESSURE\n"; outbuffer << current_distance << "\t" << aTable.GetValue(current_distance) << std::endl; // get the other points until we reach the half-distance of 20.0 units for(unsigned int i = 0; i < num_samples_for_output; i++) { current_distance += distance_increment; outbuffer << current_distance << "\t" << aTable.GetValue(current_distance) << std::endl; } // get some more points just to make sure the interpolation after we reach the bell with gives always Zero current_distance += distance_increment; outbuffer << current_distance << "\t" << aTable.GetValue(current_distance) << std::endl; current_distance += distance_increment; outbuffer << current_distance << "\t" << aTable.GetValue(current_distance) << std::endl; // print std::cout << outbuffer.str(); } void AddPeriodicCondition(ModelPart& mp, int slave_node, int master_node) { unsigned int max_cond_id = 0; for(ModelPart::ConditionIterator it = mp.ConditionsBegin(); it != mp.ConditionsEnd(); ++it) if(max_cond_id < it->GetId()) max_cond_id = it->GetId(); max_cond_id++; ModelPart::NodeType::Pointer n1 = mp.pGetNode(slave_node); ModelPart::NodeType::Pointer n2 = mp.pGetNode(master_node); Condition::GeometryType::PointsArrayType points; points.push_back(n1); points.push_back(n2); Condition::GeometryType::Pointer new_geom( new Line2D2<Condition::GeometryType::PointType>( points ) ); PeriodicConditionLM2D2N::Pointer new_cond( new PeriodicConditionLM2D2N(max_cond_id, new_geom) ); mp.AddCondition( new_cond ); } void AddUtilitiesToPython() { def("Table_example_cpp_01", &Table_example_cpp_01); def("AddPeriodicCondition", &AddPeriodicCondition); def("RveCloneModelPart", &RveUtilities::CloneModelPart); //def("RveCloneModelPart2Physics", &RveUtilities::CloneModelPart2Physics); def("ReorientNarrowQuads", &RveUtilities::ReorientNarrowQuads); def("ReorientNarrowQuadsReplaceWithInterface", &RveUtilities::ReorientNarrowQuadsReplaceWithInterface); def("ReorientQuadsX", &RveUtilities::ReorientQuadsX); def("ReorientQuadsY", &RveUtilities::ReorientQuadsY); def("ReorientQuadsCCWBL", &RveUtilities::ReorientQuadsCCWBL); def("TestOpenMP", &TestOpenMP); typedef RveUtilities::SolidElementInfo SolidElementInfoType; typedef SolidElementInfoType::IndexType ElementInfoIndexType; typedef RveUtilities::ShellElementInfo ShellElementInfoType; class_<SolidElementInfoType, boost::noncopyable>( "SolidElementInfo", init<>()) .def(init<ElementInfoIndexType, ElementInfoIndexType>()) .def("GetStringExtension", &SolidElementInfoType::GetStringExtension) .def(self_ns::str(self)) .add_property("ElementID", &SolidElementInfoType::GetElementID, &SolidElementInfoType::SetElementID) .add_property("GaussPointID", &SolidElementInfoType::GetGaussPointID, &SolidElementInfoType::SetGaussPointID) ; class_<ShellElementInfoType, bases<SolidElementInfoType>, boost::noncopyable>( "ShellElementInfo", init<>()) .def(init<ElementInfoIndexType, ElementInfoIndexType>()) .def(init<ElementInfoIndexType, ElementInfoIndexType, ElementInfoIndexType, ElementInfoIndexType>()) .add_property("PlyID", &ShellElementInfoType::GetPlyID, &ShellElementInfoType::SetPlyID) .add_property("PlyIntegrationPointID", &ShellElementInfoType::GetPlyIntegrationPointID, &ShellElementInfoType::SetPlyIntegrationPointID) ; // =============================================================================== // // load functions // // =============================================================================== typedef LoadFunction<double> LoadFunctionbaseType; enum_<LoadFunctionbaseType::ProlongationType>("ProlongationType") .value("Zero", LoadFunctionbaseType::Zero) .value("Constant", LoadFunctionbaseType::Constant) .value("Linear", LoadFunctionbaseType::Linear) ; class_<LoadFunctionbaseType, LoadFunctionbaseType::Pointer, boost::noncopyable >( "LoadFunction", init<>()) ; typedef PieceWiseLoadFunction<double> PieceWiseLoadFunctionType; class_<PieceWiseLoadFunctionType, PieceWiseLoadFunctionType::Pointer, bases< LoadFunctionbaseType >, boost::noncopyable >( "PieceWiseLoadFunction", init<const boost::python::list &>()) .def(init<const boost::python::list &, LoadFunctionbaseType::ProlongationType>()) .def(init<const boost::python::list &, const boost::python::list &, LoadFunctionbaseType::ProlongationType>()) ; // =============================================================================== // // RVE - These should be moved to .. AddRveToPython // // =============================================================================== typedef UblasSpace<double, CompressedMatrix, Vector> SparseSpaceType; typedef UblasSpace<double, Matrix, Vector> LocalSpaceType; typedef LinearSolver<SparseSpaceType, LocalSpaceType> LinearSolverBaseType; class_<RveMaterialDatabase, RveMaterialDatabase::Pointer, boost::noncopyable>( "RveMaterialDatabase", init<std::string, std::string, std::string>()) .def(self_ns::str(self)) ; class_<RveMacroscaleData, RveMacroscaleData::Pointer, boost::noncopyable>( "RveMacroscaleData", init<>()) .def(self_ns::str(self)) ; class_<RveGeometryDescriptor, RveGeometryDescriptor::Pointer, boost::noncopyable>( "RveGeometryDescriptor", init<>()) .def("Build", &RveGeometryDescriptor::Build) .def("SetUserCornerNodes", &RveGeometryDescriptor_SetUserCornerNodes_Helper) .def(self_ns::str(self)) ; class_<RvePredictorCalculator, RvePredictorCalculator::Pointer, boost::noncopyable>( "RvePredictorCalculator", init<std::string, std::string, std::string>()) ; typedef RveConstraintHandler<SparseSpaceType, LocalSpaceType> RveConstraintHandlerBaseType; class_<RveConstraintHandlerBaseType, RveConstraintHandlerBaseType::Pointer, boost::noncopyable>( "RveConstraintHandler", init<>()) ; typedef RveConstraintHandler_ZBF_SD<SparseSpaceType, LocalSpaceType> RveConstraintHandler_ZBF_SD_Type; class_<RveConstraintHandler_ZBF_SD_Type, RveConstraintHandler_ZBF_SD_Type::Pointer, bases<RveConstraintHandlerBaseType>, boost::noncopyable>( "RveConstraintHandler_ZBF_SD", init<>()) ; typedef RveConstraintHandler_PBF_SD<SparseSpaceType, LocalSpaceType> RveConstraintHandler_PBF_SD_Type; class_<RveConstraintHandler_PBF_SD_Type, RveConstraintHandler_PBF_SD_Type::Pointer, bases<RveConstraintHandlerBaseType>, boost::noncopyable>( "RveConstraintHandler_PBF_SD", init<>()) ; typedef RveConstraintHandler_WPBF_SD<SparseSpaceType, LocalSpaceType> RveConstraintHandler_WPBF_SD_Type; class_<RveConstraintHandler_WPBF_SD_Type, RveConstraintHandler_WPBF_SD_Type::Pointer, bases<RveConstraintHandlerBaseType>, boost::noncopyable>( "RveConstraintHandler_WPBF_SD", init<>()) ; typedef RveConstraintHandler_ZBF_SD_ThickShell<SparseSpaceType, LocalSpaceType> RveConstraintHandler_ZBF_SD_ThicShell_Type; class_<RveConstraintHandler_ZBF_SD_ThicShell_Type, RveConstraintHandler_ZBF_SD_ThicShell_Type::Pointer, bases<RveConstraintHandlerBaseType>, boost::noncopyable>( "RveConstraintHandler_ZBF_SD_ThickShell", init<>()) ; typedef RveConstraintHandler_PBF_SD_ThickShell<SparseSpaceType, LocalSpaceType> RveConstraintHandler_PBF_SD_ThicShell_Type; class_<RveConstraintHandler_PBF_SD_ThicShell_Type, RveConstraintHandler_PBF_SD_ThicShell_Type::Pointer, bases<RveConstraintHandlerBaseType>, boost::noncopyable>( "RveConstraintHandler_PBF_SD_ThickShell", init<>()) ; typedef RveConstraintHandler_PBFZU_SD_ThickShell<SparseSpaceType, LocalSpaceType> RveConstraintHandler_PBFZU_SD_ThicShell_Type; class_<RveConstraintHandler_PBFZU_SD_ThicShell_Type, RveConstraintHandler_PBFZU_SD_ThicShell_Type::Pointer, bases<RveConstraintHandlerBaseType>, boost::noncopyable>( "RveConstraintHandler_PBFZU_SD_ThickShell", init<>()) ; typedef RveConstraintHandler_PBFZR_SD_ThickShell<SparseSpaceType, LocalSpaceType> RveConstraintHandler_PBFZR_SD_ThicShell_Type; class_<RveConstraintHandler_PBFZR_SD_ThicShell_Type, RveConstraintHandler_PBFZR_SD_ThicShell_Type::Pointer, bases<RveConstraintHandlerBaseType>, boost::noncopyable>( "RveConstraintHandler_PBFZR_SD_ThickShell", init<>()) ; typedef RveConstraintHandler_PBFWTS_SD_ThickShell<SparseSpaceType, LocalSpaceType> RveConstraintHandler_PBFWTS_SD_ThicShell_Type; class_<RveConstraintHandler_PBFWTS_SD_ThicShell_Type, RveConstraintHandler_PBFWTS_SD_ThicShell_Type::Pointer, bases<RveConstraintHandlerBaseType>, boost::noncopyable>( "RveConstraintHandler_PBFWTS_SD_ThickShell", init<>()) ; typedef RveLinearSystemOfEquations<SparseSpaceType, LocalSpaceType> RveLinearSystemOfEquationsType; class_<RveLinearSystemOfEquationsType, RveLinearSystemOfEquationsType::Pointer, boost::noncopyable>( "RveLinearSystemOfEquations", init<LinearSolverBaseType::Pointer>()) ; typedef RveHomogenizer<SparseSpaceType, LocalSpaceType> RveHomogenizerType; class_<RveHomogenizerType, RveHomogenizerType::Pointer, boost::noncopyable>( "RveHomogenizer", init<>()) ; typedef RveHomogenizerThickShell<SparseSpaceType, LocalSpaceType> RveHomogenizerThickShellType; class_<RveHomogenizerThickShellType, RveHomogenizerThickShellType::Pointer, bases<RveHomogenizerType>, boost::noncopyable>( "RveHomogenizerThickShell", init<>()) ; // PLANE STRESS typedef RveAdapterV2<SparseSpaceType, LocalSpaceType, RveAdapterSettings_PlaneStress> RvePlaneStressAdapterV2Type; class_<RvePlaneStressAdapterV2Type, RvePlaneStressAdapterV2Type::Pointer, boost::noncopyable>( "RvePlaneStressAdapterV2", init<>()) .def("SetPredictorData", &RvePlaneStressAdapterV2Type::SetPredictorData) .def("SetRveDataAfterPredictor", &RvePlaneStressAdapterV2Type::SetRveDataAfterPredictor) .def("SetRveData", &RvePlaneStressAdapterV2Type::SetRveData) .def("RveGenerated", &RvePlaneStressAdapterV2Type::RveGenerated) .def("RveGenerationRequested", &RvePlaneStressAdapterV2Type::RveGenerationRequested) .def("WorkingSpaceDimension", &RvePlaneStressAdapterV2Type::WorkingSpaceDimension) .def("GetStrainSize", &RvePlaneStressAdapterV2Type::GetStrainSize) .def(self_ns::str(self)) ; typedef ConstitutiveLawAdapter<RvePlaneStressAdapterV2Type> RveConstitutiveLawV2PlaneStressBaseType; class_<RveConstitutiveLawV2PlaneStressBaseType, RveConstitutiveLawV2PlaneStressBaseType::Pointer, bases<ConstitutiveLaw>, boost::noncopyable>( "RveConstitutiveLawV2PlaneStressBase", no_init) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2PlaneStressBaseType, double>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2PlaneStressBaseType, Vector>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2PlaneStressBaseType, Matrix>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2PlaneStressBaseType, array_1d<double,3> >) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2PlaneStressBaseType, array_1d<double,6> >) ; typedef RveConstitutiveLaw<RvePlaneStressAdapterV2Type> RveConstitutiveLawV2PlaneStressType; class_<RveConstitutiveLawV2PlaneStressType, RveConstitutiveLawV2PlaneStressType::Pointer, bases<RveConstitutiveLawV2PlaneStressBaseType>, boost::noncopyable>( "RveConstitutiveLawV2PlaneStress", init<const RvePlaneStressAdapterV2Type::Pointer&>()) .def("GetModelPart", &RveConstitutiveLawV2PlaneStressType::GetModelPart) ; // 3D typedef RveAdapterV2<SparseSpaceType, LocalSpaceType, RveAdapterSettings_3D> Rve3DAdapterV2Type; class_<Rve3DAdapterV2Type, Rve3DAdapterV2Type::Pointer, boost::noncopyable>( "Rve3DAdapterV2", init<>()) .def("SetPredictorData", &Rve3DAdapterV2Type::SetPredictorData) .def("SetRveDataAfterPredictor", &Rve3DAdapterV2Type::SetRveDataAfterPredictor) .def("SetRveData", &Rve3DAdapterV2Type::SetRveData) .def("RveGenerated", &Rve3DAdapterV2Type::RveGenerated) .def("RveGenerationRequested", &Rve3DAdapterV2Type::RveGenerationRequested) .def("WorkingSpaceDimension", &Rve3DAdapterV2Type::WorkingSpaceDimension) .def("GetStrainSize", &Rve3DAdapterV2Type::GetStrainSize) .def(self_ns::str(self)) ; typedef ConstitutiveLawAdapter<Rve3DAdapterV2Type> RveConstitutiveLawV23DBaseType; class_<RveConstitutiveLawV23DBaseType, RveConstitutiveLawV23DBaseType::Pointer, bases<ConstitutiveLaw>, boost::noncopyable>( "RveConstitutiveLawV23DBase", no_init) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV23DBaseType, double>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV23DBaseType, Vector>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV23DBaseType, Matrix>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV23DBaseType, array_1d<double,3> >) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV23DBaseType, array_1d<double,6> >) ; typedef RveConstitutiveLaw<Rve3DAdapterV2Type> RveConstitutiveLawV23DType; class_<RveConstitutiveLawV23DType, RveConstitutiveLawV23DType::Pointer, bases<RveConstitutiveLawV23DBaseType>, boost::noncopyable>( "RveConstitutiveLawV23D", init<const Rve3DAdapterV2Type::Pointer&>()) .def("GetModelPart", &RveConstitutiveLawV23DType::GetModelPart) ; // ThickShell typedef RveAdapterV2<SparseSpaceType, LocalSpaceType, RveAdapterSettings_ThickShell> RveThickShellAdapterV2Type; class_<RveThickShellAdapterV2Type, RveThickShellAdapterV2Type::Pointer, boost::noncopyable>( "RveThickShellAdapterV2", init<>()) .def("SetRveData", &RveThickShellAdapterV2Type::SetRveData) .def("RveGenerated", &RveThickShellAdapterV2Type::RveGenerated) .def("RveGenerationRequested", &RveThickShellAdapterV2Type::RveGenerationRequested) .def("WorkingSpaceDimension", &RveThickShellAdapterV2Type::WorkingSpaceDimension) .def("GetStrainSize", &RveThickShellAdapterV2Type::GetStrainSize) .def(self_ns::str(self)) ; typedef ConstitutiveLawAdapter<RveThickShellAdapterV2Type> RveConstitutiveLawV2ThickShellBaseType; class_<RveConstitutiveLawV2ThickShellBaseType, RveConstitutiveLawV2ThickShellBaseType::Pointer, bases<ConstitutiveLaw>, boost::noncopyable>( "RveConstitutiveLawV2ThickShellBase", no_init) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThickShellBaseType, double>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThickShellBaseType, Vector>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThickShellBaseType, Matrix>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThickShellBaseType, array_1d<double,3> >) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThickShellBaseType, array_1d<double,6> >) ; typedef RveConstitutiveLaw<RveThickShellAdapterV2Type> RveConstitutiveLawV2ThickShellType; class_<RveConstitutiveLawV2ThickShellType, RveConstitutiveLawV2ThickShellType::Pointer, bases<RveConstitutiveLawV2ThickShellBaseType>, boost::noncopyable>( "RveConstitutiveLawV2ThickShell", init<const RveThickShellAdapterV2Type::Pointer&>()) .def("GetModelPart", &RveConstitutiveLawV2ThickShellType::GetModelPart) ; // ThinShell typedef RveAdapterV2<SparseSpaceType, LocalSpaceType, RveAdapterSettings_ThinShell> RveThinShellAdapterV2Type; class_<RveThinShellAdapterV2Type, RveThinShellAdapterV2Type::Pointer, boost::noncopyable>( "RveThinShellAdapterV2", init<>()) .def("SetRveData", &RveThinShellAdapterV2Type::SetRveData) .def("RveGenerated", &RveThinShellAdapterV2Type::RveGenerated) .def("RveGenerationRequested", &RveThinShellAdapterV2Type::RveGenerationRequested) .def("WorkingSpaceDimension", &RveThinShellAdapterV2Type::WorkingSpaceDimension) .def("GetStrainSize", &RveThinShellAdapterV2Type::GetStrainSize) .def(self_ns::str(self)) ; typedef ConstitutiveLawAdapter<RveThinShellAdapterV2Type> RveConstitutiveLawV2ThinShellBaseType; class_<RveConstitutiveLawV2ThinShellBaseType, RveConstitutiveLawV2ThinShellBaseType::Pointer, bases<ConstitutiveLaw>, boost::noncopyable>( "RveConstitutiveLawV2ThinShellBase", no_init) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThinShellBaseType, double>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThinShellBaseType, Vector>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThinShellBaseType, Matrix>) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThinShellBaseType, array_1d<double,3> >) .def("GetValue", ConstitutiveLawGetValue<RveConstitutiveLawV2ThinShellBaseType, array_1d<double,6> >) ; typedef RveConstitutiveLaw<RveThinShellAdapterV2Type> RveConstitutiveLawV2ThinShellType; class_<RveConstitutiveLawV2ThinShellType, RveConstitutiveLawV2ThinShellType::Pointer, bases<RveConstitutiveLawV2ThinShellBaseType>, boost::noncopyable>( "RveConstitutiveLawV2ThinShell", init<const RveThinShellAdapterV2Type::Pointer&>()) .def("GetModelPart", &RveConstitutiveLawV2ThinShellType::GetModelPart) ; } } }
43.734875
144
0.763782
[ "vector", "3d" ]
a6f3eab56e50ef35000dd62b46a5427322b2d962
3,584
cpp
C++
bingo.cpp
codesAliecc/hacktoberfest2021
2f3e5e318ab5834131c6aab75185a1b67e748b79
[ "Unlicense" ]
null
null
null
bingo.cpp
codesAliecc/hacktoberfest2021
2f3e5e318ab5834131c6aab75185a1b67e748b79
[ "Unlicense" ]
null
null
null
bingo.cpp
codesAliecc/hacktoberfest2021
2f3e5e318ab5834131c6aab75185a1b67e748b79
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; template <typename T> T power(T a, long long b) { T r = 1; while (b) { if (b & 1) { r *= a; } a *= a; b >>= 1; } return r; } template <typename T> T inverse(T a, T m) { a %= m; if (a < 0) { a += m; } T b = m, u = 0, v = 1; while (a) { T t = b / a; b -= a * t; swap(a, b); u -= v * t; swap(u, v); } if (u < 0) { u += m; } return u; } template <int _P> struct modnum { static constexpr int P = _P; private: int v; public: modnum() : v(0) { } modnum(long long _v) { v = _v % P; if (v < 0) { v += P; } } explicit operator int() const { return v; } bool operator==(const modnum& o) const { return v == o.v; } bool operator!=(const modnum& o) const { return v != o.v; } modnum inverse() const { return modnum(::inverse(v, P)); } modnum operator-() const { return modnum(v ? P - v : 0); } modnum operator+() const { return *this; } modnum& operator++() { v++; if (v == P) { v = 0; } return *this; } modnum& operator--() { if (v == 0) { v = P; } v--; return *this; } modnum operator++(int) { modnum r = *this; ++*this; return r; } modnum operator--(int) { modnum r = *this; --*this; return r; } modnum& operator+=(const modnum& o) { v += o.v; if (v >= P) { v -= P; } return *this; } modnum operator+(const modnum& o) const { return modnum(*this) += o; } modnum& operator-=(const modnum& o) { v -= o.v; if (v < 0) { v += P; } return *this; } modnum operator-(const modnum& o) const { return modnum(*this) -= o; } modnum& operator*=(const modnum& o) { v = (int) ((long long) v * o.v % P); return *this; } modnum operator*(const modnum& o) const { return modnum(*this) *= o; } modnum& operator/=(const modnum& o) { return *this *= o.inverse(); } modnum operator/(const modnum& o) const { return modnum(*this) /= o; } }; template <int _P> ostream& operator<<(ostream& out, const modnum<_P>& n) { return out << int(n); } template <int _P> istream& operator>>(istream& in, modnum<_P>& n) { long long _v; in >> _v; n = modnum<_P>(_v); return in; } using num = modnum<31607>; int main() { #ifdef LOCAL freopen("input.txt", "r", stdin); #endif ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; vector<vector<num>> a(n, vector<num>(n)); vector<vector<num>> b(n, vector<num>(n)); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cin >> a[i][j]; a[i][j] /= 10000; b[i][j] = num(1) / a[i][j]; } } vector<num> f(1 << (n + 2), 1); vector<num> g(1 << (n + 2)); for (int i = 0; i < n; ++i) { num base = 1; for (int j = 0; j < n; ++j) { base *= a[i][j]; } for (int j = 0; j < 1 << (n + 2); ++j) { int k = __builtin_ctz(j); if (k >= n) { g[j] = base; } else if (!(i == k && !(j >> n & 1)) && !(i + k == n - 1 && !(j >> (n + 1) & 1))) { g[j] = g[j ^ (1 << k)] * b[i][k]; } else { g[j] = g[j ^ (1 << k)]; } } for (int j = 0; j < 1 << (n + 2); ++j) { g[j] -= base; f[j] *= g[j]; } } num ans = 1; for (int i = 0; i < 1 << (n + 2); ++i) { if ((__builtin_popcount(i) ^ n) & 1) { ans += f[i]; } else { ans -= f[i]; } } cout << ans << "\n"; return 0; }
16.747664
90
0.442243
[ "vector" ]
a6f5df324d1b944dfcff0a463690cf0436f43bfa
9,155
cpp
C++
Tree/Tree.cpp
pingpingbangbang/owchart
6a8ad1eeeff153182226307bdbb32b1fe25a4125
[ "MIT" ]
null
null
null
Tree/Tree.cpp
pingpingbangbang/owchart
6a8ad1eeeff153182226307bdbb32b1fe25a4125
[ "MIT" ]
null
null
null
Tree/Tree.cpp
pingpingbangbang/owchart
6a8ad1eeeff153182226307bdbb32b1fe25a4125
[ "MIT" ]
1
2021-10-30T06:37:44.000Z
2021-10-30T06:37:44.000Z
#include "..\\stdafx.h" #include "..\\include\\Tree\\Tree.h" using namespace OwLib; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TreeA::TreeA() { m_checkBoxes = false; m_checkBoxSize.cx = 14; m_checkBoxSize.cy = 14; GridA::SetGridLineColor(COLOR_EMPTY); m_movingNode = 0; m_nodeSize.cx = 14; m_nodeSize.cy = 14; } TreeA::~TreeA() { m_movingNode = 0; } bool TreeA::HasCheckBoxes() { return m_checkBoxes; } void TreeA::SetCheckBoxes( bool checkBoxes ) { m_checkBoxes = checkBoxes; } SIZE TreeA::GetCheckBoxSize() { return m_checkBoxSize; } void TreeA::SetCheckBoxSize( SIZE checkBoxSize ) { m_checkBoxSize = checkBoxSize; } String TreeA::GetCheckedImage() { return m_checkedImage; } void TreeA::SetCheckedImage( const String& checkedImage ) { m_checkedImage = checkedImage; } String TreeA::GetCollapsedNodeImage() { return m_collapsedNodeImage; } void TreeA::SetCollapsedNodeImage( const String& collapsedNodeImage ) { m_collapsedNodeImage = collapsedNodeImage; } String TreeA::GetExpendedNodeImage() { return m_expendedNodeImage; } void TreeA::SetExpendedNodeImage( const String& expendedNodeImage ) { m_expendedNodeImage = expendedNodeImage; } SIZE TreeA::GetNodeSize() { return m_nodeSize; } void TreeA::SetNodeSize( SIZE nodeSize ) { m_nodeSize = nodeSize; } vector<TreeNodeA*> TreeA::GetSelectedNodes() { vector<TreeNodeA*> list; vector<GridRow*> selectedRows = GetSelectedRows(); int count = (int)selectedRows.size(); for (int i = 0; i < count; i++) { vector<GridCell*> cells = selectedRows[i]->m_cells; int num3 = (int)cells.size(); for (int j = 0; j < num3; j++) { TreeNodeA *item = (TreeNodeA*)cells[j]; if (item) { list.push_back(item); break; } } } return list; } void TreeA::SetSelectedNodes( vector<TreeNodeA*> selectedNodes ) { int count = (int)selectedNodes.size(); vector<GridRow*> list; for (int i = 0; i < count; i++) { list.push_back(selectedNodes[i]->GetRow()); } SetSelectedRows(list); } String TreeA::GetUnCheckedImage() { return m_unCheckedImage; } void TreeA::SetUnCheckedImage( const String& unCheckedImage ) { m_unCheckedImage = unCheckedImage; } void TreeA::AppendNode( TreeNodeA *node ) { node->SetTree(this); node->OnAddingNode(-1); m_nodes.push_back(node); } void TreeA::ClearNodes() { int count = (int)m_nodes.size(); for (int i = 0; i < count; i++) { RemoveNode(m_nodes[i]); } m_nodes.clear(); } void TreeA::Collapse() { int count = (int)m_nodes.size(); for (int i = 0; i < count; i++) { m_nodes[i]->Collapse(); } } void TreeA::CollapseAll() { int count = (int)m_nodes.size(); for (int i = 0; i < count; i++) { m_nodes[i]->CollapseAll(); } } void TreeA::Expend() { int count = (int)m_nodes.size(); for (int i = 0; i < count; i++) { m_nodes[i]->Expend(); } } void TreeA::ExpendAll() { int count = (int)m_nodes.size(); for (int i = 0; i < count; i++) { m_nodes[i]->ExpendAll(); } } vector<TreeNodeA*> TreeA::GetChildNodes() { return m_nodes; } String TreeA::GetControlType() { return L"Tree"; } int TreeA::GetNodeIndex( TreeNodeA *node ) { int count = (int)m_nodes.size(); for (int i = 0; i < count; i++) { if (m_nodes[i] == node) { return i; } } return -1; } void TreeA::GetProperty( const String& name, String *value, String *type ) { if (name == L"checkboxes") { *type = L"bool"; *value = CStr::ConvertBoolToStr(HasCheckBoxes()); } else if (name == L"checkboxsize") { *type = L"size"; *value = CStr::ConvertSizeToStr(GetCheckBoxSize()); } else if (name == L"checkedimage") { *type = L"String"; *value = GetCheckedImage(); } else if (name == L"collapsednodeimage") { *type = L"String"; *value = GetCollapsedNodeImage(); } else if (name == L"expendednodeimage") { *type = L"String"; *value = GetExpendedNodeImage(); } else if (name == L"uncheckedimage") { *type = L"String"; *value = GetUnCheckedImage(); } else if (name == L"nodesize") { *type = L"size"; *value = CStr::ConvertSizeToStr(GetNodeSize()); } else { GridA::GetProperty(name, value, type); } } vector<String> TreeA::GetPropertyNames() { vector<String> propertyNames = GridA::GetPropertyNames(); propertyNames.push_back(L"CheckBoxes"); propertyNames.push_back(L"CheckBoxSize"); propertyNames.push_back(L"CheckedImage"); propertyNames.push_back(L"CollapsedNodeImage"); propertyNames.push_back(L"ExpendedNodeImage"); propertyNames.push_back(L"UnCheckedImage"); propertyNames.push_back(L"NodeSize"); return propertyNames; } void TreeA::InsertNode( int index, TreeNodeA *node ) { int num = -1; if (index == 0) { if (node->GetParent()) { num = node->GetParent()->GetRow()->GetIndex() + 1; } else { num = 0; } } else if (!m_nodes.empty()) { num = m_nodes[index]->GetRow()->GetIndex(); } node->SetTree(this); node->OnAddingNode(num); m_nodes.insert(m_nodes.begin() + index, node); } void TreeA::OnCellMouseDown( GridCell *cell, const POINT& mp, MouseButtonsA button, int clicks, int delta ) { GridA::OnCellMouseDown(cell, mp, button, clicks, delta); TreeNodeA *ea = (TreeNodeA*)cell; if (ea) { int pos = 0; HScrollBarA *hScrollBar = GetHScrollBar(); if (hScrollBar && hScrollBar->IsVisible()) { pos = hScrollBar->GetPos(); } RECT bounds = ea->GetTargetColumn()->GetBounds(); bounds.left += GetHorizontalOffset() - pos; bounds.top += GetVerticalOffset() - pos; int left = bounds.left; if (m_checkBoxes) { int cx = m_checkBoxSize.cx; if ((mp.x >= left) && (mp.x <= (left + cx))) { ea->SetChecked(!ea->IsChecked()); return; } left += cx + 10; } vector<TreeNodeA*> childNodes = ea->GetChildNodes(); if (!childNodes.empty()) { int num4 = m_nodeSize.cx; if ((mp.x >= left) && (mp.x <= (left + num4))) { if (ea->IsExpended()) { ea->Collapse(); } else { ea->Expend(); } Update(); return; } } if (ea->AllowDragOut()) { m_movingNode = ea; } } } void TreeA::OnCellMouseMove( GridCell *cell, const POINT& mp, MouseButtonsA button, int clicks, int delta ) { GridA::OnCellMouseMove(cell, mp, button, clicks, delta); if (m_movingNode) { Invalidate(); } } void TreeA::OnCellMouseUp( GridCell *cell, const POINT& mp, MouseButtonsA button, int clicks, int delta ) { GridA::OnCellMouseUp(cell, mp, button, clicks, delta); if (m_movingNode) { GridRow *row = GetRow(mp); if (row) { TreeNodeA *node = (TreeNodeA*)(row->GetCell(0)); if (node->AllowDragIn() && (m_movingNode != node)) { TreeNodeA *parent = node->GetParent(); TreeNodeA *ea3 = m_movingNode->GetParent(); if (ea3) { ea3->RemoveNode(m_movingNode); } else { RemoveNode(m_movingNode); } if (parent) { if (ea3 == parent) { parent->InsertNode(parent->GetNodeIndex(node), m_movingNode); } else { node->AppendNode(m_movingNode); } } else if (ea3 == parent) { InsertNode(GetNodeIndex(node), m_movingNode); } else { node->AppendNode(m_movingNode); } node->Expend(); } } m_movingNode = 0; Update(); } } void TreeA::OnPaintForeground( CPaint *paint, const RECT& clipRect ) { GridA::OnPaintForeground(paint, clipRect); if (m_movingNode) { FONT *font = GetFont(); POINT mousePoint = GetMousePoint(); SIZE size = paint->TextSize(m_movingNode->GetText().c_str(), font); RECT rect = {mousePoint.x, mousePoint.y, mousePoint.x + size.cx, mousePoint.y + size.cy}; paint->DrawText(m_movingNode->GetText().c_str(), GetForeColor(), font, rect); } } void TreeA::OnPaintEditTextBox( GridCell *cell, CPaint *paint, const RECT& rc, const RECT& clipRect ) { RECT rect = rc; TextBoxA *editTextBox = GetEditTextBox(); if (editTextBox) { TreeNodeA *ea = (TreeNodeA*)cell; if (ea) { int indent = ea->GetIndent(); rect.left += indent; if (rect.right < rect.left) { rect.right = rect.left; } editTextBox->SetBounds(rect); editTextBox->SetDisplayOffset(false); editTextBox->BringToFront(); } else { GridA::OnPaintEditTextBox(cell, paint, rect, clipRect); } } } void TreeA::RemoveNode( TreeNodeA *node ) { node->OnRemovingNode(); for (vector<TreeNodeA*>::iterator it = m_nodes.begin(); it != m_nodes.end(); it++) { if (*it == node) { m_nodes.erase(it); break; } } } void TreeA::SetProperty( const String& name, const String& value ) { if (name == L"checkboxes") { SetCheckBoxes(CStr::ConvertStrToBool(value)); } else if (name == L"checkboxsize") { SetCheckBoxSize(CStr::ConvertStrToSize(value)); } else if (name == L"checkedimage") { SetCheckedImage(value); } else if (name == L"collapsednodeimage") { SetCollapsedNodeImage(value); } else if (name == L"expendednodeimage") { SetExpendedNodeImage(value); } else if (name == L"uncheckedimage") { SetUnCheckedImage(value); } else if (name == L"nodesize") { SetNodeSize(CStr::ConvertStrToSize(value)); } else { GridA::SetProperty(name, value); } }
19.273684
155
0.636592
[ "vector" ]
a6f61643c320df511fb5365119db1d5b685a2639
12,827
cpp
C++
csv/test/ascii_test.cpp
mission-systems-pty-ltd/comma
3ccec0b206fb15a8c048358a7fc01be61a7e4f1e
[ "BSD-3-Clause" ]
21
2015-05-07T06:11:09.000Z
2022-02-01T09:55:46.000Z
csv/test/ascii_test.cpp
mission-systems-pty-ltd/comma
3ccec0b206fb15a8c048358a7fc01be61a7e4f1e
[ "BSD-3-Clause" ]
17
2015-01-16T01:38:08.000Z
2020-03-30T09:05:01.000Z
csv/test/ascii_test.cpp
mission-systems-pty-ltd/comma
3ccec0b206fb15a8c048358a7fc01be61a7e4f1e
[ "BSD-3-Clause" ]
13
2016-01-13T01:29:29.000Z
2022-02-01T09:55:49.000Z
// This file is part of comma, a generic and flexible library // Copyright (c) 2011 The University of Sydney // 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 University of Sydney nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE // GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT // HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE // OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN // IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <gtest/gtest.h> #include <boost/date_time/posix_time/posix_time.hpp> #include "../../csv/ascii.h" #include "../../string/string.h" namespace comma { namespace csv { namespace ascii_test { struct nested { int x; int y; nested() : x( 0 ), y( 0 ) {} }; struct simple_struct { int a; double b; char c; std::string s; boost::posix_time::ptime t; ascii_test::nested nested; simple_struct() : a( 0 ), b( 0 ), c( 0 ) {} }; struct test_struct { int a; boost::optional< int > z; boost::optional< ascii_test::nested > nested; }; struct containers { boost::array< int, 4 > array; }; struct vector_container { std::vector< int > vector; }; } } } // namespace comma { namespace csv { namespace ascii_test { namespace comma { namespace visiting { template <> struct traits< comma::csv::ascii_test::nested > { template < typename Key, class Visitor > static void visit( const Key&, const comma::csv::ascii_test::nested& p, Visitor& v ) { v.apply( "x", p.x ); v.apply( "y", p.y ); } template < typename Key, class Visitor > static void visit( const Key&, comma::csv::ascii_test::nested& p, Visitor& v ) { v.apply( "x", p.x ); v.apply( "y", p.y ); } }; template <> struct traits< comma::csv::ascii_test::simple_struct > { template < typename Key, class Visitor > static void visit( const Key&, const comma::csv::ascii_test::simple_struct& p, Visitor& v ) { v.apply( "a", p.a ); v.apply( "b", p.b ); v.apply( "c", p.c ); v.apply( "s", p.s ); v.apply( "t", p.t ); v.apply( "nested", p.nested ); } template < typename Key, class Visitor > static void visit( const Key&, comma::csv::ascii_test::simple_struct& p, Visitor& v ) { v.apply( "a", p.a ); v.apply( "b", p.b ); v.apply( "c", p.c ); v.apply( "s", p.s ); v.apply( "t", p.t ); v.apply( "nested", p.nested ); } }; template <> struct traits< comma::csv::ascii_test::test_struct > { template < typename Key, class Visitor > static void visit( const Key&, const comma::csv::ascii_test::test_struct& p, Visitor& v ) { v.apply( "a", p.a ); v.apply( "z", p.z ); v.apply( "nested", p.nested ); } template < typename Key, class Visitor > static void visit( const Key&, comma::csv::ascii_test::test_struct& p, Visitor& v ) { v.apply( "a", p.a ); v.apply( "z", p.z ); v.apply( "nested", p.nested ); } }; template <> struct traits< comma::csv::ascii_test::containers > { template < typename Key, class Visitor > static void visit( const Key&, const comma::csv::ascii_test::containers& p, Visitor& v ) { v.apply( "array", p.array ); } template < typename Key, class Visitor > static void visit( const Key&, comma::csv::ascii_test::containers& p, Visitor& v ) { v.apply( "array", p.array ); } }; template <> struct traits< comma::csv::ascii_test::vector_container > { template < typename Key, class Visitor > static void visit( const Key&, const comma::csv::ascii_test::vector_container& p, Visitor& v ) { v.apply( "vector", p.vector ); } template < typename Key, class Visitor > static void visit( const Key&, comma::csv::ascii_test::vector_container& p, Visitor& v ) { v.apply( "vector", p.vector ); } }; } } // namespace comma { namespace visiting { TEST( csv, ascii_constructor ) { //EXPECT_THROW( comma::csv::ascii< comma::csv::ascii_test::simple_struct >( "blah" ), comma::exception ); //EXPECT_NO_THROW( comma::csv::ascii< comma::csv::ascii_test::simple_struct >( "a" ) ); //EXPECT_NO_THROW( comma::csv::ascii< comma::csv::ascii_test::simple_struct >() ); EXPECT_EQ( comma::join( comma::csv::names< comma::csv::ascii_test::simple_struct >( ",,,," ), ',' ), ",,,," ); } TEST( csv, ascii_get ) { { comma::csv::ascii_test::simple_struct s; EXPECT_EQ( comma::join( comma::csv::names( s ), ',' ), "a,b,c,s,t,nested/x,nested/y" ); comma::csv::ascii< comma::csv::ascii_test::simple_struct > ascii; ascii.get( s, "1,2,'c',hello,20110304T111111.1234,5,6" ); EXPECT_EQ( s.a, 1 ); EXPECT_EQ( s.b, 2 ); EXPECT_EQ( s.c, 'c' ); EXPECT_EQ( s.s, "hello" ); EXPECT_EQ( s.t, boost::posix_time::from_iso_string( "20110304T111111.1234" ) ); EXPECT_EQ( s.nested.x, 5 ); EXPECT_EQ( s.nested.y, 6 ); } { comma::csv::ascii_test::simple_struct s; comma::csv::ascii< comma::csv::ascii_test::simple_struct > ascii( ",,,," ); ascii.get( s, "1,2,'c',\"hello\",20110304T111111.1234,5,6" ); EXPECT_EQ( s.a, 0 ); EXPECT_EQ( s.b, 0 ); EXPECT_EQ( s.c, 0 ); EXPECT_EQ( s.s, "" ); EXPECT_EQ( s.t, boost::posix_time::not_a_date_time ); EXPECT_EQ( s.nested.x, 0 ); EXPECT_EQ( s.nested.y, 0 ); } { comma::csv::ascii_test::simple_struct s; comma::csv::ascii< comma::csv::ascii_test::simple_struct > ascii( ",,,,t,," ); ascii.get( s, "1,2,'c',\"hello\",20110304T111111.1234,5,6" ); EXPECT_EQ( s.a, 0 ); EXPECT_EQ( s.b, 0 ); EXPECT_EQ( s.c, 0 ); EXPECT_EQ( s.s, "" ); EXPECT_EQ( s.t, boost::posix_time::from_iso_string( "20110304T111111.1234" ) ); EXPECT_EQ( s.nested.x, 0 ); EXPECT_EQ( s.nested.y, 0 ); } // todo: more testing } TEST( csv, ascii_put ) { // todo } TEST( csv, ascii_optional_element ) { { comma::csv::ascii_test::test_struct s; EXPECT_EQ( comma::join( comma::csv::names( s ), ',' ), "a,z,nested/x,nested/y" ); comma::csv::ascii< comma::csv::ascii_test::test_struct > ascii; ascii.get( s, "1,2,3,4" ); // TODO fails on windows EXPECT_TRUE( bool( s.z ) ); EXPECT_TRUE( bool( s.nested ) ); EXPECT_EQ( s.a, 1 ); EXPECT_EQ( *s.z, 2 ); EXPECT_EQ( s.nested->x, 3 ); EXPECT_EQ( s.nested->y, 4 ); } { comma::csv::ascii_test::test_struct s; comma::csv::ascii< comma::csv::ascii_test::test_struct > ascii( ",,z" ); ascii.get( s, "1,2,3" ); EXPECT_TRUE( bool( s.z ) ); EXPECT_FALSE( s.nested ); EXPECT_EQ( *s.z, 3 ); } { comma::csv::ascii_test::test_struct s; comma::csv::ascii< comma::csv::ascii_test::test_struct > ascii( "nested,z" ); ascii.get( s, "1,2,3" ); EXPECT_TRUE( bool( s.z ) ); EXPECT_TRUE( bool( s.nested ) ); EXPECT_EQ( *s.z, 3 ); EXPECT_EQ( s.nested->x, 1 ); EXPECT_EQ( s.nested->y, 2 ); } { comma::csv::ascii_test::test_struct s; comma::csv::ascii< comma::csv::ascii_test::test_struct > ascii( ",nested" ); ascii.get( s, "1,2,3" ); EXPECT_FALSE( bool( s.z ) ); EXPECT_TRUE( bool( s.nested ) ); EXPECT_EQ( s.nested->x, 2 ); EXPECT_EQ( s.nested->y, 3 ); } { comma::csv::ascii_test::test_struct s; comma::csv::ascii< comma::csv::ascii_test::test_struct > ascii( "nested,,a" ); ascii.get( s, "1,2,3,4" ); EXPECT_FALSE( bool( s.z ) ); EXPECT_TRUE( bool( s.nested ) ); EXPECT_EQ( s.nested->x, 1 ); EXPECT_EQ( s.nested->y, 2 ); EXPECT_EQ( s.a, 4 ); } { comma::csv::ascii_test::test_struct s; comma::csv::ascii< comma::csv::ascii_test::test_struct > ascii( ",x,y,a", ',', false ); ascii.get( s, "1,2,3,4" ); EXPECT_FALSE( bool( s.z ) ); EXPECT_TRUE( bool( s.nested ) ); EXPECT_EQ( s.nested->x, 2 ); EXPECT_EQ( s.nested->y, 3 ); EXPECT_EQ( s.a, 4 ); } { comma::csv::ascii< comma::csv::ascii_test::test_struct > ascii; { comma::csv::ascii_test::test_struct s; ascii.get( s, "1,2,3,4" ); EXPECT_TRUE( bool( s.z ) ); EXPECT_TRUE( bool( s.nested ) ); EXPECT_EQ( s.z, 2 ); EXPECT_EQ( s.nested->x, 3 ); EXPECT_EQ( s.nested->y, 4 ); } // { // comma::csv::ascii_test::test_struct s; // ascii.get( s, "1,,3,4" ); // EXPECT_FALSE( s.z ); // EXPECT_TRUE( s.nested ); // EXPECT_EQ( s.nested->x, 3 ); // EXPECT_EQ( s.nested->y, 4 ); // } } // todo: more testing } TEST( csv, ascii_containers ) { { comma::csv::ascii_test::containers c; for( unsigned int i = 0; i < c.array.size(); ++i ) { c.array[i] = i; } comma::csv::ascii< comma::csv::ascii_test::containers > ascii; { std::string s; ascii.put( c, s ); EXPECT_EQ( s, "0,1,2,3" ); } { std::string s = "6,7,8,9"; ascii.get( c, s ); EXPECT_EQ( c.array[0], 6 ); EXPECT_EQ( c.array[1], 7 ); EXPECT_EQ( c.array[2], 8 ); EXPECT_EQ( c.array[3], 9 ); } } { comma::csv::ascii_test::vector_container v; v.vector.resize( 3 ); for( unsigned int i = 0; i < v.vector.size(); ++i ) { v.vector[i] = i; } comma::csv::ascii< comma::csv::ascii_test::vector_container > ascii( "", ',', false, v ); { std::string s; ascii.put( v, s ); EXPECT_EQ( s, "0,1,2" ); } { std::string s = "5,6,7"; ascii.get( v, s ); EXPECT_EQ( v.vector[0], 5 ); EXPECT_EQ( v.vector[1], 6 ); EXPECT_EQ( v.vector[2], 7 ); } } { comma::csv::ascii_test::vector_container v; v.vector.resize( 3 ); for( unsigned int i = 0; i < v.vector.size(); ++i ) { v.vector[i] = i; } comma::csv::ascii< comma::csv::ascii_test::vector_container > ascii( "vector[0],vector[1],vector[2]", ',', false, v ); { std::string s; ascii.put( v, s ); EXPECT_EQ( s, "0,1,2" ); } { std::string s = "5,6,7"; ascii.get( v, s ); EXPECT_EQ( v.vector[0], 5 ); EXPECT_EQ( v.vector[1], 6 ); EXPECT_EQ( v.vector[2], 7 ); } } { comma::csv::ascii_test::vector_container v; v.vector.resize( 3 ); for( unsigned int i = 0; i < v.vector.size(); ++i ) { v.vector[i] = i; } comma::csv::ascii< comma::csv::ascii_test::vector_container > ascii( "vector[0],vector[2]", ',', false, v ); { std::string s; ascii.put( v, s ); EXPECT_EQ( s, "0,2" ); } { std::string s = "5,6"; ascii.get( v, s ); EXPECT_EQ( v.vector[0], 5 ); EXPECT_EQ( v.vector[1], 1 ); EXPECT_EQ( v.vector[2], 6 ); } } // todo: more tests } int main( int argc, char* argv[] ) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
33.666667
139
0.555469
[ "vector" ]
a6fae0c8c5d62c8ebd00155a7288e27784078060
23,321
cc
C++
third-party/paxos/src/deptran/paxos/server.cc
shenweihai1/rolis-eurosys2022
59b3fd58144496a9b13415e30b41617b34924323
[ "MIT" ]
1
2022-03-08T00:36:10.000Z
2022-03-08T00:36:10.000Z
third-party/paxos/src/deptran/paxos/server.cc
shenweihai1/rolis-eurosys2022
59b3fd58144496a9b13415e30b41617b34924323
[ "MIT" ]
null
null
null
third-party/paxos/src/deptran/paxos/server.cc
shenweihai1/rolis-eurosys2022
59b3fd58144496a9b13415e30b41617b34924323
[ "MIT" ]
null
null
null
#include "server.h" #include "../paxos_worker.h" #include "exec.h" namespace janus { shared_ptr<ElectionState> es = ElectionState::instance(); void PaxosServer::OnPrepare(slotid_t slot_id, ballot_t ballot, ballot_t *max_ballot, const function<void()> &cb) { std::lock_guard<std::recursive_mutex> lock(mtx_); Log_debug("multi-paxos scheduler receives prepare for slot_id: %llx", slot_id); auto instance = GetInstance(slot_id); verify(ballot != instance->max_ballot_seen_); if (instance->max_ballot_seen_ < ballot) { instance->max_ballot_seen_ = ballot; } else { // TODO if accepted anything, return; verify(0); } *max_ballot = instance->max_ballot_seen_; n_prepare_++; cb(); } void PaxosServer::OnAccept(const slotid_t slot_id, const ballot_t ballot, shared_ptr<Marshallable> &cmd, ballot_t *max_ballot, const function<void()> &cb) { std::lock_guard<std::recursive_mutex> lock(mtx_); Log_debug("multi-paxos scheduler accept for slot_id: %llx", slot_id); auto instance = GetInstance(slot_id); verify(instance->max_ballot_accepted_ < ballot); if (instance->max_ballot_seen_ <= ballot) { instance->max_ballot_seen_ = ballot; instance->max_ballot_accepted_ = ballot; } else { // TODO verify(0); } *max_ballot = instance->max_ballot_seen_; n_accept_++; cb(); } void PaxosServer::OnCommit(const slotid_t slot_id, const ballot_t ballot, shared_ptr<Marshallable> &cmd) { std::lock_guard<std::recursive_mutex> lock(mtx_); Log_debug("multi-paxos scheduler decide for slot: %lx", slot_id); auto instance = GetInstance(slot_id); instance->committed_cmd_ = cmd; if (slot_id > max_committed_slot_) { max_committed_slot_ = slot_id; } verify(slot_id > max_executed_slot_); for (slotid_t id = max_executed_slot_ + 1; id <= max_committed_slot_; id++) { auto next_instance = GetInstance(id); if (next_instance->committed_cmd_) { app_next_(*next_instance->committed_cmd_); Log_debug("multi-paxos par:%d loc:%d executed slot %lx now", partition_id_, loc_id_, id); max_executed_slot_++; n_commit_++; } else { break; } } FreeSlots(); } // marker:ansh change the args to accomodate objects // marker:ansh add a suitable reply at bottom void PaxosServer::OnBulkPrepare(shared_ptr<Marshallable> &cmd, i32* ballot, i32* valid, const function<void()> &cb) { auto bp_log = dynamic_pointer_cast<BulkPrepareLog>(cmd); es->state_lock(); if(bp_log->epoch < es->cur_epoch){ //es->state_unlock(); *valid = 0; *ballot = es->cur_epoch; es->state_unlock(); cb(); return; } if(bp_log->epoch == es->cur_epoch && bp_log->leader_id != es->machine_id){ //es->state_unlock(); *valid = 0; *ballot = es->cur_epoch; es->state_unlock(); cb(); return; } /* acquire all other server locks one by one */ Log_info("Paxos workers size %d %d %d", pxs_workers_g.size(), bp_log->leader_id, bp_log->epoch, es->cur_epoch); for(int i = 0; i < bp_log->min_prepared_slots.size(); i++){ //if(pxs_workers_g[i]) // Log_info("cast successfull %d", i); PaxosServer* ps = (PaxosServer*)(pxs_workers_g[i]->rep_sched_); ps->mtx_.lock(); } /*verify possibility before modification*/ for(int i = 0; i < bp_log->min_prepared_slots.size(); i++){ slotid_t slot_id_min = bp_log->min_prepared_slots[i].second; PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); BulkPrepare* bp = &ps->bulk_prepares[make_pair(ps->cur_min_prepared_slot_, ps->max_possible_slot_)]; if(ps->bulk_prepares.size() != 0 && bp->seen_ballot > bp_log->epoch){ verify(0); // should not happen, should have been caught bp_log->epoch. } else{ // debug //if(slot_id_min <= ps->max_committed_slot_){ // verify(0); // marker:ansh to handle. // handle later //} } } for(int i = 0; i < bp_log->min_prepared_slots.size(); i++){ slotid_t slot_id_min = bp_log->min_prepared_slots[i].second; PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); BulkPrepare* bp = &ps->bulk_prepares[make_pair(ps->cur_min_prepared_slot_, ps->max_possible_slot_)]; ps->bulk_prepares.erase(make_pair(ps->cur_min_prepared_slot_, ps->max_possible_slot_)); bp->seen_ballot = bp_log->epoch; bp->leader_id = bp_log->leader_id; ps->bulk_prepares[make_pair(slot_id_min, max_possible_slot_)] = *bp; ps->cur_min_prepared_slot_ = slot_id_min; ps->cur_epoch = bp_log->epoch; // ps->clear_accepted_entries(); // pending bulk-prepare-return } unlock_and_return: /* change election state holder */ if(es->machine_id != bp_log->leader_id) es->set_state(0); es->set_leader(bp_log->leader_id); es->set_lastseen(); Log_info("Leader set to %d", bp_log->leader_id); es->set_epoch(bp_log->epoch); for(int i = 0; i < bp_log->min_prepared_slots.size(); i++){ PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); ps->mtx_.unlock(); } *ballot = es->cur_epoch; es->state_unlock(); Log_debug("BulkPrepare: Terminating RPC here"); *valid = 1; cb(); } void PaxosServer::OnHeartbeat(shared_ptr<Marshallable> &cmd, i32* ballot, i32* valid, const function<void()> &cb){ auto hb_log = dynamic_pointer_cast<HeartBeatLog>(cmd); es->state_lock(); if(hb_log->epoch < es->cur_epoch){ es->state_unlock(); *valid = 0; *ballot = es->cur_epoch; cb(); return; } if(hb_log->leader_id == 1 && es->machine_id == 2) Log_debug("OnHeartbeat: received heartbeat from machine is %d %d", hb_log->leader_id, es->leader_id); if(hb_log->epoch == es->cur_epoch){ if(hb_log->leader_id != es->leader_id){ Log_info("Req leader is %d while machine leader is %d", hb_log->leader_id, es->leader_id); es->state_unlock(); verify(0); // should not happen, means there are two leaders with different in the same epoch. } else if(hb_log->leader_id == es->leader_id){ if(hb_log->leader_id != es->machine_id) es->set_state(0); es->set_epoch(hb_log->epoch); es->set_lastseen(); es->state_unlock(); *valid = 1; cb(); return; } else{ es->set_lastseen(); es->state_unlock(); *valid = 1; cb(); return; } } else{ // in this case reply needs to be that it needs a prepare. *valid = 2 + es->machine_id; // hacky way. es->set_state(0); es->set_epoch(hb_log->epoch); for(int i = 0; i < pxs_workers_g.size()-1; i++){ PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); ps->mtx_.lock(); ps->cur_epoch = hb_log->epoch; ps->leader_id = hb_log->leader_id; ps->mtx_.unlock(); } es->set_lastseen(); es->set_leader(hb_log->leader_id); es->state_unlock(); *valid = 1; cb(); return; } } void PaxosServer::OnBulkPrepare2(shared_ptr<Marshallable> &cmd, i32* ballot, i32* valid, shared_ptr<BulkPaxosCmd> ret_cmd, const function<void()> &cb){ pthread_setname_np(pthread_self(), "Follower server thread"); auto bcmd = dynamic_pointer_cast<PaxosPrepCmd>(cmd); ballot_t cur_b = bcmd->ballots[0]; slotid_t cur_slot = bcmd->slots[0]; int req_leader = bcmd->leader_id; if(req_leader == 1 && es->machine_id != 1) Log_debug("Prepare Received from new leader"); //Log_info("Received paxos Prepare for slot %d ballot %d machine %d",cur_slot, cur_b, req_leader); *valid = 1; //cb(); //return; auto rbcmd = make_shared<BulkPaxosCmd>(); Log_debug("Received paxos Prepare for slot %d ballot %d machine %d",cur_slot, cur_b, req_leader); //es->state_lock(); mtx_.lock(); if(cur_b < cur_epoch){ *ballot = cur_epoch; //es->state_unlock(); *valid = 0; mtx_.unlock(); cb(); return; } mtx_.unlock(); es->state_lock(); es->set_lastseen(); if(req_leader != es->machine_id) es->set_state(0); es->state_unlock(); mtx_.lock(); max_touched_slot = max(max_touched_slot, cur_slot); if(cur_b > cur_epoch){ mtx_.unlock(); es->state_lock(); es->set_epoch(cur_b); es->set_leader(req_leader); // marker:ansh send leader in every request. for(int i = 0; i < pxs_workers_g.size()-1; i++){ PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); ps->mtx_.lock(); ps->cur_epoch = cur_b; ps->leader_id = req_leader; ps->mtx_.unlock(); } es->state_unlock(); } else{ mtx_.unlock(); if(req_leader != es->leader_id){ Log_info("Req leader is %d and prev leader is %d", req_leader, es->leader_id); verify(0); //more than one leader in a term, should not send prepare if not leader. } } mtx_.lock(); auto instance = GetInstance(cur_slot); Log_debug("OnBulkPrepare2: Checks successfull preparing response for slot %d %d", cur_slot, partition_id_); if(!instance || !instance->accepted_cmd_){ mtx_.unlock(); *valid = 2; *ballot = cur_b; //*ret_cmd = *bcmd; // ret_cmd->ballots.push_back(bcmd->ballots[0]); // ret_cmd->slots.push_back(bcmd->slots[0]); // ret_cmd->cmds.push_back(bcmd->cmds[0]); //Log_info("OnBulkPrepare2: the kind_ of the response object is"); //es->state_unlock(); cb(); //es->state_unlock(); return; } //es->state_unlock(); Log_debug("OnBulkPrepare2: instance found, Preparing response"); ret_cmd->ballots.push_back(instance->max_ballot_accepted_); ret_cmd->slots.push_back(cur_slot); ret_cmd->cmds.push_back(make_shared<MarshallDeputy>(instance->accepted_cmd_)); mtx_.unlock(); cb(); } void PaxosServer::OnSyncLog(shared_ptr<Marshallable> &cmd, i32* ballot, i32* valid, shared_ptr<SyncLogResponse> ret_cmd, const function<void()> &cb){ auto bcmd = dynamic_pointer_cast<SyncLogRequest>(cmd); es->state_lock(); if(bcmd->epoch < es->cur_epoch){ //es->state_unlock(); *valid = 0; *ballot = es->cur_epoch; es->state_unlock(); cb(); return; } es->state_unlock(); *valid = 1; for(int i = 0; i < pxs_workers_g.size()-1; i++){ ret_cmd->missing_slots.push_back(vector<slotid_t>{}); PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); auto bp_cmd = make_shared<BulkPaxosCmd>(); ps->mtx_.lock(); for(int j = bcmd->sync_commit_slot[i]; j <= ps->max_committed_slot_; j++){ auto inst = ps->GetInstance(j); if(inst->committed_cmd_){ bp_cmd->slots.push_back(j); bp_cmd->ballots.push_back(inst->max_ballot_accepted_); auto temp_cmd = inst->committed_cmd_; MarshallDeputy md(temp_cmd); auto shrd_ptr = make_shared<MarshallDeputy>(md); bp_cmd->cmds.push_back(shrd_ptr); } } Log_info("The partition %d, and max executed slot is %d and sync commit is %d", i, ps->max_executed_slot_, bcmd->sync_commit_slot[i]); for(int j = ps->max_executed_slot_; j < bcmd->sync_commit_slot[i]; j++){ auto inst = ps->GetInstance(j); if(!inst->committed_cmd_){ ret_cmd->missing_slots[i].push_back(j); } } Log_info("The partition %d has missing slots size %d", i, ret_cmd->missing_slots[i].size()); auto sp_marshallable = dynamic_pointer_cast<Marshallable>(bp_cmd); MarshallDeputy bp_md_cmd(sp_marshallable); auto bp_sp_md = make_shared<MarshallDeputy>(bp_md_cmd); ret_cmd->sync_data.push_back(bp_sp_md); ps->mtx_.unlock(); } cb(); } void PaxosServer::OnBulkAccept(shared_ptr<Marshallable> &cmd, i32* ballot, i32* valid, const function<void()> &cb) { //Log_info("here accept"); //std::lock_guard<std::recursive_mutex> lock(mtx_); auto bcmd = dynamic_pointer_cast<BulkPaxosCmd>(cmd); *valid = 1; ballot_t cur_b = bcmd->ballots[0]; slotid_t cur_slot = bcmd->slots[0]; int req_leader = bcmd->leader_id; if(req_leader == 1 && es->machine_id != 1) Log_debug("Accept Received from new leader"); //Log_debug("multi-paxos scheduler accept for slot: %lx", bcmd->slots.size()); //es->state_lock(); mtx_.lock(); if(cur_b < cur_epoch){ *ballot = cur_epoch; //es->state_unlock(); *valid = 0; mtx_.unlock(); cb(); return; } mtx_.unlock(); es->state_lock(); es->set_lastseen(); if(req_leader != es->machine_id) es->set_state(0); es->state_unlock(); //cb(); //return; //Log_info("multi-paxos scheduler accept for slot: %ld, par_id: %d", cur_slot, partition_id_); for(int i = 0; i < bcmd->slots.size(); i++){ slotid_t slot_id = bcmd->slots[i]; ballot_t ballot_id = bcmd->ballots[i]; mtx_.lock(); if(cur_epoch > ballot_id){ *valid = 0; *ballot = cur_epoch; mtx_.unlock(); break; } else{ if(cur_epoch < ballot_id){ mtx_.unlock(); //Log_info("I am here"); for(int i = 0; i < pxs_workers_g.size()-1; i++){ PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); ps->mtx_.lock(); ps->cur_epoch = ballot_id; ps->leader_id = req_leader; ps->mtx_.unlock(); } } else{ mtx_.unlock(); } es->state_lock(); es->set_leader(req_leader); es->state_unlock(); auto instance = GetInstance(slot_id); //verify(instance->max_ballot_accepted_ < ballot_id); instance->max_ballot_seen_ = ballot_id; instance->max_ballot_accepted_ = ballot_id; instance->accepted_cmd_ = bcmd->cmds[i].get()->sp_data_; max_accepted_slot_ = slot_id; n_accept_++; *valid &= 1; *ballot = ballot_id; } } if(req_leader != 0) Log_debug("multi-paxos scheduler accept for slot: %ld, par_id: %d", cur_slot, partition_id_); //es->state_unlock(); cb(); //Log_info("multi-paxos scheduler accept for slot: %ld, par_id: %d", cur_slot, partition_id_); } void PaxosServer::OnSyncCommit(shared_ptr<Marshallable> &cmd, i32* ballot, i32* valid, const function<void()> &cb) { //Log_info("here"); //std::lock_guard<std::recursive_mutex> lock(mtx_); //mtx_.lock(); //Log_info("here"); //Log_info("multi-paxos scheduler decide for slot: %ld", bcmd->slots.size()); auto bcmd = dynamic_pointer_cast<BulkPaxosCmd>(cmd); *valid = 1; ballot_t cur_b = bcmd->ballots[0]; slotid_t cur_slot = bcmd->slots[0]; //Log_info("multi-paxos scheduler decide for slot: %ld", cur_slot); int req_leader = bcmd->leader_id; //es->state_lock(); mtx_.lock(); if(cur_b < cur_epoch){ *ballot = cur_epoch; //es->state_unlock(); *valid = 0; mtx_.unlock(); cb(); return; } mtx_.unlock(); es->state_lock(); es->set_lastseen(); if(req_leader != es->machine_id) es->set_state(0); es->state_unlock(); vector<shared_ptr<PaxosData>> commit_exec; for(int i = 0; i < bcmd->slots.size(); i++){ //break; slotid_t slot_id = bcmd->slots[i]; ballot_t ballot_id = bcmd->ballots[i]; mtx_.lock(); if(cur_epoch > ballot_id){ *valid = 0; *ballot = cur_epoch; mtx_.unlock(); break; } else{ if(cur_epoch < ballot_id){ mtx_.unlock(); for(int i = 0; i < pxs_workers_g.size()-1; i++){ PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); ps->mtx_.lock(); ps->cur_epoch = ballot_id; ps->leader_id = req_leader; ps->mtx_.unlock(); } } else{ mtx_.unlock(); } es->state_lock(); es->set_leader(req_leader); es->state_unlock(); auto instance = GetInstance(slot_id); verify(instance->max_ballot_accepted_ <= ballot_id); instance->max_ballot_seen_ = ballot_id; instance->max_ballot_accepted_ = ballot_id; instance->committed_cmd_ = bcmd->cmds[i].get()->sp_data_; *valid &= 1; if (slot_id > max_committed_slot_) { max_committed_slot_ = slot_id; } } } //es->state_unlock(); if(*valid == 0){ cb(); return; } //mtx_.lock(); //Log_info("The commit batch size is %d", bcmd->slots.size()); for (slotid_t id = max_executed_slot_ + 1; id <= max_committed_slot_; id++) { //break; auto next_instance = GetInstance(id); if (next_instance->committed_cmd_) { //app_next_(*next_instance->committed_cmd_); commit_exec.push_back(next_instance); //Log_debug("multi-paxos par:%d loc:%d executed slot %lx now", partition_id_, loc_id_, id); max_executed_slot_++; n_commit_++; } else { break; } } //mtx_.unlock(); //Log_info("Committing %d", commit_exec.size()); for(int i = 0; i < commit_exec.size(); i++){ //auto x = new PaxosData(); app_next_(*commit_exec[i]->committed_cmd_); } *valid = 1; //cb(); //mtx_.lock(); //FreeSlots(); //mtx_.unlock(); cb(); } void PaxosServer::OnBulkCommit(shared_ptr<Marshallable> &cmd, i32* ballot, i32* valid, const function<void()> &cb) { //Log_info("here"); //std::lock_guard<std::recursive_mutex> lock(mtx_); //mtx_.lock(); //Log_info("here"); //Log_info("multi-paxos scheduler decide for slot: %ld", bcmd->slots.size()); auto bcmd = dynamic_pointer_cast<PaxosPrepCmd>(cmd); *valid = 1; ballot_t cur_b = bcmd->ballots[0]; slotid_t cur_slot = bcmd->slots[0]; //Log_info("multi-paxos scheduler decide for slot: %ld", cur_slot); int req_leader = bcmd->leader_id; //es->state_lock(); mtx_.lock(); if(cur_b < cur_epoch){ *ballot = cur_epoch; //es->state_unlock(); *valid = 0; mtx_.unlock(); cb(); return; } /*if(req_leader != 0 && es->machine_id == 2) Log_info("Stuff in getting committed on machine %d", bcmd->slots[0]); */ mtx_.unlock(); es->state_lock(); es->set_lastseen(); if(req_leader != es->machine_id) es->set_state(0); es->state_unlock(); vector<shared_ptr<PaxosData>> commit_exec; for(int i = 0; i < bcmd->slots.size(); i++){ //break; slotid_t slot_id = bcmd->slots[i]; ballot_t ballot_id = bcmd->ballots[i]; mtx_.lock(); if(cur_epoch > ballot_id){ *valid = 0; *ballot = cur_epoch; mtx_.unlock(); break; } else{ if(cur_epoch < ballot_id){ mtx_.unlock(); for(int i = 0; i < pxs_workers_g.size()-1; i++){ PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); ps->mtx_.lock(); ps->cur_epoch = ballot_id; ps->leader_id = req_leader; ps->mtx_.unlock(); } } else{ mtx_.unlock(); } es->state_lock(); es->set_leader(req_leader); es->state_unlock(); auto instance = GetInstance(slot_id); verify(instance->max_ballot_accepted_ == ballot_id); //todo: for correctness, if a new commit comes, sync accept. instance->max_ballot_seen_ = ballot_id; instance->max_ballot_accepted_ = ballot_id; instance->committed_cmd_ = instance->accepted_cmd_; *valid &= 1; if (slot_id > max_committed_slot_) { max_committed_slot_ = slot_id; } } } //es->state_unlock(); if(*valid == 0){ cb(); return; } //mtx_.lock(); //Log_info("The commit batch size is %d", bcmd->slots.size()); for (slotid_t id = max_executed_slot_ + 1; id <= max_committed_slot_; id++) { //break; auto next_instance = GetInstance(id); if (next_instance->committed_cmd_) { //app_next_(*next_instance->committed_cmd_); commit_exec.push_back(next_instance); if(req_leader == 0) Log_debug("multi-paxos par:%d loc:%d executed slot %ld now", partition_id_, loc_id_, id); max_executed_slot_++; n_commit_++; } else { if(req_leader != 0) Log_info("Some slot is stopping commit %d %d and partition %d", id, bcmd->slots[0], partition_id_); break; } } if(commit_exec.size() > 0){ Log_debug("Something is getting committed %d", commit_exec.size()); } //mtx_.unlock(); //Log_info("Committing %d", commit_exec.size()); for(int i = 0; i < commit_exec.size(); i++){ //auto x = new PaxosData(); app_next_(*commit_exec[i]->committed_cmd_); } *valid = 1; //cb(); //mtx_.lock(); //FreeSlots(); //mtx_.unlock(); cb(); } void PaxosServer::OnSyncNoOps(shared_ptr<Marshallable> &cmd, i32* ballot, i32* valid, const function<void()> &cb){ auto bcmd = dynamic_pointer_cast<SyncNoOpRequest>(cmd); *valid = 1; ballot_t cur_b = bcmd->epoch; int req_leader = bcmd->leader_id; //es->state_lock(); mtx_.lock(); if(cur_b < cur_epoch){ *ballot = cur_epoch; //es->state_unlock(); *valid = 0; mtx_.unlock(); cb(); return; } mtx_.unlock(); for(int i = 0; i < pxs_workers_g.size()-1; i++){ PaxosServer* ps = dynamic_cast<PaxosServer*>(pxs_workers_g[i]->rep_sched_); ps->mtx_.lock(); if(bcmd->sync_slots[i] <= ps->max_executed_slot_){ Log_info("The sync slot is %d for partition %d and committed slot is %d", bcmd->sync_slots[i], i, ps->max_executed_slot_); verify(0); } Log_info("NoOps sync slot is %d for partition %d", bcmd->sync_slots[i], i); for(int j = bcmd->sync_slots[i]; j <= ps->max_committed_slot_; j++){ auto instance = ps->GetInstance(j); if(instance->committed_cmd_) continue; instance->committed_cmd_ = make_shared<LogEntry>(); instance->is_no_op = true; instance->max_ballot_accepted_ = cur_b; } for (slotid_t id = ps->max_executed_slot_ + 1; id <= ps->max_committed_slot_; id++) { auto next_instance = ps->GetInstance(id); if (next_instance->committed_cmd_ && !next_instance->is_no_op) { ps->app_next_(*next_instance->committed_cmd_); ps->max_executed_slot_++; ps->n_commit_++; } else { verify(0); } } ps->max_committed_slot_ = ps->max_committed_slot_; ps->max_executed_slot_ = ps->max_committed_slot_; ps->cur_open_slot_ = ps->max_committed_slot_+1; ps->mtx_.unlock(); } *valid = 1; cb(); } } // namespace janus
32.616783
138
0.600274
[ "object", "vector" ]
a6fe29736311effdb29ccf6e7ec1099056e39a42
2,367
cpp
C++
unstable/subsample.cpp
docpaa/mumdex
571f2d03a457da2f51d525ac038aef455e3467c1
[ "Zlib", "MIT" ]
5
2018-02-07T15:58:30.000Z
2019-11-23T00:58:54.000Z
unstable/subsample.cpp
docpaa/mumdex
571f2d03a457da2f51d525ac038aef455e3467c1
[ "Zlib", "MIT" ]
null
null
null
unstable/subsample.cpp
docpaa/mumdex
571f2d03a457da2f51d525ac038aef455e3467c1
[ "Zlib", "MIT" ]
1
2019-11-20T15:47:54.000Z
2019-11-20T15:47:54.000Z
// // subsample // // subsample input // // Copyright 2014 Peter Andrews @ CSHL // #include <algorithm> #include <exception> #include <iostream> #include <fstream> #include <functional> #include <random> #include <string> #include <vector> #include "error.h" using std::bind; using std::cout; using std::cerr; using std::endl; using std::exception; using std::ifstream; using std::mt19937_64; using std::shuffle; using std::string; using std::vector; using std::uniform_int_distribution; using std::uniform_real_distribution; using paa::Error; int main(int argc, char* argv[], char * []) try { if (--argc < 2) throw Error("usage: subsample N input_file ..."); vector<string> reservoir; const uint64_t N = atol((++argv)[0]); reservoir.reserve(N); uint64_t n = 0; std::random_device rd; auto mersenne = mt19937_64(rd()); auto realGen = bind(uniform_real_distribution<double>(0.0, 1.0), std::ref(mersenne)); auto intGen = bind(uniform_int_distribution<uint64_t>(0, N - 1), std::ref(mersenne)); while (--argc) { const string input_file_name((++argv)[0]); ifstream input_file(input_file_name.c_str()); if (!input_file) throw Error("Could not open file for input:") << input_file_name; string line; while (getline(input_file, line) && input_file) { ++n; if (N == 0) { cout << line << endl; } else { if (reservoir.size() < N) { reservoir.push_back(line); } else { if (realGen() < 1.0 * N / n) { reservoir[intGen()] = line; } } if (n == N) shuffle(reservoir.begin(), reservoir.end(), mersenne); } } } if (N == 0) { cerr << "Output all input since N was 0" << endl; return 0; } if (n < N) { shuffle(reservoir.begin(), reservoir.end(), mersenne); cerr << "Not enough lines in subsample: only " << n << " of " << N << endl; } for (const string & line : reservoir) { cout << line << endl; } // cerr << "done" << endl; return 0; } catch (Error & e) { cerr << "paa::Error:" << endl; cerr << e.what() << endl; return 1; } catch (exception & e) { cerr << "std::exception" << endl; cerr << e.what() << endl; return 1; } catch (...) { cerr << "unknown exception was caught" << endl; return 1; }
23.909091
74
0.579637
[ "vector" ]
470149d51c29ae96b263f6eddfecfe4e13bd27ee
1,810
cpp
C++
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/VI.5/TestBSPDE1.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/VI.5/TestBSPDE1.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
Part F Finite Difference Methods/Exercise F Finite Difference Methods/Level9/Level9Code/Level9Code/VI.5/TestBSPDE1.cpp
bondxue/Option-Pricing-Model
5f22df0ff31e90fd536eb216c5af19c697fb87b2
[ "MIT" ]
null
null
null
// TestBSPDE1.cpp // // Testing 1 factor BS model. // // (C) Datasim Education BV 2005-2011 // #include "FdmDirector.hpp" #include <iostream> #include <string> using namespace std; #include "UtilitiesDJD/ExcelDriver/ExcelDriverLite.hpp" namespace BS // Black Scholes { //// Batch 1 data //double sig = 0.3; //double K = 65.0; //double T = 0.25; //double r = 0.08; //double D = 0.0; // aka q //// Batch 2 data //double T = 1.0; //double K = 100.0; //double sig = 0.20; //double r = 0.0; //double D = 0.0; // aka q //// Batch 3 data //double T = 1.0; //double K = 10.0; //double sig = 0.50; //double r = 0.12; //double D = 0.0; // aka q // Batch 4 data double T = 30.0; double K = 100.0; double sig = 0.30; double r = 0.08; double D = 0.0; // aka q double mySigma (double x, double t) { double sigmaS = sig*sig; return 0.5 * sigmaS * x * x; } double myMu (double x, double t) { return (r - D) * x; } double myB (double x, double t) { return -r; } double myF (double x, double t) { return 0.0; } double myBCL (double t) { // Put return K *exp(-r * t); } double myBCR (double t) { // Put return 0.0; // P } double myIC (double x) { // Payoff // Put return max(K - x, 0.0); } } int main() { using namespace ParabolicIBVP; // Assignment of functions sigma = BS::mySigma; mu = BS::myMu; b = BS::myB; f = BS::myF; BCL = BS::myBCL; BCR = BS::myBCR; IC = BS::myIC; int J = static_cast<int>(1*BS::K); int N = 50000-1; // k = O(h^2) !!!!!!!!! double Smax = 5*BS::K; // Magix cout << "start FDM\n"; FDMDirector fdir(Smax, BS::T, J, N); fdir.doit(); cout << "Finished\n"; // Have you Excel installed (ExcelImports.cpp) printOneExcel(fdir.xarr, fdir.current(), string("Value")); return 0; }
14.596774
76
0.568508
[ "model" ]
47017e67f3ca8c54d989bb8a37a82a463fe18db3
9,516
cpp
C++
src/Hierarchy.cpp
choltz95/c-pcb-annealer
ca962f5fe5a6e398e4f8ef8d1142e619817beb1b
[ "BSD-3-Clause" ]
12
2019-11-01T00:57:42.000Z
2022-02-27T05:38:17.000Z
src/Hierarchy.cpp
choltz95/c-pcb-annealer
ca962f5fe5a6e398e4f8ef8d1142e619817beb1b
[ "BSD-3-Clause" ]
1
2019-12-23T17:22:24.000Z
2019-12-23T17:22:24.000Z
src/Hierarchy.cpp
choltz95/c-pcb-annealer
ca962f5fe5a6e398e4f8ef8d1142e619817beb1b
[ "BSD-3-Clause" ]
7
2020-01-30T20:44:11.000Z
2021-12-21T13:17:38.000Z
#include "Hierarchy.hpp" #include <boost/geometry/geometries/adapted/c_array.hpp> #include <boost/geometry/geometries/adapted/boost_tuple.hpp> BOOST_GEOMETRY_REGISTER_BOOST_TUPLE_CS(cs::cartesian) BOOST_GEOMETRY_REGISTER_C_ARRAY_CS(cs::cartesian) void Hierarchy::init_hierarchy(int nl, vector <int> nm) { num_levels = nl; num_modules_per_layer = nm; for (int l=0; l<=num_levels; ++l) { Level tmp; tmp.level = l; levels.push_back(tmp); } root = create_hierarchy(0,0,true); root->root = true; } Module* Hierarchy::create_hierarchy(int id, int lev, bool r) { Module *m = new Module; m->init_module(id, lev, r); levels[lev].modules.push_back(m); if (num_levels <= lev) { m->leaf = true; return m; } int num_children = num_modules_per_layer[lev]; for (int i =1; i<=num_children; ++i) { Module* mc; mc = create_hierarchy(i, lev+1, false); mc->parent = m; if(mc) { m->add_child(mc); } } return m; } void Hierarchy::print_param(int i) { int ii = 0; for (auto &lvl : levels) { if (i >= 0 && i == ii) { for (auto &m : lvl.modules) { cout << m->idx << " " << m->width << " " << m->height << endl; } } ii++ ; } } void Hierarchy::insert_cell(int cell_id, vector < int> cluster_id_vec, Module *m, int level) { if(num_levels <= level) { return; } if(cluster_id_vec.size() < 1) { // macro cell - just insert into every level vector < Module * > macroModulePath; for(int l=0; l<=num_levels; ++l) { Module *tmp = new Module; tmp->init_module(levels[l].modules.size() + 1, l, false); tmp->macroModule = true; tmp->fixed = 1; tmp->terminal = 1; tmp->insert_cell(cell_id); levels[l].modules.push_back(tmp); macroModulePath.push_back(tmp); } for(int l=1; l<num_levels; ++l) { Module *tmp = macroModulePath[l-1]; if (l == 1) { root->children.push_back(tmp); tmp->parent = root; } else { tmp->parent = macroModulePath[l-2]; } tmp->children.push_back(macroModulePath[l]); } macroModulePath[num_levels-1]->parent = macroModulePath[num_levels-2]; macroModulePath[num_levels-1]->children.push_back(macroModulePath[num_levels]); macroModulePath[num_levels]->parent = macroModulePath[num_levels-1]; macroModulePath[num_levels]->leaf = true; } else { int cluster_id = cluster_id_vec[level]; m->children[cluster_id-1]->insert_cell(cell_id); insert_cell(cell_id, cluster_id_vec, m->children[cluster_id-1], level+1); } } Module *Hierarchy::get_leaf_module_from_id(int idx, Module *m) { if(m->leaf) { return m; } else { for (auto &child : m->children) { if(std::find(child->cells.begin(), child->cells.end(), idx) != child->cells.end()) { return get_leaf_module_from_id(idx, child); } } } } Module *Hierarchy::get_level_module_from_id(int idx, int level, Module *m) { if(m->level == level) { return m; } else { for (auto &child : m->children) { if(std::find(child->cells.begin(), child->cells.end(), idx) != child->cells.end()) { return get_level_module_from_id(idx,level, child); } } } } /** for each level in the hierarchy, instantiate a netlist for that level: associated nets for each module (list of net ids) netlist-module mapping id -> list of modules */ void Hierarchy::set_netlist_hierarchy(map<int, vector<pPin> > netToCell) { int netidx = 1; for (auto &net : netToCell) { int netid = net.first; vector<pPin> pvec = net.second; //pvec_i.idx -> cell id vector<Module *> ms; // convert vector of pins to vector of clusters for that net add to netToModule in leaf-level for (auto &pin : pvec) { int cell_id = pin.idx; Module *m = get_leaf_module_from_id(cell_id, root); if(!m->leaf || !(std::find(m->cells.begin(), m->cells.end(), cell_id) != m->cells.end())) { cout << "[ERR] set_netlist_hierarchy: cell not found in leaf nodes: " << cell_id << " " << m->idx << " " << m->leaf << endl; return; } if(!(std::find(ms.begin(), ms.end(), m) != ms.end())) { // uniqueify module-level netlist m->setNetList(netidx); ms.push_back(m); } } levels.back().netToModule.insert(pair < int, vector < Module * > > (netidx, ms)); netidx ++; } // now need to propagate up the hierarchy propagate_netlist(levels.back().level); } void Hierarchy::propagate_netlist(int lev) { if (lev <= 0) { return; } map<int, vector< Module * > >netToModules = levels[lev].netToModule; int netidx = 1; for (auto &net : netToModules) { int netid = net.first; vector<Module *> pvec = net.second; //pvec_i.idx -> cell id vector<Module *> ms; // convert vector of pins to vector of clusters for that net add to netToModule in leaf-level for (auto &module : pvec) { Module *m = module->parent; if(!(std::find(ms.begin(), ms.end(), m) != ms.end())) { // uniqueify module-level netlist m->setNetList(netidx); // crash here, module is root for some reason so parent m is garbage ms.push_back(m); } } if (ms.size() > 0 && lev > 0) { levels[lev-1].netToModule.insert(pair < int, vector < Module* > > (netidx, ms)); } netidx ++; } propagate_netlist(lev - 1); } void Hierarchy::set_module_geometries(vector < Node > nodeId) { // should fix to be bottom up // first get leaf params int dim = 0; double area = 0.0; double xcenter = 0.0; double ycenter = 0.0; for (auto &m : levels.back().modules) { double xmin = 99999999999999.0; double ymin = 99999999999999.0; double xmax = 0.0; double ymax = 0.0; double area = 0.0; double xcenter = 0.0; double ycenter = 0.0; for (auto &cellid : m->cells) { double cellx = nodeId[cellid].xCoordinate; double celly = nodeId[cellid].yCoordinate; double cellw = nodeId[cellid].width; double cellh = nodeId[cellid].height; xmin = min(xmin, cellx); ymin = min(ymin, celly); xmax = max(xmax, cellx + cellw); ymax = max(ymax, celly + cellh); area += cellw * cellh; xcenter += cellx; ycenter += celly; } xcenter = xcenter / m->cells.size(); ycenter = ycenter / m->cells.size(); //cout << m->idx << " " << xmax - xmin<< " " << ymax - ymin << endl; //m->setParameterNodes(xmax - xmin, ymax - ymin); //m->setParameterPl(xmin, ymin); dim = ceil(sqrt(area)); m->setParameterNodes(dim, dim); m->setParameterPl(xcenter, ycenter); } propagate_geometries(num_levels-1); } void Hierarchy::propagate_geometries(int lev) { if (lev <= 0) { return; } int dim = 0; vector <Module *> modules = levels[lev].modules; for (auto &module : modules) { double xmin = 99999999999999.0; double ymin = 99999999999999.0; double xmax = 0.0; double ymax = 0.0; double area = 0.0; double xcenter = 0.0; double ycenter = 0.0; for (auto &m : module->children) { double cellx = m->xCoordinate; double celly = m->yCoordinate; double cellw = m->width; double cellh = m->height; xmin = min(xmin, cellx); ymin = min(ymin, celly); xmax = max(xmax, cellx + cellw); ymax = max(ymax, celly + cellh); area += cellw * cellh; xcenter += cellx; ycenter += celly; } xcenter = xcenter / module->children.size(); ycenter = ycenter / module->children.size(); //module->setParameterNodes(xmax - xmin, ymax - ymin); //module->setParameterPl(xmin, ymin); dim = ceil(sqrt(area)); module->setParameterNodes(dim, dim); module->setParameterPl(xcenter, ycenter); } propagate_geometries(lev - 1); } vector < Node > Hierarchy::update_cell_positions_at_level(vector < Node > nodeId, int level) { for (auto &node : nodeId) { int cell_id = node.idx; Module *m = get_level_module_from_id(cell_id, level, root); if(!(std::find(m->cells.begin(), m->cells.end(), cell_id) != m->cells.end())) { cout << "[ERR] update_cell_positions_at_level: cell not found in leaf nodes: " << cell_id << " " << m->idx << " " << m->leaf << endl; return nodeId; } double mx = m->xCoordinate; double my = m->yCoordinate; double cx = node.initialX; double cy = node.initialY; double mx_orig = m->initialX; double my_orig = m->initialY; double trans_x = mx - mx_orig; double trans_y = my - my_orig; double new_cell_x = cx + trans_x; double new_cell_y = cy + trans_y; node.setPos(new_cell_x, new_cell_y); } return nodeId; } vector < Node > Hierarchy::update_cell_positions(vector < Node > nodeId) { for (auto &node : nodeId) { int cell_id = node.idx; Module *m = get_leaf_module_from_id(cell_id, root); if(!m->leaf || !(std::find(m->cells.begin(), m->cells.end(), cell_id) != m->cells.end())) { cout << "[ERR] update_cell_positions: cell not found in leaf nodes: " << cell_id << " " << m->idx << " " << m->leaf << endl; return nodeId; } double mx = m->xCoordinate; double my = m->yCoordinate; double cx = node.initialX; double cy = node.initialY; double mx_orig = m->initialX; double my_orig = m->initialY; double trans_x = mx - mx_orig; double trans_y = my - my_orig; double new_cell_x = cx + trans_x; double new_cell_y = cy + trans_y; node.setPos(new_cell_x, new_cell_y); } return nodeId; }
29.7375
139
0.611917
[ "geometry", "vector" ]
47087422ec5742edba9839d0313ad37c302851d0
24,016
cpp
C++
src/mbgl/renderer/symbol_bucket.cpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
null
null
null
src/mbgl/renderer/symbol_bucket.cpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
null
null
null
src/mbgl/renderer/symbol_bucket.cpp
donpark/mapbox-gl-native
efa7dad89c61fe0fcc01a492e8db8e36b8f27f53
[ "BSD-2-Clause" ]
null
null
null
#include <mbgl/renderer/symbol_bucket.hpp> #include <mbgl/map/geometry_tile.hpp> #include <mbgl/style/style_layout.hpp> #include <mbgl/annotation/sprite_image.hpp> #include <mbgl/geometry/text_buffer.hpp> #include <mbgl/geometry/icon_buffer.hpp> #include <mbgl/geometry/glyph_atlas.hpp> #include <mbgl/geometry/sprite_atlas.hpp> #include <mbgl/geometry/anchor.hpp> #include <mbgl/text/get_anchors.hpp> #include <mbgl/renderer/painter.hpp> #include <mbgl/text/glyph_store.hpp> #include <mbgl/text/font_stack.hpp> #include <mbgl/platform/log.hpp> #include <mbgl/text/collision_tile.hpp> #include <mbgl/shader/sdf_shader.hpp> #include <mbgl/shader/icon_shader.hpp> #include <mbgl/shader/box_shader.hpp> #include <mbgl/map/sprite.hpp> #include <mbgl/util/utf.hpp> #include <mbgl/util/token.hpp> #include <mbgl/util/math.hpp> #include <mbgl/util/merge_lines.hpp> #include <mbgl/util/clip_lines.hpp> #include <mbgl/util/std.hpp> namespace mbgl { SymbolInstance::SymbolInstance(Anchor &anchor, const std::vector<Coordinate> &line, const Shaping &shapedText, const PositionedIcon &shapedIcon, const StyleLayoutSymbol &layout, const bool addToBuffers, const float textBoxScale, const float textPadding, const float textAlongLine, const float iconBoxScale, const float iconPadding, const float iconAlongLine, const GlyphPositions &face) : x(anchor.x), y(anchor.y), hasText(shapedText), hasIcon(shapedIcon), // Create the quads used for rendering the glyphs. glyphQuads(addToBuffers && shapedText ? getGlyphQuads(anchor, shapedText, textBoxScale, line, layout, textAlongLine, face) : SymbolQuads()), // Create the quad used for rendering the icon. iconQuads(addToBuffers && shapedIcon ? getIconQuads(anchor, shapedIcon, line, layout, iconAlongLine) : SymbolQuads()), // Create the collision features that will be used to check whether this symbol instance can be placed textCollisionFeature(line, anchor, shapedText, textBoxScale, textPadding, textAlongLine), iconCollisionFeature(line, anchor, shapedIcon, iconBoxScale, iconPadding, iconAlongLine) {}; SymbolBucket::SymbolBucket(CollisionTile &collision_, float overscaling_) : collision(collision_), overscaling(overscaling_) { } SymbolBucket::~SymbolBucket() { // Do not remove. header file only contains forward definitions to unique pointers. } void SymbolBucket::upload() { if (hasTextData()) { renderData->text.vertices.upload(); renderData->text.triangles.upload(); } if (hasIconData()) { renderData->icon.vertices.upload(); renderData->icon.triangles.upload(); } uploaded = true; } void SymbolBucket::render(Painter& painter, const StyleLayer& layer_desc, const TileID& id, const mat4& matrix) { painter.renderSymbol(*this, layer_desc, id, matrix); } bool SymbolBucket::hasData() const { return hasTextData() || hasIconData() || symbolInstances.size(); } bool SymbolBucket::hasTextData() const { return renderData && !renderData->text.groups.empty(); } bool SymbolBucket::hasIconData() const { return renderData && !renderData->icon.groups.empty(); } bool SymbolBucket::hasCollisionBoxData() const { return renderData && !renderData->collisionBox.groups.empty(); } bool SymbolBucket::needsDependencies(const GeometryTileLayer& layer, const FilterExpression& filter, GlyphStore& glyphStore, Sprite& sprite) { const bool has_text = !layout.text.field.empty() && !layout.text.font.empty(); const bool has_icon = !layout.icon.image.empty(); if (!has_text && !has_icon) { return false; } // Determine and load glyph ranges std::set<GlyphRange> ranges; for (std::size_t i = 0; i < layer.featureCount(); i++) { auto feature = layer.getFeature(i); GeometryTileFeatureExtractor extractor(*feature); if (!evaluate(filter, extractor)) continue; SymbolFeature ft; auto getValue = [&feature](const std::string& key) -> std::string { auto value = feature->getValue(key); return value ? toString(*value) : std::string(); }; if (has_text) { std::string u8string = util::replaceTokens(layout.text.field, getValue); if (layout.text.transform == TextTransformType::Uppercase) { u8string = platform::uppercase(u8string); } else if (layout.text.transform == TextTransformType::Lowercase) { u8string = platform::lowercase(u8string); } ft.label = util::utf8_to_utf32::convert(u8string); if (ft.label.size()) { // Loop through all characters of this text and collect unique codepoints. for (char32_t chr : ft.label) { ranges.insert(getGlyphRange(chr)); } } } if (has_icon) { ft.sprite = util::replaceTokens(layout.icon.image, getValue); } if (ft.label.length() || ft.sprite.length()) { auto &multiline = ft.geometry; GeometryCollection geometryCollection = feature->getGeometries(); for (auto& line : geometryCollection) { multiline.emplace_back(); for (auto& point : line) { multiline.back().emplace_back(point.x, point.y); } } features.push_back(std::move(ft)); } } if (layout.placement == PlacementType::Line) { util::mergeLines(features); } if (glyphStore.requestGlyphRangesIfNeeded(layout.text.font, ranges)) { return true; } if (!sprite.isLoaded()) { return true; } return false; } void SymbolBucket::addFeatures(uintptr_t tileUID, SpriteAtlas& spriteAtlas, GlyphAtlas& glyphAtlas, GlyphStore& glyphStore) { float horizontalAlign = 0.5; float verticalAlign = 0.5; switch (layout.text.anchor) { case TextAnchorType::Top: case TextAnchorType::Bottom: case TextAnchorType::Center: break; case TextAnchorType::Right: case TextAnchorType::TopRight: case TextAnchorType::BottomRight: horizontalAlign = 1; break; case TextAnchorType::Left: case TextAnchorType::TopLeft: case TextAnchorType::BottomLeft: horizontalAlign = 0; break; } switch (layout.text.anchor) { case TextAnchorType::Left: case TextAnchorType::Right: case TextAnchorType::Center: break; case TextAnchorType::Bottom: case TextAnchorType::BottomLeft: case TextAnchorType::BottomRight: verticalAlign = 1; break; case TextAnchorType::Top: case TextAnchorType::TopLeft: case TextAnchorType::TopRight: verticalAlign = 0; break; } const float justify = layout.text.justify == TextJustifyType::Right ? 1 : layout.text.justify == TextJustifyType::Left ? 0 : 0.5; auto fontStack = glyphStore.getFontStack(layout.text.font); for (const auto& feature : features) { if (!feature.geometry.size()) continue; Shaping shapedText; PositionedIcon shapedIcon; GlyphPositions face; // if feature has text, shape the text if (feature.label.length()) { shapedText = fontStack->getShaping( /* string */ feature.label, /* maxWidth: ems */ layout.placement != PlacementType::Line ? layout.text.max_width * 24 : 0, /* lineHeight: ems */ layout.text.line_height * 24, /* horizontalAlign */ horizontalAlign, /* verticalAlign */ verticalAlign, /* justify */ justify, /* spacing: ems */ layout.text.letter_spacing * 24, /* translate */ vec2<float>(layout.text.offset[0], layout.text.offset[1])); // Add the glyphs we need for this label to the glyph atlas. if (shapedText) { glyphAtlas.addGlyphs(tileUID, feature.label, layout.text.font, **fontStack, face); } } // if feature has icon, get sprite atlas position if (feature.sprite.length()) { auto image = spriteAtlas.getImage(feature.sprite, false); if (image.pos.hasArea() && image.texture) { shapedIcon = shapeIcon(image.pos, layout); assert(image.texture); if (image.texture->sdf) { sdfIcons = true; } } } // if either shapedText or icon position is present, add the feature if (shapedText || shapedIcon) { addFeature(feature.geometry, shapedText, shapedIcon, face); } } features.clear(); placeFeatures(true); } void SymbolBucket::addFeature(const std::vector<std::vector<Coordinate>> &lines, const Shaping &shapedText, const PositionedIcon &shapedIcon, const GlyphPositions &face) { const float minScale = 0.5f; const float glyphSize = 24.0f; const float fontScale = layout.text.max_size / glyphSize; const float textBoxScale = collision.tilePixelRatio * fontScale; const float iconBoxScale = collision.tilePixelRatio * layout.icon.max_size; const float symbolSpacing = collision.tilePixelRatio * layout.min_distance; const bool avoidEdges = layout.avoid_edges && layout.placement != PlacementType::Line; const float textPadding = layout.text.padding * collision.tilePixelRatio; const float iconPadding = layout.icon.padding * collision.tilePixelRatio; const float textMaxAngle = layout.text.max_angle * M_PI / 180; const bool textAlongLine = layout.text.rotation_alignment == RotationAlignmentType::Map && layout.placement == PlacementType::Line; const bool iconAlongLine = layout.icon.rotation_alignment == RotationAlignmentType::Map && layout.placement == PlacementType::Line; const bool mayOverlap = layout.text.allow_overlap || layout.icon.allow_overlap || layout.text.ignore_placement || layout.icon.ignore_placement; auto& clippedLines = layout.placement == PlacementType::Line ? util::clipLines(lines, 0, 0, 4096, 4096) : lines; for (const auto& line : clippedLines) { if (!line.size()) continue; // Calculate the anchor points around which you want to place labels Anchors anchors = layout.placement == PlacementType::Line ? getAnchors(line, symbolSpacing, textMaxAngle, shapedText.left, shapedText.right, glyphSize, textBoxScale, overscaling) : Anchors({ Anchor(float(line[0].x), float(line[0].y), 0, minScale) }); // For each potential label, create the placement features used to check for collisions, and the quads use for rendering. for (Anchor &anchor : anchors) { const bool inside = !(anchor.x < 0 || anchor.x > 4096 || anchor.y < 0 || anchor.y > 4096); if (avoidEdges && !inside) continue; // Normally symbol layers are drawn across tile boundaries. Only symbols // with their anchors within the tile boundaries are added to the buffers // to prevent symbols from being drawn twice. // // Symbols in layers with overlap are sorted in the y direction so that // symbols lower on the canvas are drawn on top of symbols near the top. // To preserve this order across tile boundaries these symbols can't // be drawn across tile boundaries. Instead they need to be included in // the buffers for both tiles and clipped to tile boundaries at draw time. // // TODO remove the `&& false` when is #1673 implemented const bool addToBuffers = inside || (mayOverlap && false); symbolInstances.emplace_back(anchor, line, shapedText, shapedIcon, layout, addToBuffers, textBoxScale, textPadding, textAlongLine, iconBoxScale, iconPadding, iconAlongLine, face); } } } void SymbolBucket::placeFeatures() { placeFeatures(false); } void SymbolBucket::placeFeatures(bool swapImmediately) { renderDataInProgress = std::make_unique<SymbolRenderData>(); // Calculate which labels can be shown and when they can be shown and // create the bufers used for rendering. const bool textAlongLine = layout.text.rotation_alignment == RotationAlignmentType::Map && layout.placement == PlacementType::Line; const bool iconAlongLine = layout.icon.rotation_alignment == RotationAlignmentType::Map && layout.placement == PlacementType::Line; const bool mayOverlap = layout.text.allow_overlap || layout.icon.allow_overlap || layout.text.ignore_placement || layout.icon.ignore_placement; // Sort symbols by their y position on the canvas so that they lower symbols // are drawn on top of higher symbols. // Don't sort symbols that won't overlap because it isn't necessary and // because it causes more labels to pop in and out when rotating. if (mayOverlap) { float sin = std::sin(collision.angle); float cos = std::cos(collision.angle); std::sort(symbolInstances.begin(), symbolInstances.end(), [sin, cos](SymbolInstance &a, SymbolInstance &b) { const float aRotated = sin * a.x + cos * a.y; const float bRotated = sin * b.x + cos * b.y; return aRotated < bRotated; }); } for (SymbolInstance &symbolInstance : symbolInstances) { const bool hasText = symbolInstance.hasText; const bool hasIcon = symbolInstance.hasIcon; const bool iconWithoutText = layout.text.optional || !hasText; const bool textWithoutIcon = layout.icon.optional || !hasIcon; // Calculate the scales at which the text and icon can be placed without collision. float glyphScale = hasText && !layout.text.allow_overlap ? collision.placeFeature(symbolInstance.textCollisionFeature) : collision.minScale; float iconScale = hasIcon && !layout.icon.allow_overlap ? collision.placeFeature(symbolInstance.iconCollisionFeature) : collision.minScale; // Combine the scales for icons and text. if (!iconWithoutText && !textWithoutIcon) { iconScale = glyphScale = util::max(iconScale, glyphScale); } else if (!textWithoutIcon && glyphScale) { glyphScale = util::max(iconScale, glyphScale); } else if (!iconWithoutText && iconScale) { iconScale = util::max(iconScale, glyphScale); } // Insert final placement into collision tree and add glyphs/icons to buffers if (hasText) { if (!layout.text.ignore_placement) { collision.insertFeature(symbolInstance.textCollisionFeature, glyphScale); } if (glyphScale < collision.maxScale) { addSymbols<SymbolRenderData::TextBuffer, TextElementGroup>(renderDataInProgress->text, symbolInstance.glyphQuads, glyphScale, layout.text.keep_upright, textAlongLine); } } if (hasIcon) { if (!layout.icon.ignore_placement) { collision.insertFeature(symbolInstance.iconCollisionFeature, iconScale); } if (iconScale < collision.maxScale) { addSymbols<SymbolRenderData::IconBuffer, IconElementGroup>(renderDataInProgress->icon, symbolInstance.iconQuads, iconScale, layout.icon.keep_upright, iconAlongLine); } } } if (collision.getDebug()) addToDebugBuffers(); if (swapImmediately) swapRenderData(); } template <typename Buffer, typename GroupType> void SymbolBucket::addSymbols(Buffer &buffer, const SymbolQuads &symbols, float scale, const bool keepUpright, const bool alongLine) { const float zoom = collision.zoom; const float placementZoom = std::fmax(std::log(scale) / std::log(2) + zoom, 0); for (const auto& symbol : symbols) { const auto &tl = symbol.tl; const auto &tr = symbol.tr; const auto &bl = symbol.bl; const auto &br = symbol.br; const auto &tex = symbol.tex; float minZoom = util::max(static_cast<float>(zoom + log(symbol.minScale) / log(2)), placementZoom); float maxZoom = util::min(static_cast<float>(zoom + log(symbol.maxScale) / log(2)), 25.0f); const auto &glyphAnchor = symbol.anchor; // drop upside down versions of glyphs const float a = std::fmod(symbol.angle + collision.angle + M_PI, M_PI * 2); if (keepUpright && alongLine && (a <= M_PI / 2 || a > M_PI * 3 / 2)) continue; if (maxZoom <= minZoom) continue; // Lower min zoom so that while fading out the label // it can be shown outside of collision-free zoom levels if (minZoom == placementZoom) { minZoom = 0; } const int glyph_vertex_length = 4; if (!buffer.groups.size() || (buffer.groups.back()->vertex_length + glyph_vertex_length > 65535)) { // Move to a new group because the old one can't hold the geometry. buffer.groups.emplace_back(std::make_unique<GroupType>()); } // We're generating triangle fans, so we always start with the first // coordinate in this polygon. assert(buffer.groups.back()); auto &triangleGroup = *buffer.groups.back(); uint32_t triangleIndex = triangleGroup.vertex_length; // coordinates (2 triangles) buffer.vertices.add(glyphAnchor.x, glyphAnchor.y, tl.x, tl.y, tex.x, tex.y, minZoom, maxZoom, placementZoom); buffer.vertices.add(glyphAnchor.x, glyphAnchor.y, tr.x, tr.y, tex.x + tex.w, tex.y, minZoom, maxZoom, placementZoom); buffer.vertices.add(glyphAnchor.x, glyphAnchor.y, bl.x, bl.y, tex.x, tex.y + tex.h, minZoom, maxZoom, placementZoom); buffer.vertices.add(glyphAnchor.x, glyphAnchor.y, br.x, br.y, tex.x + tex.w, tex.y + tex.h, minZoom, maxZoom, placementZoom); // add the two triangles, referencing the four coordinates we just inserted. buffer.triangles.add(triangleIndex + 0, triangleIndex + 1, triangleIndex + 2); buffer.triangles.add(triangleIndex + 1, triangleIndex + 2, triangleIndex + 3); triangleGroup.vertex_length += glyph_vertex_length; triangleGroup.elements_length += 2; } } void SymbolBucket::addToDebugBuffers() { const float yStretch = 1.0f; const float angle = collision.angle; const float zoom = collision.zoom; float angle_sin = std::sin(-angle); float angle_cos = std::cos(-angle); std::array<float, 4> matrix = {{angle_cos, -angle_sin, angle_sin, angle_cos}}; for (const SymbolInstance &symbolInstance : symbolInstances) { for (int i = 0; i < 2; i++) { auto& feature = i == 0 ? symbolInstance.textCollisionFeature : symbolInstance.iconCollisionFeature; for (const CollisionBox &box : feature.boxes) { auto& anchor = box.anchor; vec2<float> tl{box.x1, box.y1 * yStretch}; vec2<float> tr{box.x2, box.y1 * yStretch}; vec2<float> bl{box.x1, box.y2 * yStretch}; vec2<float> br{box.x2, box.y2 * yStretch}; tl = tl.matMul(matrix); tr = tr.matMul(matrix); bl = bl.matMul(matrix); br = br.matMul(matrix); const float maxZoom = util::max(0.0f, util::min(25.0f, static_cast<float>(zoom + log(box.maxScale) / log(2)))); const float placementZoom= util::max(0.0f, util::min(25.0f, static_cast<float>(zoom + log(box.placementScale) / log(2)))); auto& collisionBox = renderDataInProgress->collisionBox; if (!collisionBox.groups.size()) { // Move to a new group because the old one can't hold the geometry. collisionBox.groups.emplace_back(std::make_unique<CollisionBoxElementGroup>()); } collisionBox.vertices.add(anchor.x, anchor.y, tl.x, tl.y, maxZoom, placementZoom); collisionBox.vertices.add(anchor.x, anchor.y, tr.x, tr.y, maxZoom, placementZoom); collisionBox.vertices.add(anchor.x, anchor.y, tr.x, tr.y, maxZoom, placementZoom); collisionBox.vertices.add(anchor.x, anchor.y, br.x, br.y, maxZoom, placementZoom); collisionBox.vertices.add(anchor.x, anchor.y, br.x, br.y, maxZoom, placementZoom); collisionBox.vertices.add(anchor.x, anchor.y, bl.x, bl.y, maxZoom, placementZoom); collisionBox.vertices.add(anchor.x, anchor.y, bl.x, bl.y, maxZoom, placementZoom); collisionBox.vertices.add(anchor.x, anchor.y, tl.x, tl.y, maxZoom, placementZoom); auto &group= *collisionBox.groups.back(); group.vertex_length += 8; } } } } void SymbolBucket::swapRenderData() { renderData = std::move(renderDataInProgress); } void SymbolBucket::drawGlyphs(SDFShader &shader) { char *vertex_index = BUFFER_OFFSET(0); char *elements_index = BUFFER_OFFSET(0); auto& text = renderData->text; for (auto &group : text.groups) { assert(group); group->array[0].bind(shader, text.vertices, text.triangles, vertex_index); MBGL_CHECK_ERROR(glDrawElements(GL_TRIANGLES, group->elements_length * 3, GL_UNSIGNED_SHORT, elements_index)); vertex_index += group->vertex_length * text.vertices.itemSize; elements_index += group->elements_length * text.triangles.itemSize; } } void SymbolBucket::drawIcons(SDFShader &shader) { char *vertex_index = BUFFER_OFFSET(0); char *elements_index = BUFFER_OFFSET(0); auto& icon = renderData->icon; for (auto &group : icon.groups) { assert(group); group->array[0].bind(shader, icon.vertices, icon.triangles, vertex_index); MBGL_CHECK_ERROR(glDrawElements(GL_TRIANGLES, group->elements_length * 3, GL_UNSIGNED_SHORT, elements_index)); vertex_index += group->vertex_length * icon.vertices.itemSize; elements_index += group->elements_length * icon.triangles.itemSize; } } void SymbolBucket::drawIcons(IconShader &shader) { char *vertex_index = BUFFER_OFFSET(0); char *elements_index = BUFFER_OFFSET(0); auto& icon = renderData->icon; for (auto &group : icon.groups) { assert(group); group->array[1].bind(shader, icon.vertices, icon.triangles, vertex_index); MBGL_CHECK_ERROR(glDrawElements(GL_TRIANGLES, group->elements_length * 3, GL_UNSIGNED_SHORT, elements_index)); vertex_index += group->vertex_length * icon.vertices.itemSize; elements_index += group->elements_length * icon.triangles.itemSize; } } void SymbolBucket::drawCollisionBoxes(CollisionBoxShader &shader) { char *vertex_index = BUFFER_OFFSET(0); auto& collisionBox = renderData->collisionBox; for (auto &group : collisionBox.groups) { group->array[0].bind(shader, collisionBox.vertices, vertex_index); MBGL_CHECK_ERROR(glDrawArrays(GL_LINES, 0, group->vertex_length)); } } }
40.363025
138
0.630247
[ "geometry", "render", "shape", "vector", "transform" ]
4713c0badb69d7b40c0099e63607f0e3c9fa31be
9,940
cpp
C++
B2G/gecko/dom/src/events/nsJSEventListener.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/dom/src/events/nsJSEventListener.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/dom/src/events/nsJSEventListener.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsJSEventListener.h" #include "nsJSUtils.h" #include "nsString.h" #include "nsIServiceManager.h" #include "nsIScriptSecurityManager.h" #include "nsIScriptContext.h" #include "nsIScriptGlobalObject.h" #include "nsIScriptRuntime.h" #include "nsIXPConnect.h" #include "nsGUIEvent.h" #include "nsContentUtils.h" #include "nsDOMScriptObjectHolder.h" #include "nsIMutableArray.h" #include "nsVariant.h" #include "nsIDOMBeforeUnloadEvent.h" #include "nsGkAtoms.h" #include "nsIDOMEventTarget.h" #include "nsIJSContextStack.h" #include "xpcpublic.h" #include "nsJSEnvironment.h" #include "nsDOMJSUtils.h" #ifdef DEBUG #include "nspr.h" // PR_fprintf class EventListenerCounter { public: ~EventListenerCounter() { } }; static EventListenerCounter sEventListenerCounter; #endif /* * nsJSEventListener implementation */ nsJSEventListener::nsJSEventListener(nsIScriptContext *aContext, JSObject* aScopeObject, nsISupports *aTarget, nsIAtom* aType, JSObject *aHandler) : nsIJSEventListener(aContext, aScopeObject, aTarget, aHandler), mEventName(aType) { // aScopeObject is the inner window's JS object, which we need to lock // until we are done with it. NS_ASSERTION(aScopeObject && aContext, "EventListener with no context or scope?"); NS_HOLD_JS_OBJECTS(this, nsJSEventListener); } nsJSEventListener::~nsJSEventListener() { if (mContext) { mScopeObject = nullptr; mHandler = nullptr; NS_DROP_JS_OBJECTS(this, nsJSEventListener); } } NS_IMPL_CYCLE_COLLECTION_CLASS(nsJSEventListener) NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(nsJSEventListener) if (tmp->mContext) { tmp->mScopeObject = nullptr; tmp->mHandler = nullptr; NS_DROP_JS_OBJECTS(tmp, nsJSEventListener); NS_IMPL_CYCLE_COLLECTION_UNLINK_NSCOMPTR(mContext) } NS_IMPL_CYCLE_COLLECTION_UNLINK_END NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INTERNAL(nsJSEventListener) if (NS_UNLIKELY(cb.WantDebugInfo()) && tmp->mEventName) { nsAutoCString name; name.AppendLiteral("nsJSEventListener handlerName="); name.Append( NS_ConvertUTF16toUTF8(nsDependentAtomString(tmp->mEventName)).get()); cb.DescribeRefCountedNode(tmp->mRefCnt.get(), name.get()); } else { NS_IMPL_CYCLE_COLLECTION_DESCRIBE(nsJSEventListener, tmp->mRefCnt.get()) } NS_IMPL_CYCLE_COLLECTION_TRAVERSE_NSCOMPTR(mContext) NS_IMPL_CYCLE_COLLECTION_TRAVERSE_SCRIPT_OBJECTS NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(nsJSEventListener) NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mScopeObject) NS_IMPL_CYCLE_COLLECTION_TRACE_JS_MEMBER_CALLBACK(mHandler) NS_IMPL_CYCLE_COLLECTION_TRACE_END NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_BEGIN(nsJSEventListener) if (tmp->IsBlackForCC()) { return true; } // If we have a target, it is the one which has tmp as onfoo handler. if (tmp->mTarget) { nsXPCOMCycleCollectionParticipant* cp = nullptr; CallQueryInterface(tmp->mTarget, &cp); nsISupports* canonical = nullptr; tmp->mTarget->QueryInterface(NS_GET_IID(nsCycleCollectionISupports), reinterpret_cast<void**>(&canonical)); // Usually CanSkip ends up unmarking the event listeners of mTarget, // so tmp may become black. if (cp && canonical && cp->CanSkip(canonical, true)) { return tmp->IsBlackForCC(); } } NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_END NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_BEGIN(nsJSEventListener) return tmp->IsBlackForCC(); NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_IN_CC_END NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_BEGIN(nsJSEventListener) return tmp->IsBlackForCC(); NS_IMPL_CYCLE_COLLECTION_CAN_SKIP_THIS_END NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(nsJSEventListener) NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener) NS_INTERFACE_MAP_ENTRY(nsIJSEventListener) NS_INTERFACE_MAP_ENTRY(nsISupports) NS_INTERFACE_MAP_END NS_IMPL_CYCLE_COLLECTING_ADDREF(nsJSEventListener) NS_IMPL_CYCLE_COLLECTING_RELEASE(nsJSEventListener) bool nsJSEventListener::IsBlackForCC() { if (mContext && (!mScopeObject || !xpc_IsGrayGCThing(mScopeObject)) && (!mHandler || !xpc_IsGrayGCThing(mHandler))) { nsIScriptGlobalObject* sgo = static_cast<nsJSContext*>(mContext.get())->GetCachedGlobalObject(); return sgo && sgo->IsBlackForCC(); } return false; } nsresult nsJSEventListener::HandleEvent(nsIDOMEvent* aEvent) { nsCOMPtr<nsIDOMEventTarget> target = do_QueryInterface(mTarget); if (!target || !mContext || !mHandler) return NS_ERROR_FAILURE; nsresult rv; nsCOMPtr<nsIMutableArray> iargv; bool handledScriptError = false; if (mEventName == nsGkAtoms::onerror) { NS_ENSURE_TRUE(aEvent, NS_ERROR_UNEXPECTED); nsEvent* event = aEvent->GetInternalNSEvent(); if (event->message == NS_LOAD_ERROR && event->eventStructType == NS_SCRIPT_ERROR_EVENT) { nsScriptErrorEvent *scriptEvent = static_cast<nsScriptErrorEvent*>(event); // Create a temp argv for the error event. iargv = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; // Append the event args. nsCOMPtr<nsIWritableVariant> var(do_CreateInstance(NS_VARIANT_CONTRACTID, &rv)); NS_ENSURE_SUCCESS(rv, rv); rv = var->SetAsWString(scriptEvent->errorMsg); NS_ENSURE_SUCCESS(rv, rv); rv = iargv->AppendElement(var, false); NS_ENSURE_SUCCESS(rv, rv); // filename var = do_CreateInstance(NS_VARIANT_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = var->SetAsWString(scriptEvent->fileName); NS_ENSURE_SUCCESS(rv, rv); rv = iargv->AppendElement(var, false); NS_ENSURE_SUCCESS(rv, rv); // line number var = do_CreateInstance(NS_VARIANT_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, rv); rv = var->SetAsUint32(scriptEvent->lineNr); NS_ENSURE_SUCCESS(rv, rv); rv = iargv->AppendElement(var, false); NS_ENSURE_SUCCESS(rv, rv); handledScriptError = true; } } if (!handledScriptError) { iargv = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv); if (NS_FAILED(rv)) return rv; NS_ENSURE_TRUE(iargv != nullptr, NS_ERROR_OUT_OF_MEMORY); rv = iargv->AppendElement(aEvent, false); NS_ENSURE_SUCCESS(rv, rv); } // mContext is the same context which event listener manager pushes // to JS context stack. #ifdef DEBUG JSContext* cx = nullptr; nsCOMPtr<nsIJSContextStack> stack = do_GetService("@mozilla.org/js/xpc/ContextStack;1"); NS_ASSERTION(stack && NS_SUCCEEDED(stack->Peek(&cx)) && cx && GetScriptContextFromJSContext(cx) == mContext, "JSEventListener has wrong script context?"); #endif nsCOMPtr<nsIVariant> vrv; xpc_UnmarkGrayObject(mScopeObject); xpc_UnmarkGrayObject(mHandler); rv = mContext->CallEventHandler(mTarget, mScopeObject, mHandler, iargv, getter_AddRefs(vrv)); if (NS_SUCCEEDED(rv)) { uint16_t dataType = nsIDataType::VTYPE_VOID; if (vrv) vrv->GetDataType(&dataType); if (mEventName == nsGkAtoms::onbeforeunload) { nsCOMPtr<nsIDOMBeforeUnloadEvent> beforeUnload = do_QueryInterface(aEvent); NS_ENSURE_STATE(beforeUnload); if (dataType != nsIDataType::VTYPE_VOID) { aEvent->PreventDefault(); nsAutoString text; beforeUnload->GetReturnValue(text); // Set the text in the beforeUnload event as long as it wasn't // already set (through event.returnValue, which takes // precedence over a value returned from a JS function in IE) if ((dataType == nsIDataType::VTYPE_DOMSTRING || dataType == nsIDataType::VTYPE_CHAR_STR || dataType == nsIDataType::VTYPE_WCHAR_STR || dataType == nsIDataType::VTYPE_STRING_SIZE_IS || dataType == nsIDataType::VTYPE_WSTRING_SIZE_IS || dataType == nsIDataType::VTYPE_CSTRING || dataType == nsIDataType::VTYPE_ASTRING) && text.IsEmpty()) { vrv->GetAsDOMString(text); beforeUnload->SetReturnValue(text); } } } else if (dataType == nsIDataType::VTYPE_BOOL) { // If the handler returned false and its sense is not reversed, // or the handler returned true and its sense is reversed from // the usual (false means cancel), then prevent default. bool brv; if (NS_SUCCEEDED(vrv->GetAsBool(&brv)) && brv == (mEventName == nsGkAtoms::onerror || mEventName == nsGkAtoms::onmouseover)) { aEvent->PreventDefault(); } } } return rv; } /* virtual */ void nsJSEventListener::SetHandler(JSObject *aHandler) { // Technically we should drop the old mHandler and hold the new // one... except for JS this is a no-op, and we're really not // pretending very hard to support anything else. And since we // can't in fact only drop one script object (we'd have to drop // mScope too, and then re-hold it), let's just not worry about it // all. mHandler = aHandler; } /* * Factory functions */ nsresult NS_NewJSEventListener(nsIScriptContext* aContext, JSObject* aScopeObject, nsISupports*aTarget, nsIAtom* aEventType, JSObject* aHandler, nsIJSEventListener** aReturn) { NS_ENSURE_ARG(aEventType); nsJSEventListener* it = new nsJSEventListener(aContext, aScopeObject, aTarget, aEventType, aHandler); NS_ADDREF(*aReturn = it); return NS_OK; }
34.158076
81
0.702012
[ "object" ]
4716d61a5059ae85403829f5fa22611fb2e1c527
11,371
cpp
C++
CommonDev/Water.cpp
cjburchell/terrafighter
debc9b7563de05263d9159fbff15407a2dcb0fe9
[ "Apache-2.0" ]
null
null
null
CommonDev/Water.cpp
cjburchell/terrafighter
debc9b7563de05263d9159fbff15407a2dcb0fe9
[ "Apache-2.0" ]
null
null
null
CommonDev/Water.cpp
cjburchell/terrafighter
debc9b7563de05263d9159fbff15407a2dcb0fe9
[ "Apache-2.0" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// Water.cpp /// /// PATH: D:\dev2\CommonDev /// /// CREATED: 02/06/2004 4:51:15 PM by Christiaan Burchell /// /// PURPOSE: the water object /// /// COPYRIGHT NOTICE: Copyright (C) 2004 Redpoint Games /// /// This software is provided 'as-is', without any express or implied /// warranty. In no event will the author be held liable for any damages /// arising from the use of this software. /// /// Permission is granted to anyone to use this software for any purpose, /// excluding commercial applications, and to alter it and redistribute it /// freely, subject to the following restrictions: /// /// 1. The origin of this software must not be misrepresented; you must not /// claim that you wrote the original software. If you use this software /// in a product, an acknowledgment in the product documentation would be /// appreciated but is not required. /// 2. Altered source versions must be plainly marked as such, and must not be /// misrepresented as being the original software. /// 3. This notice may not be removed or altered from any source distribution. /// 4. The author permission is required to use this software in commercial /// applications /// /// LAST CHANGED: $Date$ /// /// REVISION HISTORY: /// $Log$ /// // Water.cpp: implementation of the CWater class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "D3DUtil.h" #include "Water.h" #include "DXUtil.h" #include "vertextypes.h" #include "D3DApp.h" #ifdef _DEBUG #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////// /// /// NAME: CWater /// /// CLASS: CWater /// /// DESCRIPTION: Class Constructor /// /// CREATED: 02/06/2004 4:51:18 PM /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// CWater::CWater() { m_pVB = NULL; m_Tex2Offset = 0.0f; //m_pIB = NULL; D3DXMatrixTranslation( &m_Matrix, 0.0f, 0.0f, 0.0f ); m_pTexture = NULL; m_pTexture2 = NULL; m_pVBGround = NULL; m_pTextureGround = NULL; m_bShowWater = TRUE; m_GroundTexture = _T("sand.jpg"); m_WaterLevel = 0; m_nTri = 0; } ///////////////////////////////////////////////// /// /// NAME: ~CWater /// /// CLASS: CWater /// /// DESCRIPTION: Class Destructor /// /// CREATED: 02/06/2004 4:51:20 PM /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// CWater::~CWater() { } ///////////////////////////////////////////////// /// /// NAME: Render /// /// CLASS: CWater /// /// DESCRIPTION: Render the water /// /// CREATED: 02/06/2004 4:51:30 PM /// /// PARAMETERS: /// LPDIRECT3DDEVICE8 pd3dDevice /// CFOVClipper* pClipper /// DWORD& nTri /// BOOL bWaterEff /// /// RETURN: HRESULT /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// HRESULT CWater::Render(LPDIRECT3DDEVICE9 pd3dDevice,CFOVClipper* pClipper, DWORD& nTri,BOOL bWaterEff) { D3DMATERIAL9 Material; D3DUtil::InitMaterial( Material, 1.0f, 1.0f, 1.0f , 0.0f); pd3dDevice->SetMaterial( &Material ); pd3dDevice->SetTransform( D3DTS_WORLD, &m_Matrix ); pd3dDevice->SetVertexShader( NULL ); pd3dDevice->SetFVF( D3DFVF_D3DVERTEX ); pd3dDevice->SetStreamSource( 0, m_pVBGround, 0, sizeof(D3DVERTEX) ); pd3dDevice->SetTexture( 0, m_pTextureGround ); pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP,0, 2); nTri+=2; if(m_bShowWater) { // Draw the mirror pd3dDevice->SetTexture( 0, m_pTexture ); if(bWaterEff) { pd3dDevice->SetTexture( 1, m_pTexture2 ); pd3dDevice->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 ); pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_MODULATE ); pd3dDevice->SetTextureStageState( 1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 ); D3DXMATRIX TexMatrix; D3DXMatrixIdentity(&TexMatrix); // declared in d3dutil.h TexMatrix._31 = m_Tex2Offset; TexMatrix._32 = m_Tex2Offset; pd3dDevice->SetTransform( D3DTS_TEXTURE1 , &TexMatrix ); } pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_DESTCOLOR);//D3DBLEND_DESTCOLOR ); pd3dDevice->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_SRCCOLOR);//D3DBLEND_ZERO ); pd3dDevice->SetVertexShader( NULL ); pd3dDevice->SetFVF( D3DFVF_MIRRORVERTEX ); pd3dDevice->SetStreamSource( 0, m_pVB, 0, sizeof(MIRRORVERTEX) ); //pd3dDevice->SetIndices( m_pIB, 0 ); pd3dDevice->SetSamplerState(0,D3DSAMP_ADDRESSU,D3DTADDRESS_MIRROR); pd3dDevice->SetSamplerState(0,D3DSAMP_ADDRESSV,D3DTADDRESS_MIRROR); //pd3dDevice->SetRenderState( D3DRS_FOGENABLE, FALSE ); pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP,0, 2); nTri+=2; m_nTri=2; //pd3dDevice->SetRenderState( D3DRS_FOGENABLE, TRUE ); pd3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); if(bWaterEff) { pd3dDevice->SetTextureStageState( 1, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE ); pd3dDevice->SetTexture( 1, NULL ); pd3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_DISABLE ); } pd3dDevice->SetSamplerState(0,D3DSAMP_ADDRESSU,D3DTADDRESS_WRAP); pd3dDevice->SetSamplerState(0,D3DSAMP_ADDRESSV,D3DTADDRESS_WRAP); } pd3dDevice->SetTexture( 0, NULL ); return S_OK; } ///////////////////////////////////////////////// /// /// NAME: Init /// /// CLASS: CWater /// /// DESCRIPTION: init the water object /// /// CREATED: 02/06/2004 4:51:40 PM /// /// PARAMETERS: /// BOOL bShowWater /// CString GroundTexture /// const char* strWater1 /// const char* strWater2 /// /// RETURN: HRESULT /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// HRESULT CWater::Init(BOOL bShowWater, CString GroundTexture,const char* strWater1,const char* strWater2) { m_bShowWater = bShowWater; if(!GroundTexture.IsEmpty()) m_GroundTexture = GroundTexture; m_WaterTexture1 = strWater1; m_WaterTexture2 = strWater2; return S_OK; } ///////////////////////////////////////////////// /// /// NAME: Create /// /// CLASS: CWater /// /// DESCRIPTION: Create the water object /// /// CREATED: 02/06/2004 4:51:48 PM /// /// PARAMETERS: /// LPDIRECT3DDEVICE8 pd3dDevice /// FLOAT sizex /// FLOAT sizey /// FLOAT WaterLevel /// CTerrain* pTerrain /// CZipArchive* pZip /// /// RETURN: HRESULT /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// HRESULT CWater::Create(LPDIRECT3DDEVICE9 pd3dDevice,FLOAT sizex, FLOAT sizey, FLOAT WaterLevel,CTerrain* pTerrain, CZipArchive* pZip) { m_WaterLevel = WaterLevel; // Set up a material if( FAILED( D3DUtil::CreateTexture( pd3dDevice, (LPSTR)((LPCSTR)m_WaterTexture1), m_pTexture ,pZip) ) ) return D3DAPPERR_MEDIANOTFOUND; if( FAILED( D3DUtil::CreateTexture( pd3dDevice, (LPSTR)((LPCSTR)m_WaterTexture2), m_pTexture2 ,pZip ) ) ) return D3DAPPERR_MEDIANOTFOUND; if( FAILED( D3DUtil::CreateTexture( pd3dDevice, m_GroundTexture.GetBuffer(m_GroundTexture.GetLength()), m_pTextureGround , pZip) ) ) return D3DAPPERR_MEDIANOTFOUND; m_dwNumVertices = g_WaterGridSize*g_WaterGridSize; m_dwNumFaces = (((g_WaterGridSize-1)*(g_WaterGridSize-1))*2); // Create a big square for rendering the mirror if( FAILED( pd3dDevice->CreateVertexBuffer( 4*sizeof(MIRRORVERTEX), D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC, D3DFVF_MIRRORVERTEX, D3DPOOL_DEFAULT, &m_pVB , NULL) ) ) return E_FAIL; if( FAILED( pd3dDevice->CreateVertexBuffer( 4*sizeof(D3DVERTEX), D3DUSAGE_WRITEONLY|D3DUSAGE_DYNAMIC, D3DFVF_D3DVERTEX, D3DPOOL_DEFAULT, &m_pVBGround, NULL ) ) ) return E_FAIL; //sizey = sizex = g_WaterGridSize; FLOAT halfx = (FLOAT)g_WaterGridSize/2.0f; FLOAT halfz = (FLOAT)g_WaterGridSize/2.0f; m_Scale = sizex/g_WaterGridSize; FLOAT xsize = (FLOAT) halfx*m_Scale; FLOAT zsize = (FLOAT) halfz*m_Scale; FLOAT textfactor = g_WaterGridSize/8; MIRRORVERTEX* v = NULL; m_pVB->Lock( 0, 4*sizeof(MIRRORVERTEX), (void**)&v, D3DLOCK_DISCARD ); v[0].p = D3DXVECTOR3(-sizex, m_WaterLevel,-sizey ); v[0].n = D3DXVECTOR3( 0.0f, -1.0f, 0.0f ); v[0].tu = textfactor; v[0].tv = textfactor; v[0].tu1 = g_WaterGridSize; v[0].tv1 = g_WaterGridSize; v[1].p = D3DXVECTOR3(-sizex, m_WaterLevel, sizey ); v[1].n = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); v[1].tu = textfactor; v[1].tv = 0.0f; v[1].tu1 = g_WaterGridSize; v[1].tv1 = 0.0f; v[2].p = D3DXVECTOR3( sizex, m_WaterLevel,-sizey ); v[2].n = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); v[2].tu = 0.0f; v[2].tv = textfactor; v[2].tu1 = 0.0f; v[2].tv1 = g_WaterGridSize; v[3].p = D3DXVECTOR3( sizex, m_WaterLevel, sizey ); v[3].n = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); v[3].tu = 0.0f; v[3].tv = 0.0f; v[3].tu1 = 0.0f; v[3].tv1 = 0.0f; m_pVB->Unlock(); D3DVERTEX* v2 = NULL; m_pVBGround->Lock( 0, 4*sizeof(D3DVERTEX), (void**)&v2, D3DLOCK_DISCARD ); v2[0].p = D3DXVECTOR3(-sizex, -0.1f,-sizey ); v2[0].n = D3DXVECTOR3( 0.0f, -1.0f, 0.0f ); v2[0].tu = textfactor; v2[0].tv = textfactor; v2[1].p = D3DXVECTOR3(-sizex, -0.1f, sizey ); v2[1].n = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); v2[1].tu = textfactor; v2[1].tv = 0.0f; v2[2].p = D3DXVECTOR3( sizex, -0.1f,-sizey ); v2[2].n = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); v2[2].tu = 0.0f; v2[2].tv = textfactor; v2[3].p = D3DXVECTOR3( sizex, -0.1f, sizey ); v2[3].n = D3DXVECTOR3( 0.0f, 1.0f, 0.0f ); v2[3].tu = 0.0f; v2[3].tv = 0.0f; m_pVB->Unlock(); return S_OK; } ///////////////////////////////////////////////// /// /// NAME: DeleteDeviceObjects /// /// CLASS: CWater /// /// DESCRIPTION: Destroys all device-dependent objects /// /// CREATED: 02/06/2004 4:54:57 PM /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CWater::DeleteDeviceObjects() { m_pVB = NULL; m_pVBGround = NULL; D3DUtil::ReleaseTexture( m_pTexture ); m_pTexture = NULL; D3DUtil::ReleaseTexture( m_pTexture2 ); m_pTexture2 = NULL; D3DUtil::ReleaseTexture( m_pTextureGround ); m_pTextureGround = NULL; } ///////////////////////////////////////////////// /// /// NAME: AnimateWater /// /// CLASS: CWater /// /// DESCRIPTION: Animate the water /// /// CREATED: 02/06/2004 4:52:00 PM /// /// PARAMETERS: /// float dt /// BOOL bWaterEff /// /// RETURN: void /// /// SIDE EFFECTS: /// ///////////////////////////////////////////////// void CWater::AnimateWater(float dt,BOOL bWaterEff) { if(bWaterEff) { m_Tex2Offset += dt/20.0f; if(m_Tex2Offset>2.0f) m_Tex2Offset -= 2.0f; } }
26.020595
133
0.580776
[ "render", "object" ]
47170e8d845f2f711c51684b9404e94672fe03c8
6,762
hh
C++
pdns-recursor-4.0.6/dnssecinfra.hh
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
7
2017-07-16T15:09:26.000Z
2021-09-01T02:13:15.000Z
pdns-recursor-4.0.6/dnssecinfra.hh
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
null
null
null
pdns-recursor-4.0.6/dnssecinfra.hh
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
3
2017-09-13T09:54:49.000Z
2019-03-18T01:29:15.000Z
/* * This file is part of PowerDNS or dnsdist. * Copyright -- PowerDNS.COM B.V. and its contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * In addition, for the avoidance of any doubt, permission is granted to * link this program with OpenSSL and to (re)distribute the binaries * produced as the result of such linking. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef PDNS_DNSSECINFRA_HH #define PDNS_DNSSECINFRA_HH #include "dnsrecords.hh" #include <string> #include <vector> #include <map> #include "misc.hh" class UeberBackend; // rules of the road: Algorithm must be set in 'make' for each KeyEngine, and will NEVER change! class DNSCryptoKeyEngine { public: explicit DNSCryptoKeyEngine(unsigned int algorithm) : d_algorithm(algorithm) {} virtual ~DNSCryptoKeyEngine() {}; virtual string getName() const = 0; typedef std::map<std::string, std::string> stormap_t; typedef std::vector<std::pair<std::string, std::string > > storvector_t; virtual void create(unsigned int bits)=0; virtual storvector_t convertToISCVector() const =0; std::string convertToISC() const ; virtual std::string sign(const std::string& msg) const =0; virtual std::string hash(const std::string& msg) const { throw std::runtime_error("hash() function not implemented"); return msg; } virtual bool verify(const std::string& msg, const std::string& signature) const =0; virtual std::string getPubKeyHash()const =0; virtual std::string getPublicKeyString()const =0; virtual int getBits() const =0; virtual void fromISCMap(DNSKEYRecordContent& drc, stormap_t& stormap)=0; virtual void fromPEMString(DNSKEYRecordContent& drc, const std::string& raw) { throw std::runtime_error("Can't import from PEM string"); } virtual void fromPublicKeyString(const std::string& content) = 0; virtual bool checkKey() const { return true; } static shared_ptr<DNSCryptoKeyEngine> makeFromISCFile(DNSKEYRecordContent& drc, const char* fname); static shared_ptr<DNSCryptoKeyEngine> makeFromISCString(DNSKEYRecordContent& drc, const std::string& content); static shared_ptr<DNSCryptoKeyEngine> makeFromPEMString(DNSKEYRecordContent& drc, const std::string& raw); static shared_ptr<DNSCryptoKeyEngine> makeFromPublicKeyString(unsigned int algorithm, const std::string& raw); static shared_ptr<DNSCryptoKeyEngine> make(unsigned int algorithm); typedef shared_ptr<DNSCryptoKeyEngine> maker_t(unsigned int algorithm); static void report(unsigned int algorithm, maker_t* maker, bool fallback=false); static std::pair<unsigned int, unsigned int> testMakers(unsigned int algorithm, maker_t* creator, maker_t* signer, maker_t* verifier); static vector<pair<uint8_t, string>> listAllAlgosWithBackend(); static bool testAll(); static bool testOne(int algo); private: typedef std::map<unsigned int, maker_t*> makers_t; typedef std::map<unsigned int, vector<maker_t*> > allmakers_t; static makers_t& getMakers() { static makers_t s_makers; return s_makers; } static allmakers_t& getAllMakers() { static allmakers_t s_allmakers; return s_allmakers; } protected: const unsigned int d_algorithm; }; struct DNSSECPrivateKey { uint16_t getTag(); const shared_ptr<DNSCryptoKeyEngine> getKey() const { return d_key; } void setKey(const shared_ptr<DNSCryptoKeyEngine> key) { d_key = key; } DNSKEYRecordContent getDNSKEY() const; uint16_t d_flags; uint8_t d_algorithm; private: shared_ptr<DNSCryptoKeyEngine> d_key; }; struct CanonicalCompare: public std::binary_function<string, string, bool> { bool operator()(const std::string& a, const std::string& b) { std::vector<std::string> avect, bvect; stringtok(avect, a, "."); stringtok(bvect, b, "."); reverse(avect.begin(), avect.end()); reverse(bvect.begin(), bvect.end()); return avect < bvect; } }; bool sharedDNSSECCompare(const std::shared_ptr<DNSRecordContent>& a, const shared_ptr<DNSRecordContent>& b); string getMessageForRRSET(const DNSName& qname, const RRSIGRecordContent& rrc, std::vector<std::shared_ptr<DNSRecordContent> >& signRecords, bool processRRSIGLabels = false); DSRecordContent makeDSFromDNSKey(const DNSName& qname, const DNSKEYRecordContent& drc, int digest=1); class RSAContext; class DNSSECKeeper; struct DNSSECPrivateKey; void fillOutRRSIG(DNSSECPrivateKey& dpk, const DNSName& signQName, RRSIGRecordContent& rrc, vector<shared_ptr<DNSRecordContent> >& toSign); uint32_t getStartOfWeek(); void addSignature(DNSSECKeeper& dk, UeberBackend& db, const DNSName& signer, const DNSName signQName, const DNSName& wildcardname, uint16_t signQType, uint32_t signTTL, DNSResourceRecord::Place signPlace, vector<shared_ptr<DNSRecordContent> >& toSign, vector<DNSResourceRecord>& outsigned, uint32_t origTTL); int getRRSIGsForRRSET(DNSSECKeeper& dk, const DNSName& signer, const DNSName signQName, uint16_t signQType, uint32_t signTTL, vector<shared_ptr<DNSRecordContent> >& toSign, vector<RRSIGRecordContent> &rrc); string hashQNameWithSalt(const NSEC3PARAMRecordContent& ns3prc, const DNSName& qname); string hashQNameWithSalt(const std::string& salt, unsigned int iterations, const DNSName& qname); void decodeDERIntegerSequence(const std::string& input, vector<string>& output); class DNSPacket; void addRRSigs(DNSSECKeeper& dk, UeberBackend& db, const std::set<DNSName>& authMap, vector<DNSResourceRecord>& rrs); string calculateHMAC(const std::string& key, const std::string& text, TSIGHashEnum hash); bool constantTimeStringEquals(const std::string& a, const std::string& b); string makeTSIGMessageFromTSIGPacket(const string& opacket, unsigned int tsigoffset, const DNSName& keyname, const TSIGRecordContent& trc, const string& previous, bool timersonly, unsigned int dnsHeaderOffset=0); void addTSIG(DNSPacketWriter& pw, TSIGRecordContent* trc, const DNSName& tsigkeyname, const string& tsigsecret, const string& tsigprevious, bool timersonly); uint64_t signatureCacheSize(const std::string& str); #endif
39.776471
212
0.746377
[ "vector" ]
471a7565cdfe006117159185e73cdcf238201adb
14,310
cpp
C++
Src/conditionalMean.cpp
AspdenGroup/PeleAnalysis_Aspden
4259efa97a65a646a4e1bc3493cd9dae1e7024c5
[ "BSD-3-Clause-LBNL" ]
4
2019-04-24T13:33:35.000Z
2021-08-24T07:11:22.000Z
Src/conditionalMean.cpp
AspdenGroup/PeleAnalysis_Aspden
4259efa97a65a646a4e1bc3493cd9dae1e7024c5
[ "BSD-3-Clause-LBNL" ]
4
2020-02-25T01:58:46.000Z
2022-02-01T20:22:49.000Z
Src/conditionalMean.cpp
AspdenGroup/PeleAnalysis_Aspden
4259efa97a65a646a4e1bc3493cd9dae1e7024c5
[ "BSD-3-Clause-LBNL" ]
6
2018-11-05T11:53:20.000Z
2021-03-22T10:44:54.000Z
#include <string> #include <iostream> using std::cout; using std::cerr; using std::endl; #include <AMReX_ParmParse.H> #include <AMReX_MultiFab.H> #include <AMReX_DataServices.H> #include <WritePlotFile.H> #include <AppendToPlotFile.H> using namespace amrex; static void print_usage (int, char* argv[]) { std::cerr << "usage:\n"; std::cerr << argv[0] << " infile=<filename>\n" << " binComp=i : Variable id number to condition on\n" << " AvgComps=j k l : Variable id numbers to average\n" << " min=m; max=m : min/max values for bins%i\n" << " nBins=n : Number of bins in PDF (default=64)\n" << " finestLevel=n : Finest level at which to evaluate PDF\n" << " outSuffix=str : Suffix to add to the pltfile name as an alt dir for results (default="")\n" << " aja=true/false : Put the header in a separate file for gnuplot/matlab (default=false)\n" << " infile= plt1 plt2 : List of plot files" << std::endl; exit(1); } typedef BaseFab<int> IntFab; typedef FabArray<IntFab> IntMF; int main (int argc, char* argv[]) { amrex::Initialize(argc,argv); if (argc < 2) print_usage(argc,argv); ParmParse pp; if (pp.contains("help")) print_usage(argc,argv); bool isioproc = ParallelDescriptor::IOProcessor(); int ioproc = ParallelDescriptor::IOProcessorNumber(); int verbose=0; pp.query("verbose",verbose); if ( !(isioproc) ) verbose=0; if (verbose>1) AmrData::SetVerbose(true); // Get plot file int nPlotFiles(pp.countval("infile")); if(nPlotFiles <= 0) { std::cerr << "Bad nPlotFiles: " << nPlotFiles << std::endl; std::cerr << "Exiting." << std::endl; DataServices::Dispatch(DataServices::ExitRequest, NULL); } if (verbose) std::cout << "Processing " << nPlotFiles << " plotfiles..." << std::endl; std::string outSuffix = ""; pp.query("outSuffix",outSuffix); // Make an array of srings containing paths of input plot files Vector<std::string> plotFileNames(nPlotFiles); for(int iPlot = 0; iPlot < nPlotFiles; ++iPlot) { pp.get("infile", plotFileNames[iPlot], iPlot); if (verbose) std::cout << " " << plotFileNames[iPlot] << std::endl; } // Get finest level argument int finestLevel(-1); pp.query("finestLevel",finestLevel); // Number of bins int nBins(64); pp.query("nBins",nBins); // Variables to bin, and to average int binComp = -1; pp.get("binComp",binComp); int nAvgComps = pp.countval("avgComps"); Vector<int> avgComps; if (nAvgComps > 0) { avgComps.resize(nAvgComps); pp.getarr("avgComps",avgComps,0,nAvgComps); } else { amrex::Abort("need to specify avgComps"); } Vector<Real> binVals(nBins*nAvgComps,0); Vector<Real> binValsSq(nBins*nAvgComps,0); bool writeBinMinMax = false; pp.query("writeBinMinMax",writeBinMinMax); Vector<Real> binMinVals; Vector<Real> binMaxVals; Vector<int> binHits(nBins,0); if (writeBinMinMax) { binMinVals.resize(nBins*nAvgComps,0); binMaxVals.resize(nBins*nAvgComps,0); } Real binMin=0; pp.get("binMin",binMin); Real binMax=1; pp.get("binMax",binMax); if (binMax <= binMin) amrex::Abort("Bad bin min,max"); bool floor=false; pp.query("floor",floor); bool ceiling=false; pp.query("ceiling",ceiling); Real domainVol = -1; Vector<int> weights; Vector<string> compNames; Vector<int> destFillComps(avgComps.size()+1); for (int i=0; i<destFillComps.size(); ++i) destFillComps[i] = i+1;// zero slot for mask int nComp = destFillComps.size() + 1; Vector<Real> dataIV(nComp); vector<Real> bbll,bbur; if (int nx=pp.countval("bounds")) { Vector<Real> barr; pp.getarr("bounds",barr,0,nx); int d=BL_SPACEDIM; BL_ASSERT(barr.size()==2*d); bbll.resize(d); bbur.resize(d); for (int i=0; i<d; ++i) { bbll[i] = barr[i]; bbur[i] = barr[d+i]; } } bool aja(false); pp.query("aja",aja); if (aja && isioproc) std::cout << "Output for aja" << std::endl; // Loop over files for (int iPlot=0; iPlot<nPlotFiles; iPlot++) { // Open file and get an amrData pointer const std::string& infile = plotFileNames[iPlot]; if (verbose) std::cout << "\nOpening " << infile << "..." << std::endl; DataServices::SetBatchMode(); Amrvis::FileType fileType(Amrvis::NEWPLT); DataServices dataServices(infile, fileType); if (!dataServices.AmrDataOk()) DataServices::Dispatch(DataServices::ExitRequest, NULL); AmrData& amrData = dataServices.AmrDataRef(); int ngrow = 0; Box domain; if (iPlot==0) { compNames.resize(avgComps.size()+1); compNames[0] = amrData.PlotVarNames()[binComp]; for (int i=0; i<avgComps.size(); ++i) { int comp = avgComps[i]; if (comp<0 || comp>=amrData.NComp()) amrex::Abort("Bad comp: " + comp); compNames[i+1] = amrData.PlotVarNames()[comp]; } domain = amrData.ProbDomain()[0]; if (bbll.size()==BL_SPACEDIM && bbur.size()==BL_SPACEDIM) { // Find coarse-grid coordinates of bounding box, round outwardly for (int i=0; i<BL_SPACEDIM; ++i) { const Real dx = amrData.ProbSize()[i] / amrData.ProbDomain()[0].length(i); domain.setSmall(i, std::max(domain.smallEnd()[i], (int)((bbll[i]-amrData.ProbLo()[i]+.0001*dx)/dx))); domain.setBig(i, std::min(domain.bigEnd()[i], (int)((bbur[i]-amrData.ProbLo()[i]-.0001*dx)/dx))); } } domainVol = domain.d_numPts(); if (finestLevel<0) finestLevel = amrData.FinestLevel(); weights.resize(finestLevel+1,1); for (int i=finestLevel-1; i>=0; --i) { int rat = amrData.RefRatio()[i]; weights[i] = weights[i+1]; for (int d=0; d<BL_SPACEDIM; ++d) weights[i] *= rat; } } // Build boxarrays for fillvar call Box levelDomain = domain; int thisFinestLevel = std::min(finestLevel,amrData.FinestLevel()); int Nlevels = thisFinestLevel+1; Vector<BoxArray> bas(Nlevels); for (int iLevel=0; iLevel<=thisFinestLevel; ++iLevel) { BoxArray baThisLev = amrex::intersect(amrData.boxArray(iLevel),levelDomain); BoxList blThisLev(baThisLev); blThisLev.simplify(); blThisLev.simplify(); baThisLev = BoxArray(blThisLev); if (baThisLev.size() > 0) { //bas.set(iLevel,baThisLev); bas[iLevel] = baThisLev; bas[iLevel].maxSize(32); if (iLevel < thisFinestLevel) { levelDomain.refine(amrData.RefRatio()[iLevel]); } } else { bas.resize(iLevel); } } int ratio = 1; for (int iLevel=0; iLevel<=thisFinestLevel; ++iLevel) { if (bas.size()>iLevel) { DistributionMapping dmap(bas[iLevel]); MultiFab mf(bas[iLevel], dmap, nComp, ngrow); amrData.FillVar(mf, iLevel, compNames, destFillComps); mf.setVal(1,0,1); // initlaize mask to value // zero out covered data if (iLevel<thisFinestLevel) { ratio = amrData.RefRatio()[iLevel]; BoxArray baf = BoxArray(bas[iLevel+1]).coarsen(ratio); for (MFIter mfi(mf); mfi.isValid(); ++mfi) { const Box& box = mfi.validbox(); FArrayBox& fab = mf[mfi]; std::vector< std::pair<int,Box> > isects = baf.intersections(box); for (int ii = 0; ii < isects.size(); ii++) fab.setVal(0,isects[ii].second,0,1); } } for(MFIter mfi(mf); mfi.isValid(); ++mfi) { FArrayBox& fab = mf[mfi]; const Box& box = mfi.validbox(); for (IntVect iv=box.smallEnd(); iv<=box.bigEnd(); box.next(iv)) { fab.getVal(dataIV.dataPtr(),iv); if (dataIV[0] != 0) // not covered { Real binVal = dataIV[1]; if (binVal>=binMin && binVal<binMax) { int myBin = (int)(nBins*(binVal-binMin)/(binMax-binMin)); if (myBin<0 || myBin>=binHits.size()) amrex::Abort("Bad bin"); int myWeight = weights[iLevel]; for (int j=0; j<nAvgComps; ++j) { Real val = dataIV[j+2]; int binIdx = myBin*nAvgComps + j; binVals[binIdx] += myWeight * val; binValsSq[binIdx] += myWeight * val * val; if (writeBinMinMax) { if (binHits[myBin]==0) { binMinVals[binIdx] = val; binMaxVals[binIdx] = val; } binMinVals[binIdx] = std::min(val,binMinVals[binIdx]); binMaxVals[binIdx] = std::max(val,binMaxVals[binIdx]); } } binHits[myBin] += myWeight; } } } } // MFI } // if } // Level } // iPlot ParallelDescriptor::ReduceIntSum(binHits.dataPtr(),binHits.size(),ioproc); ParallelDescriptor::ReduceRealSum(binVals.dataPtr(),binVals.size(),ioproc); ParallelDescriptor::ReduceRealSum(binValsSq.dataPtr(),binValsSq.size(),ioproc); if (writeBinMinMax) { ParallelDescriptor::ReduceRealMin(binMinVals.dataPtr(),binMinVals.size(),ioproc); ParallelDescriptor::ReduceRealMax(binMaxVals.dataPtr(),binMaxVals.size(),ioproc); } // Output result if (isioproc) { std::string filename; // Output data for tecplot //filename = infile + outSuffix + "/CM_" + compNames[0] + ".dat"; if (aja) { filename = plotFileNames[0] + "/CM_" + compNames[0] + ".key"; std::cout << "Opening file " << filename << std::endl; } else { // Default filename = "CM_" + compNames[0] + ".dat"; std::cout << "Opening file " << filename << std::endl; } std::ofstream ofs(filename.c_str()); string variables = "VARIABLES = " + compNames[0]; for (int i=1; i<compNames.size(); ++i) variables += " " + compNames[i] + "_sum"; for (int i=1; i<compNames.size(); ++i) variables += " " + compNames[i] + "_sumSq"; for (int i=1; i<compNames.size(); ++i) variables += " " + compNames[i] + "_avg"; for (int i=1; i<compNames.size(); ++i) variables += " " + compNames[i] + "_std"; if (writeBinMinMax) { for (int i=1; i<compNames.size(); ++i) variables += " " + compNames[i] + "_min"; for (int i=1; i<compNames.size(); ++i) variables += " " + compNames[i] + "_max"; } variables += " N "; variables += " p "; variables += '\n'; ofs << variables.c_str(); ofs << "ZONE I=" << nBins << " DATAPACKING=POINT\n"; if (aja) { ofs.close(); filename = plotFileNames[0] + "/CM_" + compNames[0] + ".dat"; std::cout << "Opening file " << filename << std::endl; ofs.open(filename.c_str()); } const Real dv = (binMax - binMin)/nBins; int ntot = 0; for (int i=0; i<nBins; i++) { ntot += binHits[i]; } for (int i=0; i<nBins; i++) { const Real v = binMin + dv*(0.5+(Real)i); ofs << v << " "; // Sum for (int j=0; j<nAvgComps; j++) { ofs << binVals[i*nAvgComps + j] << " "; } // SumSq for (int j=0; j<nAvgComps; j++) { ofs << binValsSq[i*nAvgComps + j] << " "; } if (binHits[i]>0) { // Avg for (int j=0; j<nAvgComps; j++) { ofs << binVals[i*nAvgComps + j]/(Real)binHits[i] << " "; } // Std Dev for (int j=0; j<nAvgComps; j++) { int idx = i*nAvgComps + j; Real bh = (Real)binHits[i]; ofs << std::sqrt( (binValsSq[idx]/bh) - (binVals[idx]/bh)*(binVals[idx]/bh) ) << " "; } } else { // Avg & Std Dev for (int j=0; j<nAvgComps*2; j++) { ofs << "0.0 "; } } if (writeBinMinMax) { for (int j=0; j<nAvgComps; j++) { ofs << binMinVals[i*nAvgComps + j] << " "; } for (int j=0; j<nAvgComps; j++) { ofs << binMaxVals[i*nAvgComps + j] << " "; } } ofs << Real(binHits[i]) << " "; ofs << Real(binHits[i])/ntot << '\n'; } cout << "total bins: " << ntot << endl; ofs.close(); } // IOProcessor amrex::Finalize(); return 0; }
34.987775
112
0.483019
[ "vector" ]
471c55110433cb88976322dd7b1d56b3ebfc3df5
14,121
cpp
C++
DT3Core/Scripting/ScriptingSpline.cpp
9heart/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
3
2016-01-27T13:17:18.000Z
2019-03-19T09:18:25.000Z
DT3Core/Scripting/ScriptingSpline.cpp
pakoito/DT3
4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e
[ "MIT" ]
1
2016-01-28T14:39:49.000Z
2016-01-28T22:12:07.000Z
DT3Core/Scripting/ScriptingSpline.cpp
adderly/DT3
e2605be091ec903d3582e182313837cbaf790857
[ "MIT" ]
3
2016-01-25T16:44:51.000Z
2021-01-29T19:59:45.000Z
//============================================================================== /// /// File: ScriptingSpline.cpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== #include "DT3Core/Scripting/ScriptingSpline.hpp" #include "DT3Core/System/Factory.hpp" #include "DT3Core/System/Profiler.hpp" #include "DT3Core/Types/FileBuffer/ArchiveData.hpp" #include "DT3Core/Types/FileBuffer/Archive.hpp" #include "DT3Core/Types/Math/Vector4.hpp" #include "DT3Core/Types/Math/Quaternion.hpp" //============================================================================== //============================================================================== namespace DT3 { //============================================================================== /// Register with object factory //============================================================================== IMPLEMENT_FACTORY_CREATION_SCRIPT(ScriptingSpline,"Animation",EdManipScriptingSpline) IMPLEMENT_PLUG_NODE(ScriptingSpline) IMPLEMENT_PLUG_INFO_INDEX(_d) IMPLEMENT_PLUG_INFO_INDEX(_transform) IMPLEMENT_PLUG_INFO_INDEX(_orientation) IMPLEMENT_PLUG_INFO_INDEX(_translation) //============================================================================== //============================================================================== BEGIN_IMPLEMENT_PLUGS(ScriptingSpline) PLUG_INIT(_d,"d") .set_input(true) .affects(PLUG_INFO_INDEX(_transform)) .affects(PLUG_INFO_INDEX(_orientation)) .affects(PLUG_INFO_INDEX(_translation)); PLUG_INIT(_transform,"Transform") .set_output(true); PLUG_INIT(_translation,"Translation") .set_output(true); PLUG_INIT(_orientation,"Orientation") .set_output(true); END_IMPLEMENT_PLUGS //============================================================================== /// Standard class constructors/destructors //============================================================================== ScriptingSpline::ScriptingSpline (void) : _constant_speed (true), _d (PLUG_INFO_INDEX(_d), 0.0F), _transform (PLUG_INFO_INDEX(_transform), Matrix4::identity()), _orientation (PLUG_INFO_INDEX(_orientation), Matrix3::identity()), _translation (PLUG_INFO_INDEX(_translation), Vector3(0.0F,0.0F,0.0F)), _dirty (true), _keyframe_cache (0) { } ScriptingSpline::ScriptingSpline (const ScriptingSpline &rhs) : ScriptingBase (rhs), _constant_speed (rhs._constant_speed), _d (rhs._d), _transform (rhs._transform), _orientation (rhs._orientation), _translation (rhs._translation), _dirty (true), _keyframe_cache (0) { } ScriptingSpline & ScriptingSpline::operator = (const ScriptingSpline &rhs) { // Make sure we are not assigning the class to itself if (&rhs != this) { ScriptingBase::operator = (rhs); _constant_speed = rhs._constant_speed; _d = rhs._d; _transform = rhs._transform; _orientation = rhs._orientation; _translation = rhs._translation; _keyframe_cache = rhs._keyframe_cache; _dirty = true; } return (*this); } ScriptingSpline::~ScriptingSpline (void) { } //============================================================================== //============================================================================== void ScriptingSpline::initialize (void) { ScriptingBase::initialize(); } //============================================================================== //============================================================================== void ScriptingSpline::archive (const std::shared_ptr<Archive> &archive) { ScriptingBase::archive(archive); archive->push_domain (class_id ()); *archive << ARCHIVE_DATA_ACCESSORS("Num_Points", ScriptingSpline::num_points, ScriptingSpline::set_num_points, DATA_PERSISTENT | DATA_SETTABLE); for (std::size_t i = 0; i < _transforms.size(); ++i) { *archive << ARCHIVE_DATA_RAW(_transforms[i]._transform, DATA_PERSISTENT); } *archive << ARCHIVE_PLUG(_d, DATA_PERSISTENT | DATA_SETTABLE); *archive << ARCHIVE_DATA(_constant_speed, DATA_PERSISTENT | DATA_SETTABLE); *archive << ARCHIVE_PLUG(_transform, DATA_PERSISTENT); *archive << ARCHIVE_PLUG(_orientation, DATA_PERSISTENT); *archive << ARCHIVE_PLUG(_translation, DATA_PERSISTENT); archive->pop_domain (); } void ScriptingSpline::archive_done (const std::shared_ptr<Archive> &archive) { ScriptingBase::archive_done (archive); if (archive->is_writing()) return; process_distances(); } //============================================================================== //============================================================================== DTfloat ScriptingSpline::max_distance (void) { PROFILER(SCRIPTING); if (_transforms.size() > 0) { if (_dirty) process_distances(); return _transforms.back()._distance; } else { return 0.0F; } } //============================================================================== //============================================================================== void ScriptingSpline::set_num_points (DTsize num) { PROFILER(SCRIPTING); _transforms.resize(num); _dirty = true; _transform.set_dirty(); _orientation.set_dirty(); _translation.set_dirty(); } DTsize ScriptingSpline::num_points (void) const { PROFILER(SCRIPTING); return _transforms.size(); } void ScriptingSpline::set_point_transform (DTuint k, const Matrix4 &transform) { PROFILER(SCRIPTING); _transforms[k]._transform = transform; _dirty = true; _transform.set_dirty(); _orientation.set_dirty(); _translation.set_dirty(); } const Matrix4& ScriptingSpline::point_transform (DTuint k) const { PROFILER(SCRIPTING); return _transforms[k]._transform; } void ScriptingSpline::set_point_tangent (DTuint k, const Vector3 &tangent) { PROFILER(SCRIPTING); _transforms[k]._tangent = tangent; _dirty = true; _transform.set_dirty(); _orientation.set_dirty(); _translation.set_dirty(); } const Vector3& ScriptingSpline::point_tangent (DTuint k) const { PROFILER(SCRIPTING); return _transforms[k]._tangent; } //============================================================================== // See http://mathworld.wolfram.com/LeastSquaresFittingPolynomial.html //============================================================================== void ScriptingSpline::process_distances (void) { PROFILER(SCRIPTING); if (_transforms.size() == 0) return; DTfloat STEP = 1.0F/100.0F; DTfloat distance = 0.0F; DTfloat length = 0.0; DTuint i; for (i = 0; i < _transforms.size()-1; ++i) { _transforms[i]._distance = distance; Matrix4 transform; // // Get length // length = 0.0F; interpolate (i, i+1, 0.0F, transform); Vector3 last_point = transform.translation(); // Sample curve to get length so we can normalize the // inputs for the regression analysis below for (DTfloat t = 0.0F; t <= 1.0F; t += STEP) { interpolate (i, i+1, t, transform); Vector3 this_point = transform.translation(); DTfloat dp = (this_point-last_point).abs(); // Accumulate lengths length += dp; distance += dp; last_point = this_point; } _transforms[i]._length = length; // // Perform regression // length = 0.0F; interpolate (i, i+1, 0.0F, transform); last_point = transform.translation(); DTfloat s0=0.0F,s1=0.0F,s2=0.0F,s3=0.0F,s4=0.0F,s5=0.0F,s6=0.0F; DTfloat y0=0.0F,y1=0.0F,y2=0.0F,y3=0.0F; // Sample curve for (DTfloat t = 0.0F; t <= 1.0F; t += STEP) { interpolate (i, i+1, t, transform); Vector3 this_point = transform.translation(); DTfloat dp = (this_point-last_point).abs(); // Accumulate lengths length += dp; last_point = this_point; // Accumulate points for regression analysis. // t = f(length) so x = length, y = t DTfloat x1 = length / _transforms[i]._length; // Normalized length DTfloat x2 = x1*x1; DTfloat x3 = x2*x1; DTfloat x4 = x2*x2; DTfloat x5 = x4*x1; DTfloat x6 = x4*x2; s0 += 1.0F; s1 += x1; s2 += x2; s3 += x3; s4 += x4; s5 += x5; s6 += x6; y0 += t; y1 += x1*t; y2 += x2*t; y3 += x3*t; } // Do regression Matrix4 X( s0, s1, s2, s3, s1, s2, s3, s4, s2, s3, s4, s5, s3, s4, s5, s6 ); Vector4 Y( y0, y1, y2, y3 ); Vector4 a = X.inversed() * Y; DTfloat sum = a.y + a.z + a.w; // To make sure the polynomial always returns 0-1 //_transforms[i]._a0 = a.x; _transforms[i]._a1 = a.y / sum; _transforms[i]._a2 = a.z / sum; _transforms[i]._a3 = a.w / sum; } _transforms[i]._distance = distance; _transforms[i]._length = 0.0F; _dirty = false; } //============================================================================== //============================================================================== void ScriptingSpline::interpolate (DTint i0, DTint i1, DTfloat d, Matrix4 &transform) { DTfloat d2 = d * d; DTfloat d3 = d * d2; // interpolate via Hermite spline // See Real_time Rendering, 2nd Ed., Page 492 Vector3 p1,p2,p3,p4; p1 = _transforms[i0]._transform.translation() * (2.0F * d3 - 3.0F * d2 + 1.0F); p2 = _transforms[i0]._tangent * (d3 - 2.0F * d2 + d); p3 = _transforms[i1]._tangent * (d3 - d2); p4 = _transforms[i1]._transform.translation() * (-2.0F * d3 + 3.0F * d2); Vector3 translation = p1 + p2 + p3 + p4; // Slerp orientations Quaternion q0 = Quaternion(_transforms[i0]._transform); Quaternion q1 = Quaternion(_transforms[i1]._transform); Quaternion rotation = Quaternion::slerp (q0, q1, d); transform = Matrix4( Matrix3(rotation), translation); } void ScriptingSpline::interpolate (DTfloat d, Matrix4 &transform) { // Special cases if (_transforms.size() == 0) { transform = Matrix4::identity(); return; } if (_dirty) process_distances(); if (_transforms.size() == 1) { transform = _transforms[0]._transform; return; } // Scan for the best key if (_keyframe_cache < 0) _keyframe_cache = 0; else if (_keyframe_cache > (DTint) _transforms.size() - 2) _keyframe_cache = (DTint) _transforms.size() - 2; while (1) { if (d < _transforms[_keyframe_cache]._distance) { --_keyframe_cache; if (_keyframe_cache < 0) { _keyframe_cache = 0; transform = _transforms[_keyframe_cache]._transform; break; } } else if (d > _transforms[_keyframe_cache+1]._distance) { ++_keyframe_cache; if (_keyframe_cache > (DTint) _transforms.size() - 2) { _keyframe_cache = (DTint) _transforms.size() - 2; transform = _transforms[_keyframe_cache+1]._transform; break; } } else { Pt &pt = _transforms[_keyframe_cache]; DTfloat d1 = 0.0F; if (pt._length > 0.0F) d1 = (d - pt._distance) / pt._length; // Normalized distance if (_constant_speed) { // Using polynomial approximation, convert distance to spline parametric value. Note a0 is always 0 DTfloat t = (pt._a1 * d1 + pt._a2 * d1 * d1 + pt._a3 * d1 * d1 * d1); interpolate (_keyframe_cache, _keyframe_cache+1, t, transform); } else { interpolate (_keyframe_cache, _keyframe_cache+1, d1, transform); } break; } } } //============================================================================== //============================================================================== DTboolean ScriptingSpline::compute (const PlugBase *plug) { PROFILER(SCRIPTING); if (super_type::compute(plug)) return true; if (plug == &_transform || plug == &_orientation || plug == &_translation) { Matrix4 transform = Matrix4::identity(); interpolate(_d,transform); _transform = transform; _orientation = transform.orientation(); _translation = transform.translation(); _transform.set_clean(); _orientation.set_clean(); _translation.set_clean(); return true; } return false; } //============================================================================== //============================================================================== } // DT3
30.044681
149
0.490334
[ "object", "transform" ]
471f4681abd782056407e87d7b8aaac2bc0033b1
1,143
cpp
C++
gsWriteParaviewMultiPhysics_.cpp
gismo/gsElasticity
a94347d4b8d8cd76de79d4b512023be9b68363bf
[ "BSD-3-Clause-Attribution" ]
7
2020-04-24T04:11:02.000Z
2021-09-18T19:24:10.000Z
gsWriteParaviewMultiPhysics_.cpp
gismo/gsElasticity
a94347d4b8d8cd76de79d4b512023be9b68363bf
[ "BSD-3-Clause-Attribution" ]
1
2021-08-16T20:41:48.000Z
2021-08-16T20:41:48.000Z
gsWriteParaviewMultiPhysics_.cpp
gismo/gsElasticity
a94347d4b8d8cd76de79d4b512023be9b68363bf
[ "BSD-3-Clause-Attribution" ]
6
2020-05-12T11:11:51.000Z
2021-10-21T14:13:46.000Z
#include <gsCore/gsTemplateTools.h> #include <gsElasticity/gsWriteParaviewMultiPhysics.h> #include <gsElasticity/gsWriteParaviewMultiPhysics.hpp> namespace gismo { TEMPLATE_INST void gsWriteParaviewMultiPhysics(std::map<std::string, const gsField<real_t>* > fields, std::string const & fn, unsigned npts, bool mesh, bool cnet); TEMPLATE_INST void gsWriteParaviewMultiPhysicsTimeStep(std::map<std::string, const gsField<real_t> *> fields, std::string const & fn, gsParaviewCollection & collection, int time, unsigned npts); TEMPLATE_INST void gsWriteParaviewMultiPhysicsSinglePatch(std::map<std::string,const gsField<real_t>* > fields, const unsigned patchNum, std::string const & fn, unsigned npts); TEMPLATE_INST void gsWriteParaviewMultiTPgrid(gsMatrix<real_t> const& points, std::map<std::string, gsMatrix<real_t> >& data, const gsVector<index_t> & np, std::string const & fn); }
39.413793
119
0.615923
[ "mesh" ]
47203438ee66dcdc2f7d8b35fcdab6da28e2ba1b
1,134
cc
C++
Question/幸运袋子.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
Question/幸运袋子.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
Question/幸运袋子.cc
lkimprove/Study_C
ee1153536f28e160d5daad4ddebaa547c3941ee7
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> using namespace std; int LuckyBag(vector<int>& bag, int n, int index = 0, int sum = 0, int multi = 1){ int count = 0; while(index < n){ //当前sum和multi sum += bag[index]; multi *= bag[index]; //满足条件,往下走 if(sum > multi){ count += 1 + LuckyBag(bag, n, index + 1, sum, multi); } //不满足条件,但当前为1,往下走可能会满足条件 else if(bag[index] == 1){ count += LuckyBag(bag, n, index + 1, sum, multi); } else{ break; } //恢复sum和multi sum -= bag[index]; multi /= bag[index]; //避免重复数字 while(index + 1 < n && bag[index] == bag[index + 1]){ index++; } index++; } return count; } int main(){ int n; while(cin >> n){ vector<int> bag(n, 0); for(int i = 0; i< n; i++){ cin >> bag[i]; } sort(bag.begin(), bag.end()); cout << LuckyBag(bag, n) << endl; } return 0; }
20.25
81
0.42328
[ "vector" ]
472f478c6ab2b9ddb85dd5c5e955b48f8f76e05f
2,623
cpp
C++
android-28/android/content/pm/InstrumentationInfo.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/content/pm/InstrumentationInfo.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/content/pm/InstrumentationInfo.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JArray.hpp" #include "../../os/Parcel.hpp" #include "../../../JString.hpp" #include "./InstrumentationInfo.hpp" namespace android::content::pm { // Fields JObject InstrumentationInfo::CREATOR() { return getStaticObjectField( "android.content.pm.InstrumentationInfo", "CREATOR", "Landroid/os/Parcelable$Creator;" ); } JString InstrumentationInfo::dataDir() { return getObjectField( "dataDir", "Ljava/lang/String;" ); } jboolean InstrumentationInfo::functionalTest() { return getField<jboolean>( "functionalTest" ); } jboolean InstrumentationInfo::handleProfiling() { return getField<jboolean>( "handleProfiling" ); } JString InstrumentationInfo::publicSourceDir() { return getObjectField( "publicSourceDir", "Ljava/lang/String;" ); } JString InstrumentationInfo::sourceDir() { return getObjectField( "sourceDir", "Ljava/lang/String;" ); } JArray InstrumentationInfo::splitNames() { return getObjectField( "splitNames", "[Ljava/lang/String;" ); } JArray InstrumentationInfo::splitPublicSourceDirs() { return getObjectField( "splitPublicSourceDirs", "[Ljava/lang/String;" ); } JArray InstrumentationInfo::splitSourceDirs() { return getObjectField( "splitSourceDirs", "[Ljava/lang/String;" ); } JString InstrumentationInfo::targetPackage() { return getObjectField( "targetPackage", "Ljava/lang/String;" ); } JString InstrumentationInfo::targetProcesses() { return getObjectField( "targetProcesses", "Ljava/lang/String;" ); } // QJniObject forward InstrumentationInfo::InstrumentationInfo(QJniObject obj) : android::content::pm::PackageItemInfo(obj) {} // Constructors InstrumentationInfo::InstrumentationInfo() : android::content::pm::PackageItemInfo( "android.content.pm.InstrumentationInfo", "()V" ) {} InstrumentationInfo::InstrumentationInfo(android::content::pm::InstrumentationInfo &arg0) : android::content::pm::PackageItemInfo( "android.content.pm.InstrumentationInfo", "(Landroid/content/pm/InstrumentationInfo;)V", arg0.object() ) {} // Methods jint InstrumentationInfo::describeContents() const { return callMethod<jint>( "describeContents", "()I" ); } JString InstrumentationInfo::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } void InstrumentationInfo::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod<void>( "writeToParcel", "(Landroid/os/Parcel;I)V", arg0.object(), arg1 ); } } // namespace android::content::pm
20.492188
105
0.695006
[ "object" ]
4731af5089ac3927fc942cc0a6a23d68ac069195
16,583
cpp
C++
head/contrib/llvm/lib/CodeGen/Analysis.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
17
2015-02-04T05:21:14.000Z
2021-05-30T21:03:48.000Z
head/contrib/llvm/lib/CodeGen/Analysis.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
head/contrib/llvm/lib/CodeGen/Analysis.cpp
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
3
2018-03-18T23:11:44.000Z
2019-09-05T11:47:19.000Z
//===-- Analysis.cpp - CodeGen LLVM IR Analysis Utilities -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines several CodeGen-specific LLVM IR analysis utilties. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Analysis.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MathExtras.h" #include "llvm/Target/TargetLowering.h" using namespace llvm; /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence /// of insertvalue or extractvalue indices that identify a member, return /// the linearized index of the start of the member. /// unsigned llvm::ComputeLinearIndex(Type *Ty, const unsigned *Indices, const unsigned *IndicesEnd, unsigned CurIndex) { // Base case: We're done. if (Indices && Indices == IndicesEnd) return CurIndex; // Given a struct type, recursively traverse the elements. if (StructType *STy = dyn_cast<StructType>(Ty)) { for (StructType::element_iterator EB = STy->element_begin(), EI = EB, EE = STy->element_end(); EI != EE; ++EI) { if (Indices && *Indices == unsigned(EI - EB)) return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex); CurIndex = ComputeLinearIndex(*EI, 0, 0, CurIndex); } return CurIndex; } // Given an array type, recursively traverse the elements. else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { Type *EltTy = ATy->getElementType(); for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) { if (Indices && *Indices == i) return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex); CurIndex = ComputeLinearIndex(EltTy, 0, 0, CurIndex); } return CurIndex; } // We haven't found the type we're looking for, so keep searching. return CurIndex + 1; } /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of /// EVTs that represent all the individual underlying /// non-aggregate types that comprise it. /// /// If Offsets is non-null, it points to a vector to be filled in /// with the in-memory offsets of each of the individual values. /// void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty, SmallVectorImpl<EVT> &ValueVTs, SmallVectorImpl<uint64_t> *Offsets, uint64_t StartingOffset) { // Given a struct type, recursively traverse the elements. if (StructType *STy = dyn_cast<StructType>(Ty)) { const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy); for (StructType::element_iterator EB = STy->element_begin(), EI = EB, EE = STy->element_end(); EI != EE; ++EI) ComputeValueVTs(TLI, *EI, ValueVTs, Offsets, StartingOffset + SL->getElementOffset(EI - EB)); return; } // Given an array type, recursively traverse the elements. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { Type *EltTy = ATy->getElementType(); uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy); for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets, StartingOffset + i * EltSize); return; } // Interpret void as zero return values. if (Ty->isVoidTy()) return; // Base case: we can get an EVT for this LLVM IR type. ValueVTs.push_back(TLI.getValueType(Ty)); if (Offsets) Offsets->push_back(StartingOffset); } /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V. GlobalVariable *llvm::ExtractTypeInfo(Value *V) { V = V->stripPointerCasts(); GlobalVariable *GV = dyn_cast<GlobalVariable>(V); if (GV && GV->getName() == "llvm.eh.catch.all.value") { assert(GV->hasInitializer() && "The EH catch-all value must have an initializer"); Value *Init = GV->getInitializer(); GV = dyn_cast<GlobalVariable>(Init); if (!GV) V = cast<ConstantPointerNull>(Init); } assert((GV || isa<ConstantPointerNull>(V)) && "TypeInfo must be a global variable or NULL"); return GV; } /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being /// processed uses a memory 'm' constraint. bool llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos, const TargetLowering &TLI) { for (unsigned i = 0, e = CInfos.size(); i != e; ++i) { InlineAsm::ConstraintInfo &CI = CInfos[i]; for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) { TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]); if (CType == TargetLowering::C_Memory) return true; } // Indirect operand accesses access memory. if (CI.isIndirect) return true; } return false; } /// getFCmpCondCode - Return the ISD condition code corresponding to /// the given LLVM IR floating-point condition code. This includes /// consideration of global floating-point math flags. /// ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) { switch (Pred) { case FCmpInst::FCMP_FALSE: return ISD::SETFALSE; case FCmpInst::FCMP_OEQ: return ISD::SETOEQ; case FCmpInst::FCMP_OGT: return ISD::SETOGT; case FCmpInst::FCMP_OGE: return ISD::SETOGE; case FCmpInst::FCMP_OLT: return ISD::SETOLT; case FCmpInst::FCMP_OLE: return ISD::SETOLE; case FCmpInst::FCMP_ONE: return ISD::SETONE; case FCmpInst::FCMP_ORD: return ISD::SETO; case FCmpInst::FCMP_UNO: return ISD::SETUO; case FCmpInst::FCMP_UEQ: return ISD::SETUEQ; case FCmpInst::FCMP_UGT: return ISD::SETUGT; case FCmpInst::FCMP_UGE: return ISD::SETUGE; case FCmpInst::FCMP_ULT: return ISD::SETULT; case FCmpInst::FCMP_ULE: return ISD::SETULE; case FCmpInst::FCMP_UNE: return ISD::SETUNE; case FCmpInst::FCMP_TRUE: return ISD::SETTRUE; default: llvm_unreachable("Invalid FCmp predicate opcode!"); } } ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) { switch (CC) { case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ; case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE; case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT; case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE; case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT; case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE; default: return CC; } } /// getICmpCondCode - Return the ISD condition code corresponding to /// the given LLVM IR integer condition code. /// ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) { switch (Pred) { case ICmpInst::ICMP_EQ: return ISD::SETEQ; case ICmpInst::ICMP_NE: return ISD::SETNE; case ICmpInst::ICMP_SLE: return ISD::SETLE; case ICmpInst::ICMP_ULE: return ISD::SETULE; case ICmpInst::ICMP_SGE: return ISD::SETGE; case ICmpInst::ICMP_UGE: return ISD::SETUGE; case ICmpInst::ICMP_SLT: return ISD::SETLT; case ICmpInst::ICMP_ULT: return ISD::SETULT; case ICmpInst::ICMP_SGT: return ISD::SETGT; case ICmpInst::ICMP_UGT: return ISD::SETUGT; default: llvm_unreachable("Invalid ICmp predicate opcode!"); } } static bool isNoopBitcast(Type *T1, Type *T2, const TargetLowering& TLI) { return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) || (isa<VectorType>(T1) && isa<VectorType>(T2) && TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2))); } /// sameNoopInput - Return true if V1 == V2, else if either V1 or V2 is a noop /// (i.e., lowers to no machine code), look through it (and any transitive noop /// operands to it) and check if it has the same noop input value. This is /// used to determine if a tail call can be formed. static bool sameNoopInput(const Value *V1, const Value *V2, SmallVectorImpl<unsigned> &Els1, SmallVectorImpl<unsigned> &Els2, const TargetLowering &TLI) { using std::swap; bool swapParity = false; bool equalEls = Els1 == Els2; while (true) { if ((equalEls && V1 == V2) || isa<UndefValue>(V1) || isa<UndefValue>(V2)) { if (swapParity) // Revert to original Els1 and Els2 to avoid confusing recursive calls swap(Els1, Els2); return true; } // Try to look through V1; if V1 is not an instruction, it can't be looked // through. const Instruction *I = dyn_cast<Instruction>(V1); const Value *NoopInput = 0; if (I != 0 && I->getNumOperands() > 0) { Value *Op = I->getOperand(0); if (isa<TruncInst>(I)) { // Look through truly no-op truncates. if (TLI.isTruncateFree(Op->getType(), I->getType())) NoopInput = Op; } else if (isa<BitCastInst>(I)) { // Look through truly no-op bitcasts. if (isNoopBitcast(Op->getType(), I->getType(), TLI)) NoopInput = Op; } else if (isa<GetElementPtrInst>(I)) { // Look through getelementptr if (cast<GetElementPtrInst>(I)->hasAllZeroIndices()) NoopInput = Op; } else if (isa<IntToPtrInst>(I)) { // Look through inttoptr. // Make sure this isn't a truncating or extending cast. We could // support this eventually, but don't bother for now. if (!isa<VectorType>(I->getType()) && TLI.getPointerTy().getSizeInBits() == cast<IntegerType>(Op->getType())->getBitWidth()) NoopInput = Op; } else if (isa<PtrToIntInst>(I)) { // Look through ptrtoint. // Make sure this isn't a truncating or extending cast. We could // support this eventually, but don't bother for now. if (!isa<VectorType>(I->getType()) && TLI.getPointerTy().getSizeInBits() == cast<IntegerType>(I->getType())->getBitWidth()) NoopInput = Op; } else if (isa<CallInst>(I)) { // Look through call for (User::const_op_iterator i = I->op_begin(), // Skip Callee e = I->op_end() - 1; i != e; ++i) { unsigned attrInd = i - I->op_begin() + 1; if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) && isNoopBitcast((*i)->getType(), I->getType(), TLI)) { NoopInput = *i; break; } } } else if (isa<InvokeInst>(I)) { // Look through invoke for (User::const_op_iterator i = I->op_begin(), // Skip BB, BB, Callee e = I->op_end() - 3; i != e; ++i) { unsigned attrInd = i - I->op_begin() + 1; if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) && isNoopBitcast((*i)->getType(), I->getType(), TLI)) { NoopInput = *i; break; } } } } if (NoopInput) { V1 = NoopInput; continue; } // If we already swapped, avoid infinite loop if (swapParity) break; // Otherwise, swap V1<->V2, Els1<->Els2 swap(V1, V2); swap(Els1, Els2); swapParity = !swapParity; } for (unsigned n = 0; n < 2; ++n) { if (isa<InsertValueInst>(V1)) { if (isa<StructType>(V1->getType())) { // Look through insertvalue unsigned i, e; for (i = 0, e = cast<StructType>(V1->getType())->getNumElements(); i != e; ++i) { const Value *InScalar = FindInsertedValue(const_cast<Value*>(V1), i); if (InScalar == 0) break; Els1.push_back(i); if (!sameNoopInput(InScalar, V2, Els1, Els2, TLI)) { Els1.pop_back(); break; } Els1.pop_back(); } if (i == e) { if (swapParity) swap(Els1, Els2); return true; } } } else if (!Els1.empty() && isa<ExtractValueInst>(V1)) { const ExtractValueInst *EVI = cast<ExtractValueInst>(V1); unsigned i = Els1.back(); // If the scalar value being inserted is an extractvalue of the right // index from the call, then everything is good. if (isa<StructType>(EVI->getOperand(0)->getType()) && EVI->getNumIndices() == 1 && EVI->getIndices()[0] == i) { // Look through extractvalue Els1.pop_back(); if (sameNoopInput(EVI->getOperand(0), V2, Els1, Els2, TLI)) { Els1.push_back(i); if (swapParity) swap(Els1, Els2); return true; } Els1.push_back(i); } } swap(V1, V2); swap(Els1, Els2); swapParity = !swapParity; } if (swapParity) swap(Els1, Els2); return false; } /// Test if the given instruction is in a position to be optimized /// with a tail-call. This roughly means that it's in a block with /// a return and there's nothing that needs to be scheduled /// between it and the return. /// /// This function only tests target-independent requirements. bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetLowering &TLI) { const Instruction *I = CS.getInstruction(); const BasicBlock *ExitBB = I->getParent(); const TerminatorInst *Term = ExitBB->getTerminator(); const ReturnInst *Ret = dyn_cast<ReturnInst>(Term); // The block must end in a return statement or unreachable. // // FIXME: Decline tailcall if it's not guaranteed and if the block ends in // an unreachable, for now. The way tailcall optimization is currently // implemented means it will add an epilogue followed by a jump. That is // not profitable. Also, if the callee is a special function (e.g. // longjmp on x86), it can end up causing miscompilation that has not // been fully understood. if (!Ret && (!TLI.getTargetMachine().Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false; // If I will have a chain, make sure no other instruction that will have a // chain interposes between I and the return. if (I->mayHaveSideEffects() || I->mayReadFromMemory() || !isSafeToSpeculativelyExecute(I)) for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ; --BBI) { if (&*BBI == I) break; // Debug info intrinsics do not get in the way of tail call optimization. if (isa<DbgInfoIntrinsic>(BBI)) continue; if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() || !isSafeToSpeculativelyExecute(BBI)) return false; } // If the block ends with a void return or unreachable, it doesn't matter // what the call's return type is. if (!Ret || Ret->getNumOperands() == 0) return true; // If the return value is undef, it doesn't matter what the call's // return type is. if (isa<UndefValue>(Ret->getOperand(0))) return true; // Conservatively require the attributes of the call to match those of // the return. Ignore noalias because it doesn't affect the call sequence. const Function *F = ExitBB->getParent(); AttributeSet CallerAttrs = F->getAttributes(); if (AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex). removeAttribute(Attribute::NoAlias) != AttrBuilder(CallerAttrs, AttributeSet::ReturnIndex). removeAttribute(Attribute::NoAlias)) return false; // It's not safe to eliminate the sign / zero extension of the return value. if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) return false; // Otherwise, make sure the return value and I have the same value SmallVector<unsigned, 4> Els1, Els2; return sameNoopInput(Ret->getOperand(0), I, Els1, Els2, TLI); }
38.655012
80
0.614244
[ "vector" ]
473f03163c1cd6705239a34aa405c515319a27b3
11,095
cpp
C++
tg3_ctrl.cpp
delphinus1024/tg3_ctrl
5c6f78938cab00c1fd89412d7a7d3ac7771b3a6e
[ "MIT" ]
2
2020-06-03T18:20:48.000Z
2021-01-23T13:21:41.000Z
tg3_ctrl.cpp
delphinus1024/tg3_ctrl
5c6f78938cab00c1fd89412d7a7d3ac7771b3a6e
[ "MIT" ]
null
null
null
tg3_ctrl.cpp
delphinus1024/tg3_ctrl
5c6f78938cab00c1fd89412d7a7d3ac7771b3a6e
[ "MIT" ]
1
2020-06-03T18:21:44.000Z
2020-06-03T18:21:44.000Z
/* The MIT License (MIT) Copyright (c) 2016 delphinus1024 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <sstream> #include <iostream> #include <string> #include <vector> #include <utility> // to use "swap" under C++11 or after #include <windows.h> #include <time.h> #include <winsock.h> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <opencv2/opencv.hpp> #include "analyze_rtp.h" #define TG_IP ("192.168.0.10") // tg3 IP address #define BUFFSIZE (16536) enum { FLG_GET,FLG_POST }; // liveview flag boost::mutex mtx_liveview; bool on_liveview = false; // mtx_liveview protected analyze_rtp an; // focus flag boost::mutex mtx_dofocus; bool dofocus = false; // mtx_dofocus protected int focusx,focusy; char szBuff[BUFFSIZE]; int do_transaction(int flag,const char *req,const char *data,char *resp,int resplen) { std::string get_template = std::string( " HTTP/1.1\r\n"\ "Host: 192.168.0.10\r\n"\ "Connection: Keep-Alive\r\n"\ "User-Agent: OI.Share v2\r\n"\ "\r\n"); std::string post_template = std::string( " HTTP/1.1\r\n"\ "Content-Length: "); std::string post_template2 = std::string( "\r\n"\ "Content-Type: text/plain; charset=ISO-8859-1\r\n"\ "Host: 192.168.0.10\r\n"\ "Connection: Keep-Alive\r\n"\ "User-Agent: OI.Share v2\r\n"\ "\r\n"); WSADATA wsaData; SOCKET sock = INVALID_SOCKET; int nRet; SOCKADDR_IN sockaddr; unsigned short nPort = 80; int offset; int sentnum; int restnum; int len; char szBuff[BUFFSIZE]; std::ostringstream os; os << strlen(data); std::string cmdstr = std::string(flag == FLG_GET ? ("GET ") : ("POST ")) + std::string(req) + (flag == FLG_GET ? get_template : (post_template + os.str() + post_template2)) + std::string(data); std::cout << "REQ:" << std::endl << cmdstr << std::flush << std::endl << std::endl; for(int i = 0;i < BUFFSIZE;++i) szBuff[i] = 0; WSAStartup(MAKEWORD(1, 1), &wsaData); memset(&sockaddr, 0, sizeof(sockaddr)); sockaddr.sin_family = AF_INET; sockaddr.sin_addr.s_addr = inet_addr(TG_IP); sockaddr.sin_port = htons(nPort); sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sock == INVALID_SOCKET) { std::cerr << "Error: invalid socket." << std::endl; return -1; } nRet = connect(sock, (const SOCKADDR*)&sockaddr, sizeof(sockaddr)); if (nRet != 0) { std::cerr << "Error: connect failed." << std::endl; return -2; } offset = 0; const char *cmd = cmdstr.c_str(); restnum = (int)strlen(cmd); while (restnum > 0) { sentnum = send(sock, &cmd[offset], restnum, 0); if (sentnum == SOCKET_ERROR) { return -3; } offset += sentnum; restnum -= sentnum; } resp[0] = 0; while ( (len = recv(sock, szBuff, sizeof(szBuff), 0) ) > 0) { strcat(resp,szBuff); } closesocket(sock); WSACleanup(); std::cout << "RESP:" << std::endl << resp << std::flush << std::endl << std::endl; return 0; } void UCP_Liveview(const int port) { WSAData wsaData; fd_set fds, readfds; struct timeval tv; SOCKET sock; struct sockaddr_in addr; unsigned char buf[16536]; WSAStartup(MAKEWORD(2,0), &wsaData); sock = socket(AF_INET, SOCK_DGRAM, 0); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.S_un.S_addr = INADDR_ANY; bind(sock, (struct sockaddr *)&addr, sizeof(addr)); FD_ZERO(&readfds); FD_SET(sock, &readfds); tv.tv_sec = 2; tv.tv_usec = 0; std::cout << "Liveview Started===========================" << std::flush; int index = 0; bool on_xfer = false; std::cout << std::hex << std::showbase; for(int i = 0;;++i) { { boost::mutex::scoped_lock lock(mtx_liveview); if(!on_liveview) break; } memcpy(&fds, &readfds, sizeof(fd_set)); int n = select(0, &fds, NULL, NULL, &tv); if (n == 0) { std::cout << "timeout" << std::endl; } else if (FD_ISSET(sock, &fds)) { memset(buf, 0, sizeof(buf)); int ret = recv(sock, (char*)buf, sizeof(buf), 0); if(ret < 0) { std::cout << "Error: recv :" << WSAGetLastError() << std::endl; break; } else { unsigned long head = an.check_packet_id(buf); switch(head) { case PACKETID_FIRST: if(!an.check_queue_full()) { if(an.store_first_packet(buf,ret)) { an.make_jpg_data_first(buf,ret); on_xfer = true; } else on_xfer = false; } else { on_xfer = false; } break; case PACKETID_CONT: if(on_xfer) { an.store_cont_packet(buf,ret); an.make_jpg_data_cont(buf,ret); } break; case PACKETID_LAST: if(on_xfer) { an.store_last_packet(buf,ret); an.make_jpg_data_cont(buf,ret); an.update_queue(); on_xfer = false; } break; default: std::cout << "Error: Invalid packet:" << head<< std::endl; } } } } std::cout << std::endl; closesocket(sock); WSACleanup(); std::cout << "Liveview Exit" << std::endl; } void on_mouse_callback(int event, int x, int y, int flags, void* param){ switch (event){ case cv::EVENT_LBUTTONDOWN: { focusx = x; focusy = y; boost::mutex::scoped_lock lock(mtx_dofocus); dofocus = true; } std::cout << std::dec << std::showbase; std::cout << "EVENT_LBUTTONDOWN (" << x << "," << y << ")" << std::endl; std::cout << std::hex << std::showbase; break; } } int main() { do_transaction(FLG_GET,"/switch_cammode.cgi?mode=rec&lvqty=0640x0480","",szBuff,sizeof(szBuff)); //do_transaction(FLG_GET,"/switch_cammode.cgi?mode=rec&lvqty=0320x0240","",szBuff,sizeof(szBuff)); do_transaction(FLG_POST,"/set_camprop.cgi?com=set&propname=takemode","<?xml version=\"1.0\" ?><set><value>A</value></set>\r\n",szBuff,sizeof(szBuff)); do_transaction(FLG_GET,"/get_camprop.cgi?com=desc&propname=takemode","",szBuff,sizeof(szBuff)); { boost::mutex::scoped_lock lock(mtx_liveview); on_liveview = true; } boost::thread ucp_liveview(boost::bind(&UCP_Liveview,37789)); do_transaction(FLG_GET,"/exec_takemisc.cgi?com=startliveview&port=37789","",szBuff,sizeof(szBuff)); cv::namedWindow("liveview", cv::WINDOW_NORMAL); cv::setMouseCallback("liveview", on_mouse_callback); clock_t start = clock(); while(1) { if(an.check_jpg_available()) { // frame ready //an.save_jpg(); uchar* jpgpt; int len; jpgpt = an.get_jpg_buf(len); if(!jpgpt) { std::cerr << "Error: null jpg data" << std::endl; continue; } std::vector<uchar> ibuff; for(int i = 0;i < len;++i) ibuff.push_back(jpgpt[i]); cv::Mat decodedImage = cv::imdecode( cv::Mat(ibuff) , CV_LOAD_IMAGE_COLOR); if((decodedImage.size().width > 0) && (decodedImage.size().height > 0)) cv::imshow("liveview", decodedImage); an.pop_queue(); } /* clock_t end = clock(); if(((double)(end - start) / CLOCKS_PER_SEC) > 4) break; */ int key = cv::waitKey(33); if(key == 27) break; // shoot switch(key) { case 0xd: // take picture do_transaction(FLG_GET,"/exec_takemotion.cgi?com=starttake","",szBuff,sizeof(szBuff)); break; } // focus bool dofocus_local = false; int focusx_local,focusy_local; { boost::mutex::scoped_lock lock(mtx_dofocus); if(dofocus) { dofocus_local = true; focusx_local = focusx; focusy_local = focusy; dofocus = false; } } if(dofocus_local) { char cmd[128]; sprintf(cmd,"/exec_takemotion.cgi?com=assignafframe&point=%04dx%04d",focusx_local,focusy_local); std::cout << "cmd=" << cmd << std::endl << std::flush; do_transaction(FLG_GET,cmd,"",szBuff,sizeof(szBuff)); } } //Sleep(10000); /* do_transaction(FLG_GET,"/exec_takemotion.cgi?com=assignafframe&point=0064x0139","",szBuff,sizeof(szBuff)); Sleep(1000); do_transaction(FLG_GET,"/exec_takemotion.cgi?com=starttake","",szBuff,sizeof(szBuff)); Sleep(1000); do_transaction(FLG_GET,"/exec_takemotion.cgi?com=assignafframe&point=0233x0039","",szBuff,sizeof(szBuff)); Sleep(1000); do_transaction(FLG_GET,"/exec_takemotion.cgi?com=starttake","",szBuff,sizeof(szBuff)); Sleep(1000); */ //============================== do_transaction(FLG_GET,"/exec_takemisc.cgi?com=stopliveview","",szBuff,sizeof(szBuff)); { boost::mutex::scoped_lock lock(mtx_liveview); on_liveview = false; } ucp_liveview.join(); ERROR_EXIT: return 0; }
30.564738
154
0.546913
[ "vector" ]
474228069f3e943d21b76b5680b2103397caa44b
989
cpp
C++
LeetCode/Graph/Graph Algos/MST/prim.cpp
cheshtaaagarrwal/Placement-Preparation-Problems
456c7d69e5d9efbf029591c370520f0d1f558089
[ "MIT" ]
1
2020-10-02T20:32:11.000Z
2020-10-02T20:32:11.000Z
LeetCode/Graph/Graph Algos/MST/prim.cpp
cheshtaaagarrwal/Placement-Preparation-Problems
456c7d69e5d9efbf029591c370520f0d1f558089
[ "MIT" ]
2
2020-10-02T19:01:31.000Z
2020-10-02T19:03:13.000Z
LeetCode/Graph/Graph Algos/MST/prim.cpp
cheshtaaagarrwal/Placement-Preparation-Problems
456c7d69e5d9efbf029591c370520f0d1f558089
[ "MIT" ]
4
2020-10-02T19:13:14.000Z
2020-10-24T04:43:09.000Z
// Prim code // LOGIC : // 1. builds the spanning tree by ADDING VERTEX one by one into a growing spanning tree // 2. Select the cheapest vertex that is connected to the growing spanning tree and is // not in the growing spanning tree and add it into the growing spanning tree (GREEDY) // 3. add it to the growing spanning tree. (VERTEX WHICH DON'T FORM A CYCLE) #include <queue> #include <iostream> #include <vector> using namespace std; vector <pair <int, int> > graph[101]; vector <bool> visited(101, false); int prim(int src) { priority_queue <pair <int, int>, vector <pair <int, int> >, greater <pair <int, int> > > q; int ans = 0; q.push(make_pair(0, src)); while (!q.empty()) { int u = q.top().second; int val = q.top().first; q.pop(); if (visited[u]) { continue; } visited[u] = 1; ans += val; for (int i = 0; i < graph[u].size(); i++) { int v = graph[u][i].second; if (visited[v] == false) { q.push(graph[u][i]); } } } return ans; }
26.026316
92
0.629929
[ "vector" ]
4743a50f1b178e1694d3d9f040f88f27e403ded7
544
hpp
C++
libvermilion/core/src/Pipeline.hpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
libvermilion/core/src/Pipeline.hpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
libvermilion/core/src/Pipeline.hpp
Jojojoppe/vermilion
2bfe545c5f2c02e11d96940c191bac6f6c491843
[ "Zlib", "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
#pragma once #include <vermilion/vermilion.hpp> #include <vermilion/logger.hpp> #include <memory> #include <vector> namespace Vermilion{ namespace Core{ class PipelineLayout{ public: ~PipelineLayout() = default; }; class Pipeline{ public: ~Pipeline() = default; virtual void setViewPort(unsigned int width, unsigned int height, unsigned int x=0, unsigned int y=0){}; virtual void setScissor(unsigned int width, unsigned int height, unsigned int x=0, unsigned int y=0){}; }; class Binding{ public: ~Binding() = default; }; }}
18.758621
106
0.722426
[ "vector" ]
4747f089c8d0afb14e2c7037fc77e301c3c16bb4
6,032
cpp
C++
lib/Utilities/AAvsOracle.cpp
sgh185/SCAF
715a5e50fca0fbff2dc8e3cddafa2d71ae7aa018
[ "MIT" ]
22
2020-08-01T18:09:11.000Z
2022-03-22T08:56:05.000Z
lib/Utilities/AAvsOracle.cpp
sgh185/SCAF
715a5e50fca0fbff2dc8e3cddafa2d71ae7aa018
[ "MIT" ]
4
2021-02-23T01:27:53.000Z
2021-04-19T22:11:39.000Z
lib/Utilities/AAvsOracle.cpp
sgh185/SCAF
715a5e50fca0fbff2dc8e3cddafa2d71ae7aa018
[ "MIT" ]
4
2020-09-17T17:24:22.000Z
2022-03-22T09:12:19.000Z
#include "AAvsOracle.h" #include "llvm/IR/Constants.h" #include "scaf/Utilities/CallSiteFactory.h" #include <cstdio> namespace liberty { using namespace llvm; char AAvsOracle_EarlyHelper::ID = 0; char AAvsOracle::ID = 0; namespace { static RegisterPass<AAvsOracle_EarlyHelper> X("aa-vs-oracle-early", "Early helper for AA-vs-Oracle"); static RegisterPass<AAvsOracle> Y("aa-vs-oracle", "Compare ::Alias-Analysis to Oracle"); } // namespace bool AAvsOracle_EarlyHelper::gather(Function *oracle, Truths &collection, Module &mod) { bool modified = false; const DataLayout &td = mod.getDataLayout(); // we modify the use list, so // make a tmp copy. typedef std::vector<Value *> Values; Values tmp(oracle->user_begin(), oracle->user_end()); for (Values::iterator i = tmp.begin(), e = tmp.end(); i != e; ++i) { CallSite cs = getCallSite(*i); if (!cs.getInstruction()) continue; const DebugLoc &location = cs.getInstruction()->getDebugLoc(); std::string desc; { Value *description = cs.getArgument(0); if (User *udesc = dyn_cast<User>(description)) if (GlobalVariable *gv = dyn_cast<GlobalVariable>(udesc->getOperand(0))) if (ConstantDataArray *carr = dyn_cast<ConstantDataArray>(gv->getInitializer())) desc = carr->getAsString(); } Value *ptr1 = cs.getArgument(1); Value *ptr2 = cs.getArgument(2); PointerType *pty1 = dyn_cast<PointerType>(ptr1->getType()), *pty2 = dyn_cast<PointerType>(ptr2->getType()); if (!pty1) { fprintf(stderr, "Line %d \"%s\": arg 2 is not a pointer\n", location.getLine(), desc.c_str()); continue; } if (!pty2) { fprintf(stderr, "Line %d \"%s\": arg 3 is not a pointer\n", location.getLine(), desc.c_str()); continue; } const unsigned s1 = td.getTypeSizeInBits(pty1->getElementType()) / 8, s2 = td.getTypeSizeInBits(pty2->getElementType()) / 8; collection.push_back(Truth()); collection.back().desc = desc; collection.back().line = location.getLine(); collection.back().ptr1 = ptr1; collection.back().s1 = s1; collection.back().ptr2 = ptr2; collection.back().s2 = s2; cs.getInstruction()->eraseFromParent(); modified = true; } if (oracle->use_empty()) { oracle->eraseFromParent(); modified = true; } return modified; } bool AAvsOracle_EarlyHelper::runOnModule(Module &mod) { bool modified = false; Function *no_alias_oracle = mod.getFunction("no_alias"); if (no_alias_oracle) modified |= gather(no_alias_oracle, no, mod); Function *may_alias_oracle = mod.getFunction("may_alias"); if (may_alias_oracle) modified |= gather(may_alias_oracle, may, mod); Function *must_alias_oracle = mod.getFunction("must_alias"); if (must_alias_oracle) modified |= gather(must_alias_oracle, must, mod); return modified; } void AAvsOracle::test(unsigned truth, ATI begin, ATI end, unsigned *stat_row) { AAResultsWrapperPass &aliasWrap = getAnalysis<AAResultsWrapperPass>(); AliasAnalysis &alias = aliasWrap.getAAResults(); for (ATI i = begin; i != end; ++i) { switch (alias.alias(i->ptr1, i->s1, i->ptr2, i->s2)) { case NoAlias: ++stat_row[AA_NO]; if (truth == AA_MAY || truth == AA_MUST) { fprintf(stderr, "ERROR: Line %d \"%s\": Oracle says May/Must, but AA reports " "No Alias.\n", i->line, i->desc.c_str()); } break; case MayAlias: case PartialAlias: ++stat_row[AA_MAY]; if (truth != AA_MAY) { fprintf( stderr, "Imprecise: Line %d \"%s\": Oracle=%d, but AA reports May-Alias.\n", i->line, i->desc.c_str(), truth); } break; case MustAlias: ++stat_row[AA_MUST]; if (truth != AA_MUST) { fprintf(stderr, "Imprecise: Line %d \"%s\": Oracle=%d, but AA reports " "Must-Alias.\n", i->line, i->desc.c_str(), truth); } break; } } } bool AAvsOracle::runOnModule(Module &mod) { fprintf(stderr, "AA vs Oracle:\n"); unsigned stats[3][3] = {{0u}}; AAvsOracle_EarlyHelper &helper = getAnalysis<AAvsOracle_EarlyHelper>(); // Find our oracle functions: test(AA_NO, helper.no_alias_begin(), helper.no_alias_end(), stats[AA_NO]); test(AA_MAY, helper.may_alias_begin(), helper.may_alias_end(), stats[AA_MAY]); test(AA_MUST, helper.must_alias_begin(), helper.must_alias_end(), stats[AA_MUST]); fprintf(stderr, "\n"); fprintf(stderr, " AA-No AA-May AA-Must\n"); fprintf(stderr, "Oracle-No : %3d %3d %3d\n", stats[AA_NO][AA_NO], stats[AA_NO][AA_MAY], stats[AA_NO][AA_MUST]); fprintf(stderr, "Oracle-May : %3d %3d %3d\n", stats[AA_MAY][AA_NO], stats[AA_MAY][AA_MAY], stats[AA_MAY][AA_MUST]); fprintf(stderr, "Oracle-Must: %3d %3d %3d\n", stats[AA_MUST][AA_NO], stats[AA_MUST][AA_MAY], stats[AA_MUST][AA_MUST]); fprintf(stderr, "\n"); unsigned precise = stats[AA_NO][AA_NO] + stats[AA_MAY][AA_MAY] + stats[AA_MUST][AA_MUST]; unsigned conservative = stats[AA_NO][AA_MAY] + stats[AA_NO][AA_MUST] + stats[AA_MAY][AA_MUST] + stats[AA_MUST][AA_MAY]; unsigned errors = stats[AA_MAY][AA_NO] + stats[AA_MUST][AA_NO]; unsigned total = precise + conservative + errors; fprintf(stderr, "Precise answers : %d/%d\t\t%.1f%%\n", precise, total, 100 * precise / (float)total); fprintf(stderr, "Conservative answers: %d/%d\t\t%.1f%%\n", conservative, total, 100 * conservative / (float)total); fprintf(stderr, "Erroneous answers : %d/%d\t\t%.1f%%\n", errors, total, 100 * errors / (float)total); return false; } } // namespace liberty
32.961749
80
0.602288
[ "vector", "3d" ]
4748e9dae1a788cd2c68222a540d956435028595
13,131
cpp
C++
test/http.cpp
MapQuest/avecado
947142e198e08411838bc2156bbd504dacf4acf8
[ "BSD-2-Clause" ]
19
2015-01-08T23:12:51.000Z
2020-06-23T20:00:23.000Z
test/http.cpp
MapQuest/avecado
947142e198e08411838bc2156bbd504dacf4acf8
[ "BSD-2-Clause" ]
15
2015-01-07T12:50:42.000Z
2021-02-18T20:51:27.000Z
test/http.cpp
MapQuest/avecado
947142e198e08411838bc2156bbd504dacf4acf8
[ "BSD-2-Clause" ]
11
2015-01-18T20:53:10.000Z
2021-04-18T07:33:45.000Z
#include "config.h" #include "common.hpp" #include "fetcher_io.hpp" #include "tilejson.hpp" #include "fetch/http.hpp" #include "logging/logger.hpp" #include "http_server/server.hpp" #include "http_server/mapnik_handler_factory.hpp" #include "vector_tile.pb.h" #include <google/protobuf/io/zero_copy_stream_impl.h> #include <boost/property_tree/ptree.hpp> #include <boost/make_shared.hpp> #include <boost/format.hpp> #include <boost/algorithm/string.hpp> #include <mapnik/datasource_cache.hpp> #include <iostream> #include <curl/curl.h> namespace bpt = boost::property_tree; using http::server3::request; using http::server3::reply; using http::server3::server_options; using http::server3::handler_factory; using http::server3::request_handler; using http::server3::mapnik_server_options; using http::server3::mapnik_handler_factory; namespace { server_options default_options(mapnik_server_options &map_opts) { server_options options; options.thread_hint = 1; options.port = ""; options.factory.reset(new mapnik_handler_factory(map_opts)); return options; } mapnik_server_options default_mapnik_options(const std::string &map_file, int compression_level) { mapnik_server_options options; options.path_multiplier = 16; options.buffer_size = 0; options.scale_factor = 1.0; options.offset_x = 0; options.offset_y = 0; options.tolerance = 1; options.image_format = "jpeg"; options.scaling_method = mapnik::SCALING_NEAR; options.scale_denominator = 0.0; options.map_file = map_file; options.max_age = 60; options.compression_level = compression_level; return options; } struct server_guard { mapnik_server_options map_opt; server_options srv_opt; http::server3::server server; std::string port; server_guard(const std::string &map_xml, int compression_level = -1) : map_opt(default_mapnik_options(map_xml, compression_level)) , srv_opt(default_options(map_opt)) , server("localhost", srv_opt) , port(server.port()) { server.run(false); } ~server_guard() { server.stop(); } std::string base_url() { return (boost::format("http://localhost:%1%") % port).str(); } }; // variant of the server guard which takes a custom handler factory struct server_guard2 { boost::shared_ptr<handler_factory> factory; server_options srv_opt; http::server3::server server; std::string port; server_guard2(boost::shared_ptr<handler_factory> f) : factory(f) , srv_opt(mk_options(factory)) , server("localhost", srv_opt) , port(server.port()) { server.run(false); } ~server_guard2() { server.stop(); } std::string base_url() { return (boost::format("http://localhost:%1%") % port).str(); } static server_options mk_options(boost::shared_ptr<handler_factory> f) { server_options opts; opts.thread_hint = 1; opts.port = ""; opts.factory = f; return opts; } }; void test_fetch_empty() { server_guard guard("test/empty_map_file.xml"); avecado::fetch::http fetch(guard.base_url(), "pbf"); avecado::fetch_response response(fetch(avecado::request(0, 0, 0)).get()); test::assert_equal<bool>(response.is_left(), true, "should fetch tile OK"); test::assert_equal<int>(response.left()->mapnik_tile().layers_size(), 0, "should have no layers"); } void test_fetch_single_line() { server_guard guard("test/single_line.xml"); avecado::fetch::http fetch(guard.base_url(), "pbf"); avecado::fetch_response response(fetch(avecado::request(0, 0, 0)).get()); test::assert_equal<bool>(response.is_left(), true, "should fetch tile OK"); test::assert_equal<int>(response.left()->mapnik_tile().layers_size(), 1, "should have one layer"); } void assert_is_error(avecado::fetch::http &fetch, int z, int x, int y, avecado::fetch_status status) { avecado::fetch_response response(fetch(avecado::request(z, x, y)).get()); test::assert_equal<bool>(response.is_right(), true, (boost::format("(%1%, %2%, %3%): response should be failure") % z % x % y).str()); test::assert_equal<avecado::fetch_status>(response.right().status, status, (boost::format("(%1%, %2%, %3%): response status is not what was expected") % z % x % y).str()); } void test_fetch_error_coordinates() { using avecado::fetch_status; server_guard guard("test/empty_map_file.xml"); avecado::fetch::http fetch(guard.base_url(), "pbf"); assert_is_error(fetch, -1, 0, 0, fetch_status::not_found); assert_is_error(fetch, 31, 0, 0, fetch_status::not_found); assert_is_error(fetch, 0, 0, 1, fetch_status::not_found); assert_is_error(fetch, 0, 1, 0, fetch_status::not_found); assert_is_error(fetch, 0, 0, -1, fetch_status::not_found); assert_is_error(fetch, 0, -1, 0, fetch_status::not_found); } void test_fetch_error_extension() { using avecado::fetch_status; server_guard guard("test/empty_map_file.xml"); avecado::fetch::http fetch(guard.base_url(), "gif"); assert_is_error(fetch, 0, 0, 0, fetch_status::not_found); } void test_fetch_error_path_segments() { using avecado::fetch_status; server_guard guard("test/empty_map_file.xml"); avecado::fetch::http fetch(guard.base_url(), "/0.pbf"); assert_is_error(fetch, 0, 0, 0, fetch_status::not_found); } void test_fetch_error_non_numeric() { using avecado::fetch_status; server_guard guard("test/empty_map_file.xml"); std::vector<std::string> patterns; patterns.push_back((boost::format("%1%/a/b/c.pbf") % guard.base_url()).str()); avecado::fetch::http fetch(std::move(patterns)); assert_is_error(fetch, 0, 0, 0, fetch_status::not_found); } void test_no_url_patterns_is_error() { std::vector<std::string> patterns; bool threw = false; avecado::fetch::http fetch(std::move(patterns)); try { avecado::fetch_response response(fetch(avecado::request(0, 0, 0)).get()); } catch (...) { threw = true; } test::assert_equal<bool>(threw, true, "Should have thrown exception when patterns was empty."); } void test_fetcher_io() { using avecado::fetch_status; test::assert_equal<std::string>((boost::format("%1%") % fetch_status::not_modified).str(), "Not Modified"); test::assert_equal<std::string>((boost::format("%1%") % fetch_status::bad_request).str(), "Bad Request"); test::assert_equal<std::string>((boost::format("%1%") % fetch_status::not_found).str(), "Not Found"); test::assert_equal<std::string>((boost::format("%1%") % fetch_status::server_error).str(), "Server Error"); test::assert_equal<std::string>((boost::format("%1%") % fetch_status::not_implemented).str(), "Not Implemented"); } void test_fetch_tilejson() { using avecado::fetch_status; server_guard guard("test/single_poly.xml"); bpt::ptree tilejson = avecado::tilejson( (boost::format("%1%/tile.json") % guard.base_url()).str()); } size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata) { std::stringstream *stream = static_cast<std::stringstream*>(userdata); size_t total_bytes = size * nmemb; stream->write(ptr, total_bytes); return stream->good() ? total_bytes : 0; } #define CURL_SETOPT(curl, opt, arg) { \ CURLcode res = curl_easy_setopt((curl), (opt), (arg)); \ if (res != CURLE_OK) { \ throw std::runtime_error("Unable to set cURL option " #opt); \ } \ } void test_tile_is_compressed() { server_guard guard("test/single_line.xml", 9); std::string uri = (boost::format("%1%/0/0/0.pbf") % guard.base_url()).str(); std::stringstream stream; CURL *curl = curl_easy_init(); CURL_SETOPT(curl, CURLOPT_URL, uri.c_str()); CURL_SETOPT(curl, CURLOPT_WRITEFUNCTION, write_callback); CURL_SETOPT(curl, CURLOPT_WRITEDATA, &stream); CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { throw std::runtime_error("cURL operation failed"); } curl_easy_cleanup(curl); std::string data = stream.str(); test::assert_greater_or_equal<size_t>(data.size(), 2, "tile size"); // see https://tools.ietf.org/html/rfc1952#page-6 for header magic values test::assert_equal<uint32_t>(uint8_t(data[0]), 0x1f, "gzip header magic ID1"); test::assert_equal<uint32_t>(uint8_t(data[1]), 0x8b, "gzip header magic ID2"); test::assert_equal<uint32_t>(uint8_t(data[2]), 0x08, "gzip compression method = deflate"); } void test_tile_is_not_compressed() { // check that when the compression level is set to zero, the tile is not // compressed and is just the raw PBF. server_guard guard("test/single_line.xml", 0); std::string uri = (boost::format("%1%/0/0/0.pbf") % guard.base_url()).str(); std::stringstream stream; CURL *curl = curl_easy_init(); CURL_SETOPT(curl, CURLOPT_URL, uri.c_str()); CURL_SETOPT(curl, CURLOPT_WRITEFUNCTION, write_callback); CURL_SETOPT(curl, CURLOPT_WRITEDATA, &stream); CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { throw std::runtime_error("cURL operation failed"); } curl_easy_cleanup(curl); // note: this deliberately doesn't use the functions defined on avecado::tile // because it needs to avoid any automatic ungzipping. stream.seekp(0); google::protobuf::io::IstreamInputStream gstream(&stream); vector_tile::Tile tile; bool read_ok = tile.ParseFromZeroCopyStream(&gstream); test::assert_equal<bool>(read_ok, true, "tile was plain PBF"); } struct cache_header_checker_handler : public request_handler { virtual ~cache_header_checker_handler() {} // returns 304 if the ETag header is present, otherwise a 500. this // is used to check that the HTTP system is correctly sending the // cache headers. virtual void handle_request(const request &req, reply &rep) { rep = reply::stock_reply(reply::internal_server_error); for (const auto &header : req.headers) { if (boost::iequals(header.name, "If-None-Match") && (header.value == "\"foo\"")) { rep = reply::stock_reply(reply::not_modified); break; } else if (boost::iequals(header.name, "If-Modified-Since") && (header.value == "Wed, 13 May 2015 14:35:10 GMT")) { rep = reply::stock_reply(reply::not_modified); break; } } } }; struct cache_header_checker_factory : public handler_factory { virtual ~cache_header_checker_factory() {} virtual void thread_setup(boost::thread_specific_ptr<request_handler> &tss, const std::string &) { tss.reset(new cache_header_checker_handler); } }; void test_http_etag() { auto factory = boost::make_shared<cache_header_checker_factory>(); server_guard2 server(factory); avecado::fetch::http fetch(server.base_url(), "png"); auto req = avecado::request(0, 0, 0); req.etag = "foo"; avecado::fetch_response response(fetch(req).get()); if (response.is_left()) { throw std::runtime_error("Expected 304 when using ETag header, but got 200 OK"); } if (response.right().status != avecado::fetch_status::not_modified) { throw std::runtime_error((boost::format("Expected status 304 when using ETag header, but got %1% %2%") % int(response.right().status) % response.right()).str()); } } void test_http_if_modified_since() { auto factory = boost::make_shared<cache_header_checker_factory>(); server_guard2 server(factory); avecado::fetch::http fetch(server.base_url(), "png"); auto req = avecado::request(0, 0, 0); req.if_modified_since = boost::posix_time::ptime(boost::gregorian::date(2015, boost::gregorian::May, 13), boost::posix_time::time_duration(14, 35, 10)); avecado::fetch_response response(fetch(req).get()); if (response.is_left()) { throw std::runtime_error("Expected 304 when using If-Modified-Since header, but got 200 OK"); } if (response.right().status != avecado::fetch_status::not_modified) { throw std::runtime_error((boost::format("Expected status 304 when using If-Modified-Since header, but got %1% %2%") % int(response.right().status) % response.right()).str()); } } } // anonymous namespace int main() { int tests_failed = 0; std::cout << "== Testing HTTP fetching ==" << std::endl << std::endl; // need datasource cache set up so that input plugins are available // when we parse map XML. mapnik::datasource_cache::instance().register_datasources(MAPNIK_DEFAULT_INPUT_PLUGIN_DIR); #define RUN_TEST(x) { tests_failed += test::run(#x, &(x)); } RUN_TEST(test_fetch_empty); RUN_TEST(test_fetch_single_line); RUN_TEST(test_fetch_error_coordinates); RUN_TEST(test_fetch_error_extension); RUN_TEST(test_fetch_error_path_segments); RUN_TEST(test_fetch_error_non_numeric); RUN_TEST(test_no_url_patterns_is_error); RUN_TEST(test_fetcher_io); RUN_TEST(test_fetch_tilejson); RUN_TEST(test_tile_is_compressed); RUN_TEST(test_tile_is_not_compressed); RUN_TEST(test_http_etag); RUN_TEST(test_http_if_modified_since); std::cout << " >> Tests failed: " << tests_failed << std::endl << std::endl; return (tests_failed > 0) ? 1 : 0; }
34.018135
140
0.692636
[ "vector" ]
4755dbab933e87cf0840f2efcb0eb220a656c77d
8,941
cc
C++
games/play.cc
jimages/surakarta-cpp
c5f8ba99c885d7316223356263c8ac112f2550b7
[ "MIT" ]
2
2021-01-04T12:15:48.000Z
2021-06-01T04:04:42.000Z
games/play.cc
jimages/surakarta-cpp
c5f8ba99c885d7316223356263c8ac112f2550b7
[ "MIT" ]
null
null
null
games/play.cc
jimages/surakarta-cpp
c5f8ba99c885d7316223356263c8ac112f2550b7
[ "MIT" ]
1
2021-07-31T15:26:30.000Z
2021-07-31T15:26:30.000Z
#include "helper.h" #include "mcts.h" #include "surakarta.h" #include <arpa/inet.h> #include <cassert> #include <cstdlib> #include <errno.h> #include <getopt.h> #include <iostream> #include <memory> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <unordered_map> #include <utility> #include <vector> #define BUFFER 2048 #define PORT 8999 const char* default_addres = "localhost:8999"; using MCTS::Node; using std::make_shared; using std::shared_ptr; void usage() { std::cout << "The surakarta AI player program. Zachary Wang (jimages123@gmail.com) Under MIT License.\n" << "Usage:\n" << " -h --help Print this message\n" << " -n Play with with network opponent\n" << " -t Play with with network opponent, the opponent decide the who is first.\n" << " -m Play with human in the console [default]\n" << " -s self play\n" << " -f The opponent play first\n" << std::flush; } SurakartaState::Move fromsocket(const int fd) { char buffer[BUFFER]; auto l = recv(fd, buffer, BUFFER, 0); if (l == -1) { perror(strerror(errno)); exit(-1); } assert(l == 7); buffer[7] = '\0'; std::stringstream str; str << buffer; SurakartaState::Move m = SurakartaState::no_move; str >> m; return m; } void tosocket(int fd, const SurakartaState::Move& move) { std::stringstream m; m << move; auto str = m.str(); if (send(fd, str.c_str(), str.length(), 0) == -1) { perror(strerror(errno)); exit(EXIT_FAILURE); } } // get action from human. auto human_action(const SurakartaState::Move& m) -> SurakartaState::Move { SurakartaState::Move move; cout << "Input your move: "; std::cin >> move; std::cout << "we move: " << move; return move; } // get action from network. SurakartaState::Move network_action(const int fd, const SurakartaState::Move& m) { SurakartaState::Move move; if (m != SurakartaState::no_move) { tosocket(fd, m); } move = fromsocket(fd); std::cout << "the network opponent move: " << move; return move; } int main(int argc, char* argv[]) { int ch; char buffer[BUFFER]; bool counter_first = false; bool opponent_decide_who_first = false; bool in_network = false; bool selfplay = false; bool human = true; static struct option longopts[] = { { "help", no_argument, NULL, 'h' }, { "network", optional_argument, NULL, 'n' }, { "human", no_argument, NULL, 'm' }, { "self", no_argument, NULL, 's' }, { "first", no_argument, NULL, 'f' }, { NULL, 0, NULL, 0 } }; // Get the options. while ((ch = getopt_long(argc, argv, "hnmhtsf", longopts, NULL)) != -1) { switch (ch) { case '?': case 'h': usage(); std::exit(EXIT_SUCCESS); break; case 't': std::cout << "play in target-decision net play mode\n"; opponent_decide_who_first = true; // -t is also a network mode. so we don't break. case 'n': std::cout << "play in net play mode\n"; in_network = true; human = false; selfplay = false; break; case 'm': std::cout << "play in human play mode\n"; in_network = false; human = true; selfplay = false; break; case 's': std::cout << "play in self play mode\n"; in_network = false; human = false; selfplay = true; break; case 'f': counter_first = true; break; default: std::cout << "play in human play mode\n"; } } try { // Init the model and the state. SurakartaState state; state.player_to_move = 1; PolicyValueNet network; if (exists("value_policy.pt")) network.load_model("value_policy.pt"); bool should_move = !counter_first; // Init the socket. auto serverfd = socket(AF_INET, SOCK_STREAM, 0); if (serverfd == -1) { perror(strerror(errno)); exit(EXIT_FAILURE); } decltype(serverfd) fd; struct sockaddr_in src_addr, des_addr; if (in_network) { std::cout << "Listen to the port:" << PORT << '\n'; memset(&src_addr, '\0', sizeof(src_addr)); src_addr.sin_family = AF_INET; src_addr.sin_addr.s_addr = INADDR_ANY; src_addr.sin_port = htons(PORT); socklen_t addrlen = sizeof(struct sockaddr_in); if (bind(serverfd, (struct sockaddr*)&src_addr, sizeof(src_addr)) < 0) { perror(strerror(errno)); exit(EXIT_FAILURE); } if (listen(serverfd, 1) != 0) { perror(strerror(errno)); exit(EXIT_FAILURE); } if ((fd = accept(serverfd, (struct sockaddr*)&des_addr, &addrlen)) < 0) { perror(strerror(errno)); exit(EXIT_FAILURE); } std::cout << "Accept connection from: " << inet_ntoa(des_addr.sin_addr) << " port: " << ntohs(des_addr.sin_port) << '\n'; // send the signal to the opponent. if (opponent_decide_who_first) { auto s = recv(fd, buffer, 1, 0); buffer[s] = '\0'; counter_first = !std::atoi(buffer); should_move = !counter_first; std::cout << "The target decision is: " << counter_first << '\n'; } else { if (counter_first) send(fd, static_cast<const void*>("1"), static_cast<size_t>(1), 0); } } int steps = 0; shared_ptr<Node<SurakartaState>> root = make_shared<Node<SurakartaState>>(state.player_to_move); SurakartaState::Move move = SurakartaState::no_move; while (state.has_moves()) { cout << endl << "State: " << state << endl; if (should_move) { while (true) { try { SurakartaState::Move m; m = MCTS::run_mcts(root, state, network, steps / 2); std::cout << "alphazero move: " << m; state.do_move(m); move = m; break; } catch (std::exception& e) { cout << "Invalid move." << endl; cout << e.what() << std::endl; } } } else { while (true) { try { SurakartaState::Move m; if (human) m = human_action(move); if (in_network) m = network_action(fd, move); if (selfplay) { m = MCTS::run_mcts(root, state, network, steps / 2); std::cout << "alphazero move: " << m; } std::cout << '\n'; std::ostream_iterator<SurakartaState::Move> outiter(std::cout, ", "); std::copy(state.get_moves().begin(), state.get_moves().end(), outiter); if (root->children.empty()) { MCTS::evaluate(root, state, network); } assert(state.get_moves().size() == root->children.size()); assert(state.player_to_move == root->player_to_move); state.do_move(m, true); move = m; break; } catch (std::exception& e) { cout << "Invalid move." << endl; cout << e.what() << std::endl; } } } root = root->get_child(move); should_move = !should_move; ++steps; } std::cout << endl << "Final state: " << state << endl; if (state.get_result(2) == 1.0) { cout << "Player 1 wins!" << endl; } else if (state.get_result(1) == 1.0) { cout << "Player 2 wins!" << endl; } else { cout << "Nobody wins!" << endl; } return 0; } catch (std::runtime_error& error) { std::cerr << "ERROR: " << error.what() << std::endl; return -1; } }
33.114815
120
0.47243
[ "vector", "model" ]
e6dff0781acc338ea7d62c8eba0e96d962b89be1
15,584
cpp
C++
APS-Project/Main.cpp
Hics0000/Console-Based-Cpp-Programs
6a7658a302d19b9d623ff7c5de5bc456c2d5ab69
[ "MIT" ]
null
null
null
APS-Project/Main.cpp
Hics0000/Console-Based-Cpp-Programs
6a7658a302d19b9d623ff7c5de5bc456c2d5ab69
[ "MIT" ]
1
2021-10-05T17:00:52.000Z
2021-10-05T17:00:52.000Z
APS-Project/Main.cpp
Hics0000/Console-Based-Cpp-Programs
6a7658a302d19b9d623ff7c5de5bc456c2d5ab69
[ "MIT" ]
7
2021-06-13T08:15:26.000Z
2021-10-05T17:02:10.000Z
#include <bits/stdc++.h> #include <windows.h> using namespace std; //Function Prototypes of the funcitons used throughout the Program. int SourceFileList(); int AddSourceFile(string, string); void loading(); //Program For RabinKarp Algorithm For String Sequence Pattern Matching. float rabinKarp(char seq[], char arr[], int line, int sent_line) { //seq is the sentence of the input text and arr corresponds to lines of the output file. int m = 121; int d = 256; int y; int len1 = strlen(seq); int hash_1 = 0; int len2 = strlen(arr); int hash_2 = 0; int h = 1; int l = 0; for (int x = 0; x < len1 - 1; x++) { h = (h * d) % m; } //For calculating the hash code value. for (int x = 0; x < len1; x++) { hash_1 = (d * hash_1 + seq[x]) % m; hash_2 = (d * hash_2 + arr[x]) % m; } for (int x = 0; x <= len2 - len1; x++) { if (hash_1 == hash_2) { for (y = 0; y < len1; y++) { if (seq[y] != arr[x + y]) break; } if (y == len1) { l++; // cout << "Sentence " << sent_line << " of the input text found at line " << line << " of output file" << std::endl; break; } } else if (x < len2 - len1) { int w = d * (hash_2 - arr[x] * h); hash_2 = (w + arr[x + len1]) % m; if (hash_2 < 0) { hash_2 = (hash_2 + m); } } } return l; } //UDf for reading data from the user's file, data from sources according to the content name then segregate data sentance wise then passing it to RabinKarp Function For String Sequence Pattern Matching //If The The user data is found to be 100% Plagriasm Free Then that data is added to the database under the Topicname user gave earlier int PlagChecker(string TopicName = "Russia", string FileName = "inputtest") { // ifstream SourceFile; SourceFile.open("Sources/" + TopicName + ".txt"); string SourceFileText; string SourceFileContent; while (getline(SourceFile, SourceFileText)) { SourceFileContent += SourceFileText; } SourceFile.close(); istringstream iss(SourceFileContent); string strtest; string TestData = ""; int line; float q = 0; float p = 0; float total_line = 0; float match_line = 0; while (getline(iss, strtest, '.')) { if (!strtest.empty()) { total_line++; line = 1; int m = strtest.length(); char seq[m + 1]; strcpy(seq, strtest.c_str()); ifstream file; file.open(FileName + ".txt"); string st1; while (getline(file, st1)) { int n = st1.length(); char char_array[n + 1]; strcpy(char_array, st1.c_str()); q = rabinKarp(seq, char_array, line, total_line); line++; if (q > 0) p++; } file.close(); if (p > 0) match_line++; } p = 0; } ifstream file; file.open(FileName + ".txt"); string st1; while (getline(file, st1)) { TestData += st1 + "\n"; } ofstream myfile; myfile.open("output.txt"); float plag; if (total_line == 0) { plag = 0; } else plag = 100 * (match_line / total_line); cout << " " << std::endl; myfile << "Total match sentence in the given input text is " << match_line << " and total sentence in the given input text is " << total_line << std::endl; cout << "Total match sentence in the given input text is " << match_line << " and total sentence in the given input text is " << total_line << std::endl; if (plag > 70) { myfile << "The give file has significant amount of Plagarism and it is " << plag << " %" << std::endl; cout << "The give file has significant amount of Plagarism and it is " << plag << " %" << std::endl; } else { myfile << "Plagarism is not detected in the given file and it is " << plag << " %" << std::endl; cout << "Plagarism is not detected in the given file and it is " << plag << " %" << std::endl; } if (plag == 0) { cout << TestData; AddSourceFile(TopicName, TestData); } cout << " " << std::endl; return 0; } // UDF for listing all the Orginal Sources File List. int SourceFileList() { //variable to count number of File That Exist in that databse int NumberOfFiles = 0; ifstream myfile; myfile.open("Sources/FileList.txt"); //string variable to store names of the files present in the database available. string st1; while (getline(myfile, st1)) { cout << st1 << ", "; NumberOfFiles++; } cout << endl; //returning the number of files available in the database. return NumberOfFiles; } // UDF for adding orginal data to our database and segregating into various content types int AddSourceFile(string FileName, string Content) { //int NumberOfFiles = 0; // Data File handling for saving the topic name in filelist fstream myfile; myfile.open("Sources/FileList.txt", ios::app); myfile << endl << FileName; cout << endl; //closeing the file opened myfile.close(); fstream file; // creating File with name FileName to save content in it and if file already exist then add data in the end of it. file.open("Sources/" + FileName + ".txt", ios::app); file << endl << Content; //closeing the file opened file.close(); return 0; } const int ALPHABET_SIZE = 26; // trie node class TrieNode { public: TrieNode *children[ALPHABET_SIZE]; // isEndOfWord is true if the node represents // end of a word bool isEndOfWord; TrieNode() { this->isEndOfWord = false; for (int i = 0; i < ALPHABET_SIZE; i++) this->children[i] = NULL; } }; class Trie { TrieNode *root; public: Trie() { root = new TrieNode; } // If not present, inserts key into trie // If the key is prefix of trie node, just // marks leaf node void insert(string key) { TrieNode *pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; cout << "TEST " << index << " " << key[i] << endl; if (!pCrawl->children[index]) pCrawl->children[index] = new TrieNode; pCrawl = pCrawl->children[index]; } // mark last node as leaf pCrawl->isEndOfWord = true; } // Builds Trie for helping out spam word search void build(vector<string> arr) { //print(arr); for (auto ele : arr) { this->insert(ele); } } // Returns true if key presents in trie, else // false bool search(string key) { TrieNode *pCrawl = root; for (int i = 0; i < key.length(); i++) { int index = key[i] - 'a'; if (!pCrawl->children[index]) return false; pCrawl = pCrawl->children[index]; } return (pCrawl != NULL && pCrawl->isEndOfWord); } } Spam; // Retrive spam words from database vector<string> retrieve(string FileName = "SpamWords") { // stores distinct words; vector<string> words; // Reading words from stored file ifstream spam_words; spam_words.open("Sources/" + FileName + ".txt"); string line; while (getline(spam_words, line)) { words.push_back(line); } return words; } //Utility function for debugging void print(vector<string> arr) { for (auto ele : arr) { cout << ele << " "; } cout << endl; } // Adding user specified spam words to stored database void addSpamWords(string FileName, string Content) { // transforms the word to lowercase for easier search operation transform(Content.begin(), Content.end(), Content.begin(), ::tolower); // Writing word to database ofstream spam_words; spam_words.open("Sources/" + FileName + ".txt", ios::app); spam_words << endl << Content; spam_words.close(); } // Utility function to remove unessesary characters from words string removeExtras(string word) { // useless characters to remove from words vector<char> arr = {'.', ',', '!', '#', '&', '(', ')', '\'', '"', ':', ';', '<', '>', '?', '/', '{', '}', '[', ']', '\\'}; // string to store filtered word string filterdWord = ""; for (int i = 0; i < word.length(); i++) { // flag insures only genuine characters are considered in current word bool flag = false; for (int j = 0; j < arr.size(); j++) { if (word[i] == arr[j]) { flag = true; break; } } if (!flag) filterdWord.push_back(word[i]); } return filterdWord; } // Extract disinct words from given line // Also, returns count of spam words in given line pair<int, int> countSpamWords(string str) { // total variable to store count of total words in given line int total = 0; // count variable to store count of spam words in given line int cnt = 0; // word variable to store word string word; // making a string stream stringstream iss(str); // Read and print each word. while (iss >> word) { word = removeExtras(word); total++; transform(word.begin(), word.end(), word.begin(), ::tolower); if (Spam.search(word)) cnt++; } return {cnt, total}; } // initialize the trie data structure void initSpam() { Spam.build(retrieve()); } // main function to check spam words in given file void spamChecker(string fileName) { //Initialising data structures for checker to work initSpam(); pair<long long, long long> totalSpams; ifstream file; file.open(fileName + ".txt"); string line; while (getline(file, line)) { pair<int, int> temp = countSpamWords(line); totalSpams.first += temp.first; totalSpams.second += temp.second; } cout << totalSpams.first << " out of " << totalSpams.second << " words" << endl; } int SpamFilter() { int n; string word; cout << "Enter count of words to be entered : "; cin >> n; while (n--) { cin >> word; addSpamWords("SpamWords", word); } string name; cout << "Enter FileName of file to be check for spam : "; cin >> name; spamChecker(name); return 0; } int aboutplag() // This function contains all the theory related to plagchecker { cout << "\n\nPlagiarism detection or content similarity detection is the process of locating instances of plagiarism andor copyright infringement within a work or document.\nThe widespread use of computers and the advent of the Internet have made it easier to plagiarize the work of others.\nDetection of plagiarism can be undertaken in a variety of ways. Human detection is the most traditional form of identifying plagiarism from written work. \nThis can be a lengthy and time-consuming task for the reader and can also result in inconsistencies in how plagiarism is identified within an organization. \nText-matching software (TMS), which is also referred to as plagiarism detection software or anti-plagiarism software, has become widely \navailable, in the form of both commercially available products as well as open-source[examples needed] software. TMS does not actually detect plagiarism per se, but instead finds \nspecific passages of text in one document that match text in another document"; return 0; } void aboutspam() // This function contains all the theory related to spamchecker { cout << " "; } int Plagiarism() //This function contains a menu for all functions which we will use in plagchecker { int plag; cout << "1.Check plag\n"; cout << "2.Add Original Data To Data base\n"; cout << "3.Check Available File List\n"; cout << "4.About Plagchecker\n"; cout << "Enter your choice:-\t"; cin >> plag; switch (plag) { case 1: //Case to check Plagiarism { cout << "few"; string filename1, topicname1; cout << "Enter topicname to check the Plagiarism:\t"; cin >> topicname1; cout << "\n"; cout << "Enter filename to check the Plagiarism:\t"; cin >> filename1; Sleep(1000); loading(); PlagChecker(topicname1, filename1); break; } case 2: // Case to add data in the database { string filename2, content; cout << "Enter filename of this file into database:\t"; cin >> filename2; cout << "Enter content of this file into database:\t"; cin >> content; Sleep(1000); loading(); AddSourceFile(filename2, content); cout << "many"; break; } case 3: //Case to check the content { cout << "List of content available:-\t"; Sleep(1000); cout << "more"; loading(); SourceFileList(); break; } case 4: //Case to get the information about plagchecker cout << "What is plagchecker?"; loading(); aboutplag(); break; default: cout << "Wrong choice"; } return 0; } int spam() //This function contains a menu for all functions which we will use in spamchecker { int spam; cout << "1.Add Spam words to database\n"; cout << "2.To Check Spam\n"; cout << "3.About Spamchecker\n"; cout << "Enter your choice:-\t"; cin >> spam; switch (spam) { case 1: //Case to add spam words into database { int n; string word; cout << "Enter count of words to be entered : "; cin >> n; while (n--) { cout << "\nEnter the word : "; cin >> word; loading(); addSpamWords("SpamWords", word); } break; } case 2: //Case to check spam { string name; cout << "Enter filename of file to be check for spam : "; cin >> name; loading(); spamChecker(name); break; } case 3: //Case to get information about spamchecker cout << "What is spamchecker?"; loading(); aboutspam(); break; default: cout << "Wrong choice"; } return 0; } int headpage() //This function has contains the menu to call the functions of plagchecker and spamchecker { int choice; cout << "1.Plagiarism Checker\n"; cout << "2.Spam Checker\n"; cout << "Enter your choice:-\t"; cin >> choice; switch (choice) { case 1: Plagiarism(); //Function will call the Plagiarism menu break; case 2: spam(); //Function will call the spam menu break; default: cout << "Wrong choice"; } return 0; } void loading() { for (int i = 0; i < 5; i++) { cout << "****"; Sleep(1000); } } int main() { headpage(); return 0; } // int main() // { // cout << "Hie Death"; // PlagChecker(); // return 0; // }
26.593857
1,008
0.56096
[ "vector", "transform" ]
e6e768a7fd4965e582d0b53496795771c9df5844
6,987
cpp
C++
Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp
Perpixel/o3de
b1df4c90d54839c44a6236d6fd3853e7e2af6404
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp
Perpixel/o3de
b1df4c90d54839c44a6236d6fd3853e7e2af6404
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp
Perpixel/o3de
b1df4c90d54839c44a6236d6fd3853e7e2af6404
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Atom/RPI.Edit/Common/AssetUtils.h> #include <AtomToolsFramework/Document/AtomToolsDocumentRequestBus.h> #include <AtomToolsFramework/DynamicProperty/DynamicPropertyGroup.h> #include <AtomToolsFramework/Inspector/InspectorPropertyGroupWidget.h> #include <AtomToolsFramework/Util/MaterialPropertyUtil.h> #include <Window/MaterialInspector/MaterialInspector.h> namespace MaterialEditor { MaterialInspector::MaterialInspector(QWidget* parent) : AtomToolsFramework::InspectorWidget(parent) { m_windowSettings = AZ::UserSettings::CreateFind<MaterialEditorWindowSettings>( AZ::Crc32("MaterialEditorWindowSettings"), AZ::UserSettings::CT_GLOBAL); AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); } MaterialInspector::~MaterialInspector() { AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); } void MaterialInspector::Reset() { m_documentPath.clear(); m_documentId = AZ::Uuid::CreateNull(); m_activeProperty = {}; AtomToolsFramework::InspectorRequestBus::Handler::BusDisconnect(); AtomToolsFramework::InspectorWidget::Reset(); } bool MaterialInspector::ShouldGroupAutoExpanded(const AZStd::string& groupName) const { auto stateItr = m_windowSettings->m_inspectorCollapsedGroups.find(GetGroupSaveStateKey(groupName)); return stateItr == m_windowSettings->m_inspectorCollapsedGroups.end(); } void MaterialInspector::OnGroupExpanded(const AZStd::string& groupName) { m_windowSettings->m_inspectorCollapsedGroups.erase(GetGroupSaveStateKey(groupName)); } void MaterialInspector::OnGroupCollapsed(const AZStd::string& groupName) { m_windowSettings->m_inspectorCollapsedGroups.insert(GetGroupSaveStateKey(groupName)); } void MaterialInspector::OnDocumentOpened(const AZ::Uuid& documentId) { AddGroupsBegin(); m_documentId = documentId; bool isOpen = false; AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult( isOpen, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::IsOpen); AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult( m_documentPath, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetAbsolutePath); if (!m_documentId.IsNull() && isOpen) { // This will automatically expose all document contents to an inspector with a collapsible group per object. In the case of the // material editor, this will be one inspector group per property group. AZStd::vector<AtomToolsFramework::DocumentObjectInfo> objects; AtomToolsFramework::AtomToolsDocumentRequestBus::EventResult( objects, m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::GetObjectInfo); for (auto& objectInfo : objects) { // Passing in same main and comparison instance to enable custom value comparison for highlighting modified properties auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( objectInfo.m_objectPtr, objectInfo.m_objectPtr, objectInfo.m_objectType, this, this, GetGroupSaveStateKey(objectInfo.m_name), {}, [this](const auto node) { return GetInstanceNodePropertyIndicator(node); }, 0); AddGroup(objectInfo.m_name, objectInfo.m_displayName, objectInfo.m_description, propertyGroupWidget); SetGroupVisible(objectInfo.m_name, objectInfo.m_visible); } AtomToolsFramework::InspectorRequestBus::Handler::BusConnect(m_documentId); } AddGroupsEnd(); } AZ::Crc32 MaterialInspector::GetGroupSaveStateKey(const AZStd::string& groupName) const { return AZ::Crc32(AZStd::string::format("MaterialInspector::PropertyGroup::%s::%s", m_documentPath.c_str(), groupName.c_str())); } bool MaterialInspector::IsInstanceNodePropertyModifed(const AzToolsFramework::InstanceDataNode* node) const { const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(node); return property && !AtomToolsFramework::ArePropertyValuesEqual(property->GetValue(), property->GetConfig().m_parentValue); } const char* MaterialInspector::GetInstanceNodePropertyIndicator(const AzToolsFramework::InstanceDataNode* node) const { if (IsInstanceNodePropertyModifed(node)) { return ":/Icons/changed_property.svg"; } return ":/Icons/blank.png"; } void MaterialInspector::OnDocumentObjectInfoChanged( [[maybe_unused]] const AZ::Uuid& documentId, const AtomToolsFramework::DocumentObjectInfo& objectInfo, bool rebuilt) { SetGroupVisible(objectInfo.m_name, objectInfo.m_visible); if (rebuilt) { RebuildGroup(objectInfo.m_name); } else { RefreshGroup(objectInfo.m_name); } } void MaterialInspector::BeforePropertyModified(AzToolsFramework::InstanceDataNode* pNode) { // This function is called before every single property change whether it's a button click or dragging a slider. We only want to // begin tracking undo state for the first change in the sequence, when the user begins to drag the slider. const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(pNode); if (!m_activeProperty && property) { m_activeProperty = property; AtomToolsFramework::AtomToolsDocumentRequestBus::Event( m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::BeginEdit); } } void MaterialInspector::SetPropertyEditingComplete(AzToolsFramework::InstanceDataNode* pNode) { // If tracking has started and editing has completed then we can stop tracking undue state for this sequence of changes. const AtomToolsFramework::DynamicProperty* property = AtomToolsFramework::FindDynamicPropertyForInstanceDataNode(pNode); if (m_activeProperty && m_activeProperty == property) { AtomToolsFramework::AtomToolsDocumentRequestBus::Event( m_documentId, &AtomToolsFramework::AtomToolsDocumentRequestBus::Events::EndEdit); m_activeProperty = {}; } } } // namespace MaterialEditor #include <Window/MaterialInspector/moc_MaterialInspector.cpp>
43.943396
139
0.712609
[ "object", "vector", "3d" ]
e6ebfb001d719d6e97e2fb5c2fb00ef3cf5d7c52
2,130
cc
C++
src/timer.cc
graysonchao/credis
cff510e46a63bf6b99a7812122223b9535eeb1d6
[ "Apache-2.0" ]
null
null
null
src/timer.cc
graysonchao/credis
cff510e46a63bf6b99a7812122223b9535eeb1d6
[ "Apache-2.0" ]
9
2018-02-26T21:21:18.000Z
2018-04-11T22:03:02.000Z
src/timer.cc
graysonchao/credis
cff510e46a63bf6b99a7812122223b9535eeb1d6
[ "Apache-2.0" ]
null
null
null
#include <cmath> #include <string> #include <sys/time.h> #include <time.h> #include "glog/logging.h" #include "timer.h" Timer Timer::Merge(Timer& timer1, Timer& timer2) { Timer t; auto& lat = t.latency_micros(); auto& lat1 = timer1.latency_micros(); auto& lat2 = timer2.latency_micros(); lat.reserve(lat1.size() + lat2.size()); lat.insert(lat.end(), lat1.begin(), lat1.end()); lat.insert(lat.end(), lat2.begin(), lat2.end()); return t; } double Timer::NowMicrosecs() const { struct timeval time; gettimeofday(&time, NULL); return (double) time.tv_sec * 1e6 + (double) time.tv_usec; } void Timer::ExpectOps(int N) { begin_timestamps_.reserve(N); latency_micros_.reserve(N); } double Timer::TimeOpBegin() { const double now = NowMicrosecs(); CHECK(latency_micros_.size() == begin_timestamps_.size()) << " sizes " << latency_micros_.size() << " " << begin_timestamps_.size(); begin_timestamps_.push_back(now); return now; } void Timer::TimeOpEnd(int num_completed) { const double now = NowMicrosecs(); CHECK(latency_micros_.size() == num_completed - 1); CHECK(begin_timestamps_.size() == num_completed) << begin_timestamps_.size() << " " << num_completed; latency_micros_.push_back(now - begin_timestamps_.back()); } void Timer::Stats(double* mean, double* std) const { if (latency_micros_.empty()) { *mean = 0; *std = 0; return; } double sum = 0; for (const double x : latency_micros_) sum += x; *mean = sum / latency_micros_.size(); sum = 0; for (const double x : latency_micros_) sum += (x - *mean) * (x - *mean); *std = std::sqrt(sum / latency_micros_.size()); } std::string Timer::ReportStats(const std::string& name) const { double mean = 0, std = 0; Stats(&mean, &std); std::string msg = name; msg += " mean "; msg += std::to_string(mean); msg += " std "; msg += std::to_string(std); msg += " num "; msg += std::to_string(latency_micros_.size()); return msg; } std::vector<double>& Timer::begin_timestamps() { return begin_timestamps_; } std::vector<double>& Timer::latency_micros() { return latency_micros_; }
26.625
80
0.657277
[ "vector" ]
e6eff5a4cde29caeb67d545b2b54d1a8bee547f3
2,330
hpp
C++
packages/velodyne_lidar/components/VelodyneLidar.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
packages/velodyne_lidar/components/VelodyneLidar.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
packages/velodyne_lidar/components/VelodyneLidar.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include <memory> #include <string> #include <vector> #include "engine/alice/alice_codelet.hpp" #include "engine/core/byte.hpp" #include "engine/core/optional.hpp" #include "messages/messages.hpp" #include "packages/velodyne_lidar/gems/velodyne_constants.hpp" namespace isaac { class Socket; namespace velodyne_lidar { // Serialization helper for :VelodyneModelType to JSON NLOHMANN_JSON_SERIALIZE_ENUM(VelodyneModelType, { {VelodyneModelType::VLP16, "VLP16"}, {VelodyneModelType::INVALID, nullptr}, }); // A driver for the Velodyne VLP16 Lidar. class VelodyneLidar : public alice::Codelet { public: void start() override; void tick() override; void stop() override; // A range scan slice published by the Lidar ISAAC_PROTO_TX(RangeScanProto, scan); // The IP address of the Lidar device ISAAC_PARAM(std::string, ip, "192.168.2.201"); // The port at which the Lidar device publishes data. ISAAC_PARAM(int, port, 2368); // The type of the Lidar (currently only VLP16 is supported). ISAAC_PARAM(VelodyneModelType, type, VelodyneModelType::VLP16); private: // Process a packet of data coming on the wire with VLP16Format void processDataBlockVPL16(const VelodyneRawDataBlock& raw_block, TensorView2ui16 ranges, TensorView2ub intensities, int offset); // Configures some member variables according to the lidar type void initLaser(VelodyneModelType model_type); std::unique_ptr<Socket> socket_; std::optional<std::vector<byte>> previous_packet_; std::vector<byte> raw_packet_; // Model specific parameters VelodyneLidarParameters parameters_; }; } // namespace velodyne_lidar } // namespace isaac ISAAC_ALICE_REGISTER_CODELET(isaac::velodyne_lidar::VelodyneLidar);
33.285714
91
0.718455
[ "vector", "model" ]
e6fe31114915d2073de4d7ee8f1127cc587a63ff
3,347
cpp
C++
aws-cpp-sdk-billingconductor/source/BillingConductorErrors.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-billingconductor/source/BillingConductorErrors.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-billingconductor/source/BillingConductorErrors.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/core/client/AWSError.h> #include <aws/core/utils/HashingUtils.h> #include <aws/billingconductor/BillingConductorErrors.h> #include <aws/billingconductor/model/ConflictException.h> #include <aws/billingconductor/model/ThrottlingException.h> #include <aws/billingconductor/model/InternalServerException.h> #include <aws/billingconductor/model/ResourceNotFoundException.h> #include <aws/billingconductor/model/ValidationException.h> #include <aws/billingconductor/model/ServiceLimitExceededException.h> using namespace Aws::Client; using namespace Aws::Utils; using namespace Aws::BillingConductor; using namespace Aws::BillingConductor::Model; namespace Aws { namespace BillingConductor { template<> AWS_BILLINGCONDUCTOR_API ConflictException BillingConductorError::GetModeledError() { assert(this->GetErrorType() == BillingConductorErrors::CONFLICT); return ConflictException(this->GetJsonPayload().View()); } template<> AWS_BILLINGCONDUCTOR_API ThrottlingException BillingConductorError::GetModeledError() { assert(this->GetErrorType() == BillingConductorErrors::THROTTLING); return ThrottlingException(this->GetJsonPayload().View()); } template<> AWS_BILLINGCONDUCTOR_API InternalServerException BillingConductorError::GetModeledError() { assert(this->GetErrorType() == BillingConductorErrors::INTERNAL_SERVER); return InternalServerException(this->GetJsonPayload().View()); } template<> AWS_BILLINGCONDUCTOR_API ResourceNotFoundException BillingConductorError::GetModeledError() { assert(this->GetErrorType() == BillingConductorErrors::RESOURCE_NOT_FOUND); return ResourceNotFoundException(this->GetJsonPayload().View()); } template<> AWS_BILLINGCONDUCTOR_API ValidationException BillingConductorError::GetModeledError() { assert(this->GetErrorType() == BillingConductorErrors::VALIDATION); return ValidationException(this->GetJsonPayload().View()); } template<> AWS_BILLINGCONDUCTOR_API ServiceLimitExceededException BillingConductorError::GetModeledError() { assert(this->GetErrorType() == BillingConductorErrors::SERVICE_LIMIT_EXCEEDED); return ServiceLimitExceededException(this->GetJsonPayload().View()); } namespace BillingConductorErrorMapper { static const int CONFLICT_HASH = HashingUtils::HashString("ConflictException"); static const int INTERNAL_SERVER_HASH = HashingUtils::HashString("InternalServerException"); static const int SERVICE_LIMIT_EXCEEDED_HASH = HashingUtils::HashString("ServiceLimitExceededException"); AWSError<CoreErrors> GetErrorForName(const char* errorName) { int hashCode = HashingUtils::HashString(errorName); if (hashCode == CONFLICT_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(BillingConductorErrors::CONFLICT), false); } else if (hashCode == INTERNAL_SERVER_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(BillingConductorErrors::INTERNAL_SERVER), false); } else if (hashCode == SERVICE_LIMIT_EXCEEDED_HASH) { return AWSError<CoreErrors>(static_cast<CoreErrors>(BillingConductorErrors::SERVICE_LIMIT_EXCEEDED), false); } return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false); } } // namespace BillingConductorErrorMapper } // namespace BillingConductor } // namespace Aws
36.78022
112
0.806693
[ "model" ]
e6ff9efbb13d41abd3aa496e9b0c9c2e632c67a7
6,366
cpp
C++
src/uuids.cpp
Paycasso/cpp-driver
9e6efd4842afc226d999baf890a55275e7e94cf8
[ "Apache-2.0" ]
null
null
null
src/uuids.cpp
Paycasso/cpp-driver
9e6efd4842afc226d999baf890a55275e7e94cf8
[ "Apache-2.0" ]
null
null
null
src/uuids.cpp
Paycasso/cpp-driver
9e6efd4842afc226d999baf890a55275e7e94cf8
[ "Apache-2.0" ]
null
null
null
#include "cassandra.h" #include "uuids.hpp" extern "C" { void cass_uuid_generate_time(CassUuid output) { cass::Uuids::generate_v1(output); } void cass_uuid_from_time(cass_uint64_t time, CassUuid output) { cass::Uuids::generate_v1(time, output); } void cass_uuid_min_from_time(cass_uint64_t time, CassUuid output) { cass::Uuids::min_v1(time, output); } void cass_uuid_max_from_time(cass_uint64_t time, CassUuid output) { cass::Uuids::max_v1(time, output); } cass_uint64_t cass_uuid_timestamp(CassUuid uuid) { return cass::Uuids::get_unix_timestamp(uuid); } void cass_uuid_generate_random(CassUuid output) { cass::Uuids::generate_v4(output); } cass_uint8_t cass_uuid_version(CassUuid uuid) { return cass::Uuids::get_version(uuid); } void cass_uuid_string(CassUuid uuid, char* output) { cass::Uuids::to_string(uuid, output); } } // extern "C" namespace cass { uint64_t Uuids::CLOCK_SEQ_AND_NODE = 0L; std::atomic_flag Uuids::lock_ = ATOMIC_FLAG_INIT; std::atomic<bool> Uuids::is_initialized_ = ATOMIC_VAR_INIT(false); std::atomic<uint64_t> Uuids::last_timestamp_ = ATOMIC_VAR_INIT(0L); std::mt19937_64 Uuids::ng_; void Uuids::initialize() { lock(); if (!is_initialized_) { std::random_device rd; ng_.seed(rd()); CLOCK_SEQ_AND_NODE = make_clock_seq_and_node(); is_initialized_ = true; } unlock(); } void Uuids::generate_v1(Uuid uuid) { generate_v1(uuid_timestamp(), uuid); } void Uuids::generate_v1(uint64_t timestamp, Uuid uuid) { if (!is_initialized_) { initialize(); } copy_timestamp(timestamp, 1, uuid); copy_clock_seq_and_node(CLOCK_SEQ_AND_NODE, uuid); } void Uuids::generate_v4(Uuid uuid) { if (!is_initialized_) { initialize(); } lock(); uint64_t msb = ng_(); uint64_t lsb = ng_(); unlock(); copy_timestamp(msb, 4, uuid); lsb = (lsb & 0x3FFFFFFFFFFFFFFFL) | 0x8000000000000000L; // RFC4122 variant copy_clock_seq_and_node(lsb, uuid); } void Uuids::min_v1(uint64_t timestamp, Uuid uuid) { copy_timestamp(from_unix_timestamp(timestamp), 1, uuid); copy_clock_seq_and_node(MIN_CLOCK_SEQ_AND_NODE, uuid); } void Uuids::max_v1(uint64_t timestamp, Uuid uuid) { copy_timestamp(from_unix_timestamp(timestamp + 1) - 1, 1, uuid); copy_clock_seq_and_node(MAX_CLOCK_SEQ_AND_NODE, uuid); } uint64_t Uuids::get_unix_timestamp(Uuid uuid) { uint64_t timestamp = 0; if (get_version(uuid) != 1) { return 0; } timestamp |= static_cast<uint64_t>(uuid[3]); timestamp |= static_cast<uint64_t>(uuid[2]) << 8; timestamp |= static_cast<uint64_t>(uuid[1]) << 16; timestamp |= static_cast<uint64_t>(uuid[0]) << 24; timestamp |= static_cast<uint64_t>(uuid[5]) << 32; timestamp |= static_cast<uint64_t>(uuid[4]) << 40; timestamp |= static_cast<uint64_t>(uuid[7]) << 48; timestamp |= static_cast<uint64_t>(uuid[6]) << 56; timestamp &= 0x0FFFFFFFFFFFFFFFL; // Clear version return to_milliseconds(timestamp - TIME_OFFSET_BETWEEN_UTC_AND_EPOCH); } void Uuids::to_string(Uuid uuid, char* output) { size_t pos = 0; for (int i = 0; i < 16; ++i) { char buf[3] = {'\0'}; sprintf(buf, "%02x", uuid[i]); if (i == 4 || i == 6 || i == 8 || i == 10) { output[pos++] = '-'; } output[pos++] = buf[0]; output[pos++] = buf[1]; } output[pos] = '\0'; } void Uuids::copy_timestamp(uint64_t timestamp, uint8_t version, Uuid uuid) { uuid[3] = timestamp & 0x00000000000000FFL; timestamp >>= 8; uuid[2] = timestamp & 0x00000000000000FFL; timestamp >>= 8; uuid[1] = timestamp & 0x00000000000000FFL; timestamp >>= 8; uuid[0] = timestamp & 0x00000000000000FFL; timestamp >>= 8; uuid[5] = timestamp & 0x00000000000000FFL; timestamp >>= 8; uuid[4] = timestamp & 0x00000000000000FFL; timestamp >>= 8; uuid[7] = timestamp & 0x00000000000000FFL; timestamp >>= 8; uuid[6] = (timestamp & 0x000000000000000FL) | (version << 4); } uint64_t Uuids::uuid_timestamp() { while (true) { uint64_t now = from_unix_timestamp(unix_timestamp()); uint64_t last = last_timestamp_.load(); if (now > last) { if (last_timestamp_.compare_exchange_strong(last, now)) { return now; } } else { uint64_t last_ms = to_milliseconds(last); if (to_milliseconds(now) < last_ms) { return last_timestamp_.fetch_add(1L); } uint64_t candidate = last + 1; if (to_milliseconds(candidate) == last_ms && last_timestamp_.compare_exchange_strong(last, candidate)) { return candidate; } } } } uint64_t Uuids::make_clock_seq_and_node() { int count = 0; EVP_MD_CTX* mdctx = EVP_MD_CTX_create(); EVP_DigestInit(mdctx, EVP_md5()); uv_interface_address_t* addresses; int address_count; if (uv_interface_addresses(&addresses, &address_count).code == 0) { for (int i = 0; i < address_count; ++i) { char buf[256]; uv_interface_address_t address = addresses[i]; EVP_DigestUpdate(mdctx, address.name, strlen(address.name)); if (address.address.address4.sin_family == AF_INET) { uv_ip4_name(&address.address.address4, buf, sizeof(buf)); EVP_DigestUpdate(mdctx, buf, strlen(buf)); count++; } else if (address.address.address4.sin_family == AF_INET6) { uv_ip6_name(&address.address.address6, buf, sizeof(buf)); EVP_DigestUpdate(mdctx, buf, strlen(buf)); count++; } } uv_free_interface_addresses(addresses, address_count); } assert(count > 0 && "No unique information for UUID node portion"); uv_cpu_info_t* cpu_infos; int cpu_count; if (uv_cpu_info(&cpu_infos, &cpu_count).code == 0) { for (int i = 0; i < cpu_count; ++i) { uv_cpu_info_t cpu_info = cpu_infos[i]; EVP_DigestUpdate(mdctx, cpu_info.model, strlen(cpu_info.model)); } uv_free_cpu_info(cpu_infos, cpu_count); } uint8_t hash[16]; EVP_DigestFinal_ex(mdctx, hash, nullptr); EVP_MD_CTX_destroy(mdctx); uint64_t node = 0L; for (int i = 0; i < 6; ++i) { node |= (0x00000000000000FFL & (long)hash[i]) << (i * 8); } node |= 0x0000010000000000L; // Multicast bit uint64_t clock = ng_(); uint64_t clock_seq_and_node = 0; clock_seq_and_node |= (clock & 0x0000000000003FFFL) << 48; clock_seq_and_node |= 0x8000000000000000L; // RFC4122 variant clock_seq_and_node |= node; return clock_seq_and_node; } } // namespace cass
26.860759
77
0.678919
[ "model" ]
fc020c02ad07e5b8115a1594b70a4389e3b22ea8
8,582
cpp
C++
vimframeswitcher.cpp
RockFordgt/VimFrameSwitcher
9245abacf861e675e7a351282f8f7f5af2fd0aa4
[ "BSD-3-Clause" ]
null
null
null
vimframeswitcher.cpp
RockFordgt/VimFrameSwitcher
9245abacf861e675e7a351282f8f7f5af2fd0aa4
[ "BSD-3-Clause" ]
null
null
null
vimframeswitcher.cpp
RockFordgt/VimFrameSwitcher
9245abacf861e675e7a351282f8f7f5af2fd0aa4
[ "BSD-3-Clause" ]
null
null
null
#include "vimframeswitcher.hpp" #include "vimframeswitcherconstants.hpp" #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/command.h> #include <coreplugin/coreconstants.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/icontext.h> #include <coreplugin/icore.h> #include <coreplugin/idocument.h> #include <texteditor/texteditor.h> #include <QTextEdit> #include <QAction> #include <QMessageBox> #include <QMainWindow> #include <QMenu> #include <QPoint> #include <algorithm> #include <map> namespace VimFrameSwitcher { namespace Internal { VimFrameSwitcherPlugin::VimFrameSwitcherPlugin() { // Create your members } VimFrameSwitcherPlugin::~VimFrameSwitcherPlugin() { // Unregister objects from the plugin manager's object pool // Delete members } bool VimFrameSwitcherPlugin::initialize(const QStringList &arguments, QString *errorString) { // Register objects in the plugin manager's object pool // Load settings // Add actions to menus // Connect to other plugins' signals // In the initialize function, a plugin can be sure that the plugins it // depends on have initialized their members. Q_UNUSED(arguments) Q_UNUSED(errorString) auto action_left = new QAction(tr("Jump to left"), this); auto action_right = new QAction(tr("Jump to right"), this); auto action_up = new QAction(tr("Jump to up"), this); auto action_down = new QAction(tr("Jump to down"), this); Core::Command *cmd_left = Core::ActionManager::registerAction(action_left, Constants::ACTION_LEFT_ID, Core::Context(Core::Constants::C_GLOBAL)); Core::Command *cmd_right= Core::ActionManager::registerAction(action_right, Constants::ACTION_RIGHT_ID, Core::Context(Core::Constants::C_GLOBAL)); Core::Command *cmd_up = Core::ActionManager::registerAction(action_up, Constants::ACTION_DOWN_ID, Core::Context(Core::Constants::C_GLOBAL)); Core::Command *cmd_down = Core::ActionManager::registerAction(action_down, Constants::ACTION_UP_ID, Core::Context(Core::Constants::C_GLOBAL)); cmd_left->setDefaultKeySequences(QList<QKeySequence>({ QKeySequence(tr("Alt+H")), QKeySequence(tr("Ctrl+W,H")), QKeySequence(tr("Alt+Meta+H")), })); cmd_right->setDefaultKeySequences(QList<QKeySequence>({ QKeySequence(tr("Alt+L")), QKeySequence(tr("Ctrl+W,L")), QKeySequence(tr("Alt+Meta+L")), })); cmd_up->setDefaultKeySequences(QList<QKeySequence>({ QKeySequence(tr("Alt+K")), QKeySequence(tr("Ctrl+W,K")), QKeySequence(tr("Alt+Meta+K")), })); cmd_down->setDefaultKeySequences(QList<QKeySequence>({ QKeySequence(tr("Alt+J")), QKeySequence(tr("Ctrl+W,J")), QKeySequence(tr("Alt+Meta+J")), })); connect(action_left, &QAction::triggered, this, &VimFrameSwitcherPlugin::triggerLeft_h); connect(action_right, &QAction::triggered, this, &VimFrameSwitcherPlugin::triggerRight_l); connect(action_up, &QAction::triggered, this, &VimFrameSwitcherPlugin::triggerUp_k); connect(action_down, &QAction::triggered, this, &VimFrameSwitcherPlugin::triggerDown_j); Core::ActionContainer *menu = Core::ActionManager::createMenu(Constants::MENU_ID); menu->menu()->setTitle(tr("VimFrameSwitcher")); menu->addAction(cmd_left); menu->addAction(cmd_right); menu->addAction(cmd_up); menu->addAction(cmd_down); Core::ActionManager::actionContainer(Core::Constants::M_TOOLS)->addMenu(menu); return true; } void VimFrameSwitcherPlugin::extensionsInitialized() { // Retrieve objects from the plugin manager's object pool // In the extensionsInitialized function, a plugin can be sure that all // plugins that depend on it are completely initialized. } ExtensionSystem::IPlugin::ShutdownFlag VimFrameSwitcherPlugin::aboutToShutdown() { // Save settings // Disconnect from signals that are not needed during shutdown // Hide UI (if you add UI that is not in the main window directly) return SynchronousShutdown; } void VimFrameSwitcherPlugin::triggerLeft_h() { leftRight(Left); } void VimFrameSwitcherPlugin::triggerRight_l() { leftRight(Right); } void VimFrameSwitcherPlugin::triggerUp_k() { upDown(Up); } void VimFrameSwitcherPlugin::triggerDown_j() { upDown(Down); } void VimFrameSwitcherPlugin::leftRight(VimFrameSwitcherPlugin::LeftRightDir direction) { getCurrentCursorPos(); std::map<int, Core::IEditor*> jumpsMap; for (auto editor: editors){ if (editor != Core::EditorManager::currentEditor()) { QRect editorRect(editor->widget()->mapToGlobal(editor->widget()->rect().topLeft()), editor->widget()->mapToGlobal(editor->widget()->rect().bottomRight())); if ( ( editorRect.y() < currentTextCursorPosition.y() ) && (editorRect.bottom()> currentTextCursorPosition.y()) ) { int newDistance=currentTextCursorPosition.x() - editorRect.left(); switch (direction) { case Left: if (newDistance > 0) { jumpsMap[newDistance] = editor; } break; case Right: if (newDistance < 0) { jumpsMap[newDistance] = editor; } } } } } if (jumpsMap.size()>0){ switch (direction) { case Left: Core::EditorManager::activateEditor(jumpsMap.begin()->second); break; case Right: Core::EditorManager::activateEditor(jumpsMap.rbegin()->second); } } } void VimFrameSwitcherPlugin::upDown(VimFrameSwitcherPlugin::UpDownDir direction) { getCurrentCursorPos(); std::map<int, Core::IEditor*> jumpsMap; for (auto editor: editors){ if (editor != Core::EditorManager::currentEditor()) { QRect editorRect(editor->widget()->mapToGlobal(editor->widget()->rect().topLeft()), editor->widget()->mapToGlobal(editor->widget()->rect().bottomRight())); if ( ( editorRect.x() < currentTextCursorPosition.x() ) && (editorRect.right()> currentTextCursorPosition.x()) ) { int newDistance=currentTextCursorPosition.y() - editorRect.bottom(); switch (direction) { case Up: if (newDistance > 0) { jumpsMap[newDistance] = editor; } break; case Down: if (newDistance < 0) { jumpsMap[newDistance] = editor; } } } } } if (jumpsMap.size()>0){ switch (direction) { case Up: Core::EditorManager::activateEditor(jumpsMap.begin()->second); break; case Down: Core::EditorManager::activateEditor(jumpsMap.rbegin()->second); } } } void VimFrameSwitcherPlugin::getCurrentCursorPos() { Core::IEditor* current = Core::EditorManager::currentEditor(); TextEditor::BaseTextEditor *textEdit = qobject_cast<TextEditor::BaseTextEditor*>(current); if (textEdit){ currentTextCursorPosition = current->widget()->mapToGlobal( textEdit->editorWidget()->cursorRect(textEdit->textCursor()).topLeft() ); editors = Core::EditorManager::visibleEditors(); }else{ currentTextCursorPosition = QPoint(0,0); } } } // namespace Internal } // namespace VimFrameSwitcher
38.657658
150
0.584712
[ "object" ]
fc07cfecf751493246e63472c51e970459b164b8
883
cpp
C++
test/add_two_numbers_unittest.cpp
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
test/add_two_numbers_unittest.cpp
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
test/add_two_numbers_unittest.cpp
Rokugatsu/leetcode
f868c494a9d23ac6519c94374281781f209fb19c
[ "MIT" ]
null
null
null
/** * @file add_two_numbers.cpp * @author lipingan (lipingan.dev@outlook.com) * @brief * @version 0.1 * @date 2021-12-30 * * @copyright Copyright (c) 2021 * */ #include "add_two_numbers.h" #include <gmock/gmock.h> #include <gtest/gtest.h> namespace leetcode { TEST(add_two_numers, case_0) { std::vector vec1{9}; std::vector vec2{9}; auto list1 = spawnList(vec1); auto list2 = spawnList(vec2); printList(list1); printList(list2); auto ret = addTwoNumbers(list1, list2); printList(ret); } TEST(add_two_numers, case_1) { std::vector vec2{9}; auto list2 = spawnList(vec2); printList(list2); auto ret = addTwoNumbers(nullptr, list2); printList(ret); } TEST(add_two_numers, case_3) { std::vector vec2{9}; auto list2 = spawnList(vec2); printList(list2); auto ret = addTwoNumbers(nullptr, nullptr); printList(ret); } } // namespace leetcode
19.622222
46
0.682899
[ "vector" ]
fc08a9e2ee9464762ec938cab32d6a425d8afe48
13,016
cpp
C++
k09/kalgo01.cpp
kojiynet/koli
681f9c1b1a291a36e1f0eee43c45b37567d2661e
[ "BSL-1.0" ]
null
null
null
k09/kalgo01.cpp
kojiynet/koli
681f9c1b1a291a36e1f0eee43c45b37567d2661e
[ "BSL-1.0" ]
null
null
null
k09/kalgo01.cpp
kojiynet/koli
681f9c1b1a291a36e1f0eee43c45b37567d2661e
[ "BSL-1.0" ]
null
null
null
/* kalgo Ver. k09.01 Written by Koji Yamamoto Copyright (C) 2014-2019 Koji Yamamoto In using this, please read the document which states terms of use. Library for Algorithmic Solution (possibly useful for simulations) */ /* ********** Preprocessor Directives ********** */ #ifndef kalgo_cpp_include_guard #define kalgo_cpp_include_guard #include <vector> #include <algorithm> #include <k09/kutil02.cpp> #include <k09/krand00.cpp> /* ********** Using Directives ********** */ using namespace std; /* ********** Class Declarations ********** */ template <typename TKey, typename T> class Paravec; /* ********** Enum Definitions ********** */ /* ********** Function Declarations ********** */ template <typename T> void calcRanksFromValues( vector <int> &, const vector <T> &, RandomNumberEngine &); template <typename T> void randomizeOrder( vector <T> &, RandomNumberEngine &); template <typename T> void getIndexOfMax( vector <int> &, const vector <T> &); template <typename T> int getIndexOfMaxRandomized( const vector <T> &, RandomNumberEngine &); template <typename T> void getIndexOfMin( vector <int> &, const vector <T> &); template <typename T> int getIndexOfMinRandomized( const vector <T> &, RandomNumberEngine &); template <typename T> int getIndexOfElement( const vector <T> &, T); template <typename TData, typename TKey> bool getCopyOfElementForKey( TData &, const vector <TData> &, const vector <TKey> &, TKey); template <typename TData, typename TKey> bool getPointerToElementForKey( TData * &, const vector <TData> &, const vector <TKey> &, TKey); template <typename T> T getSumOfElements( const vector <T> &, T); /* ********** Class Definitions ********** */ // Contains two parallel vectors, one of which is a Key template <typename TKey, typename T> class Paravec { private: public: vector <TKey> keys; vector <T> values; Paravec( void); ~Paravec( void); void copyFrom( const Paravec &); void initialize( const vector <TKey> &, const vector <T> &); bool addValue( TKey, T); bool keyExists( TKey) const; bool checkUniqueKeys( void) const; int getSize( void) const; bool getValueOfKey( T &, TKey) const; const vector <TKey> & getKeyVecRef( void) const; const vector <T> & getValueVecRef( void) const; T & getElementRefOfKey( TKey); }; /* ********** Global Variables ********** */ /* ********** Definitions of Static Member Variables ********** */ /* ********** Function Definitions ********** */ /* dataの各要素の大小を比較し、対応する順位を算出し、dataのk番目の要素の順位をretrank[ k]に入れる。 値の等しい要素の集合に対しては、乱数を振って、ランダムに順位を付す。 乱数の生成のためのRandomNumberEngineインスタンスを必要とする。 型Tに対して、不等号・等号・代入演算子が定義されている必要がある。 */ template <typename T> void calcRanksFromValues( vector <int> &retranks, const vector <T> &data, RandomNumberEngine &rne) { int n; vector <T> v0; vector <int> ids; bool loop; T vtemp; int idtemp; v0 = data; n = v0.size(); ids.clear(); retranks.clear(); for ( int i = 0; i < n; i++){ ids.push_back( i); retranks.push_back( i + 1); } loop = true; while ( loop){ loop = false; for ( int i = 0; i < n - 1; i++){ if ( v0[ i] < v0[ i + 1]){ vtemp = v0[ i]; v0[ i] = v0[ i + 1]; v0[ i + 1] = vtemp; idtemp = ids[ i]; ids[ i] = ids[ i + 1]; ids[ i + 1] = idtemp; loop = true; } } } // Randomize ties below int p1, p2; vector <int> tiepart; p1 = 0; p2 = 0; while ( p1 < n && p2 < n){ while ( p2 < n && v0[ p1] == v0[ p2]){ p2++; } p2--; if ( p1 < p2){ // when there is a tie tiepart.assign( ids.begin() + p1, ids.begin() + p2 + 1); randomizeOrder( tiepart, rne); for ( int j = 0; j <= p2 - p1; j++){ ids[ p1 + j] = tiepart[ j]; } p1 = p2 + 1; p2 = p1; } else { // when there is no tie p1++; p2 = p1; } } for ( int j = 0; j < n; j++){ retranks[ ids[ j]] = j + 1; } } /* dataの要素の順番を乱数によってランダマイズする。 dataの内容が書き換えられる。 乱数生成のためのRandomNumberEngineインスタンスを必要とする。 型Tに対して、代入演算子が定義されている必要がある。 */ template <typename T> void randomizeOrder( vector <T> &data, RandomNumberEngine &rne) { int n; vector <double> seq; bool loop; T temp; double tempd; n = data.size(); seq.clear(); seq.resize( n); for ( int i = 0; i < n; i++){ seq[ i] = rne.getRealUniform( 0.0, 1.0); } loop = true; while ( loop){ loop = false; for ( int i = 0; i < n - 1; i++){ if ( seq[ i] < seq[ i + 1]){ tempd = seq[ i]; seq[ i] = seq[ i + 1]; seq[ i + 1] = tempd; temp = data[ i]; data[ i] = data[ i + 1]; data[ i + 1] = temp; loop = true; } } } } /* dataの要素のうち、最大の要素の添え字(0~(size()-1))の集合をretに格納する。 最大の要素が複数ある場合には、retのsizeが2以上になる。 型Tに対して、不等号と等号が定義されている必要がある。 */ template <typename T> void getIndexOfMax( vector <int> &ret, const vector <T> &data) { int n; n = data.size(); ret.clear(); if ( n < 1){ alert( "getIndexOfMax()"); return; } ret.push_back( 0); for ( int i = 1; i < n; i++){ if ( data[ i] > data[ ret[ 0]]){ ret.clear(); ret.push_back( i); } else if ( data[ i] == data[ ret[ 0]]){ ret.push_back( i); } } } /* dataの要素のうち、最大の要素の添え字(0~(size()-1))を返す。 最大の要素が複数ある場合には、ランダムに等確率でいずれかを選んで添え字を返す。 その際のランダムネスはrneによってもたらされる。 型Tに対して、不等号と等号が定義されている必要がある。 */ template <typename T> int getIndexOfMaxRandomized( const vector <T> &data, RandomNumberEngine &rne) { vector <int> vec; getIndexOfMax( vec, data); if ( vec.size() > 1){ randomizeOrder( vec, rne); } else if ( vec.size() < 1){ alert( "getIndexOfMaxRandomized()"); return -1; } return vec[ 0]; } /* dataの要素のうち、最小の要素の添え字(0~(size()-1))の集合をretに格納する。 最小の要素が複数ある場合には、retのsizeが2以上になる。 型Tに対して、不等号と等号が定義されている必要がある。 */ template <typename T> void getIndexOfMin( vector <int> &ret, const vector <T> &data) { int n; n = data.size(); ret.clear(); if ( n < 1){ alert( "getIndexOfMin()"); return; } ret.push_back( 0); for ( int i = 1; i < n; i++){ if ( data[ i] < data[ ret[ 0]]){ ret.clear(); ret.push_back( i); } else if ( data[ i] == data[ ret[ 0]]){ ret.push_back( i); } } } /* dataの要素のうち、最小の要素の添え字(0~(size()-1))を返す。 最大の要素が複数ある場合には、ランダムに等確率でいずれかを選んで添え字を返す。 その際のランダムネスはrneによってもたらされる。 型Tに対して、不等号と等号が定義されている必要がある。 */ template <typename T> int getIndexOfMinRandomized( const vector <T> &data, RandomNumberEngine &rne) { vector <int> vec; getIndexOfMin( vec, data); if ( vec.size() > 1){ randomizeOrder( vec, rne); } else if ( vec.size() < 1){ alert( "getIndexOfMinRandomized()"); return -1; } return vec[ 0]; } /* dataの要素のうち、前方から探索して最初に見つかるeleと等しい要素のIndex(0はじまり)を返す。 見つからない場合は、-1を返す。 型Tに対して等号が定義されている必要がある。 */ template <typename T> int getIndexOfElement( const vector <T> &data, T ele) { typename vector <T> :: const_iterator pos; if ( data.size() < 1){ return -1; } pos = find( data.begin(), data.end(), ele); if ( pos == data.end()){ return -1; } return ( pos - data.begin()); } /* datavecとkeyvecはパラレルベクターであると見なし、 keyvec内を前方から探索し、最初に見つかるkeyと等しい要素の添え字に対応する、 datavecの要素を、ansにコピーする(代入演算子を用いる)。 見つかった場合はtrue、見つからない場合は、falseを返す。 型TKeyに等号が定義されている必要がある。 型TDataに代入演算子が定義されている必要がある。 */ template <typename TData, typename TKey> bool getCopyOfElementForKey( TData &ans, const vector <TData> &datavec, const vector <TKey> &keyvec, TKey key ) { int idx; if ( datavec.size() != keyvec.size()){ alert( "getCopyOfElementForKey()"); ans = TData(); return false; } idx = getIndexOfElement( keyvec, key); if ( idx == -1){ alert( "getCopyOfElementForKey()"); ans = TData(); return false; } ans = datavec[ idx]; return true; } /* datavecとkeyvecはパラレルベクターであると見なし、 keyvec内を前方から探索し、最初に見つかるkeyと等しい要素の添え字に対応する、 datavecの要素のアドレスを、ptrに代入する。 見つかった場合はtrue、見つからない場合は、falseを返す。 型TKeyに等号が定義されている必要がある。 */ template <typename TData, typename TKey> bool getPointerToElementForKey( TData * &ptr, const vector <TData> &datavec, const vector <TKey> &keyvec, TKey key){ int idx; if ( datavec.size() != keyvec.size()){ alert( "getPointerToElementForKey()"); ptr = NULL; return false; } idx = getIndexOfElement( keyvec, key); if ( idx == -1){ alert( "getPointerToElementForKey()"); ptr = NULL; return false; } ptr = &( datavec[ idx]); return true; } /* vecの要素の合計を返す。 合計とは、offsetの値に演算子+=を逐次適用していった結果である。 通常、offsetは0や0.0などの意味の値を指定する。 型Tに対して演算子=と+=が定義されている必要がある。 */ template <typename T> T getSumOfElements( const vector <T> &vec, T offset) { int n; T ret; n = vec.size(); ret = offset; for ( int i = 0; i < n; i++){ ret += vec[ i]; } return ret; } /* ********** Definitions of Member Functions ********** */ template <typename TKey, typename T> Paravec <TKey, T> :: Paravec( void) : keys(), values() { } template <typename TKey, typename T> Paravec <TKey, T> :: ~Paravec( void) { } /* Copies data from other object */ template <typename TKey, typename T> void Paravec <TKey, T> :: copyFrom( const Paravec &obj) { keys = obj.keys; values = obj.values; } /* Initializes pararell vectors by two vectors */ template <typename TKey, typename T> void Paravec <TKey, T> :: initialize( const vector <TKey> &keys0, const vector <T> &v0) { int n; bool b; n = keys0.size(); if ( v0.size() != n){ alert( "Paravec :: initialize()"); return; } // check about uniqueness of values in keys0 b = true; for ( int i = 0; i < n - 1; i++){ for ( int j = i + 1; j < n; j++){ if ( keys0[ i] == keys0[ j]){ b = false; } } } if ( b == false){ alert( "Paravec :: initialize()"); return; } keys = keys0; values = v0; } // returns true if the addition is done successfully // false otherwise. template <typename TKey, typename T> bool Paravec <TKey, T> :: addValue( TKey key0, T v0) { int n; n = values.size(); if ( n != keys.size()){ alert( "Paravec :: addValue()"); return false; } for ( int i = 0; i < n; i++){ if ( keys[ i] == key0){ alert( "Paravec :: addValue()"); return false; } } keys.push_back( key0); values.push_back( v0); return true; } // returns true if "key0" exists in the key vector template <typename TKey, typename T> bool Paravec <TKey, T> :: keyExists( TKey key0) const { int n; n = values.size(); for ( int i = 0; i < n; i++){ if ( keys[ i] == key0){ return true; } } return false; } // returns true if all the stored keys are unique template <typename TKey, typename T> bool Paravec <TKey, T> :: checkUniqueKeys( void) const { int n; bool b; n = keys.size(); if ( values.size() != n){ alert( "Paravec :: checkUniqueKeys()"); return false; } // check about uniqueness of values in keys b = true; for ( int i = 0; i < n - 1; i++){ for ( int j = i + 1; j < n; j++){ if ( keys[ i] == keys[ j]){ b = false; } } } return b; } // returns the size of vectors template <typename TKey, typename T> int Paravec <TKey, T> :: getSize( void) const { int n; n = keys.size(); if ( n != values.size()){ alert( "Paravec :: getSize()"); } return n; } // get "ret" contain the value corresponding to "key0" // returns true if it successfully found the key // returns false if it did not template <typename TKey, typename T> bool Paravec <TKey, T> :: getValueOfKey( T &ret, TKey key0) const { int n; n = keys.size(); if ( n != values.size()){ alert( "Paravec :: getValueOfKey()"); } for ( int i = 0; i < n; i++){ if ( keys[ i] == key0){ ret = values[ i]; return true; } } return false; } // returns const reference to vector "keys" itself template <typename TKey, typename T> const vector <TKey> & Paravec <TKey, T> :: getKeyVecRef( void) const { return keys; } // returns const reference to vector "values" itself template <typename TKey, typename T> const vector <T> & Paravec <TKey, T> :: getValueVecRef( void) const { return values; } // returns the reference to the element corresponding to "key0" // if failed, returns the reference to the first element template <typename TKey, typename T> T & Paravec <TKey, T> :: getElementRefOfKey( TKey key0) { int n; n = keys.size(); if ( n != values.size()){ alert( "Paravec :: getElementRefOfKey()"); } for ( int i = 0; i < n; i++){ if ( keys[ i] == key0){ return values[ i]; } } alert( "Paravec :: getElementRefOfKey()"); return values[ 0]; } #endif /* kalgo_cpp_include_guard */
19.254438
117
0.58528
[ "object", "vector" ]
fc0977296171c1967f0820cf5e47c2fb45888cf4
3,153
cpp
C++
eagleeye/render/RenderMapToCPU.cpp
MirrorYu/eagleeye
c251e7b3bc919673b41360212c38d5fda85bbe2f
[ "Apache-2.0" ]
12
2020-09-21T02:24:11.000Z
2022-03-10T03:02:03.000Z
eagleeye/render/RenderMapToCPU.cpp
MirrorYu/eagleeye
c251e7b3bc919673b41360212c38d5fda85bbe2f
[ "Apache-2.0" ]
1
2020-11-30T08:22:50.000Z
2020-11-30T08:22:50.000Z
eagleeye/render/RenderMapToCPU.cpp
MirrorYu/eagleeye
c251e7b3bc919673b41360212c38d5fda85bbe2f
[ "Apache-2.0" ]
3
2020-03-16T12:10:55.000Z
2021-07-20T09:58:15.000Z
#include "eagleeye/render/RenderMapToCPU.h" #include "eagleeye/basic/BGRARotateHWC.h" namespace eagleeye { RenderMapToCPU::RenderMapToCPU(){ // EAGLEEYE_SIGNAL_RECT this->setNumberOfInputSignals(1); // 1个输出端口 this->setNumberOfOutputSignals(1); this->setOutputPort(new ImageSignal<Array<unsigned char, 4>>(), 0); this->getOutputPort(0)->setSignalType(EAGLEEYE_SIGNAL_RGBA_IMAGE); } RenderMapToCPU::~RenderMapToCPU(){ } void RenderMapToCPU::executeNodeInfo(){ // 获取输入信号,获得实际渲染区域 ImageSignal<float>* input_sig = (ImageSignal<float>*)(this->getInputPort(0)); Matrix<float> render_region = input_sig->getData(); // 计算归一化坐标 int screen_w = this->getScreenW(); int screen_h = this->getScreenH(); int canvas_x = this->getCanvasX(); int canvas_y = this->getCanvasY(); int canvas_w = this->getCanvasW(); int canvas_h = this->getCanvasH(); if(canvas_w == 0 || canvas_h == 0){ canvas_x = 0; canvas_y = 0; canvas_w = this->getScreenW(); canvas_h = this->getScreenH(); } EAGLEEYE_LOGD("Canvas x %d y %d width %d height %d.", canvas_x, canvas_y, canvas_w, canvas_h); EAGLEEYE_LOGD("Screen width %d height %d.", screen_w, screen_h); bool enable_flip_up = true; int offset_x = 0; int offset_y = 0; int render_w = canvas_w; int render_h = canvas_h; if(render_region.rows() > 0 && render_region.cols() > 0){ // 基于渲染区域,获取 float x0 = render_region.at(0,0); float y0 = render_region.at(0,1); float w = render_region.at(0,2); float h = render_region.at(0,3); offset_x = (int)(x0 + 0.5f); offset_x = eagleeye_max(offset_x, 0); offset_y = (int)(y0 + 0.5f); offset_y = eagleeye_max(offset_y, 0); render_w = (int)(w + 0.5f); int t = render_w + offset_x; t = eagleeye_min(t, canvas_w); render_w = t - offset_x; render_h = (int)(h + 0.5f); t = render_h + offset_y; t = eagleeye_min(t, canvas_h); render_h = t - offset_y; } EAGLEEYE_LOGD("Screen render x=%d y=%d width=%d height=%d.", offset_x, offset_y, render_w, render_h); ImageSignal<Array<unsigned char, 4>>* output_sig = (ImageSignal<Array<unsigned char, 4>>*)(this->getOutputPort(0)); Matrix<Array<unsigned char, 4>> data = output_sig->getData(); if(data.rows() != render_h || data.cols() != render_w){ data = Matrix<Array<unsigned char,4>>(render_h, render_w); } if(m_temp.rows() != render_h || m_temp.cols() != render_w){ m_temp = Matrix<Array<unsigned char,4>>(render_h, render_w); } if(enable_flip_up){ unsigned char* temp_ptr = (unsigned char*)m_temp.dataptr(); glReadPixels(offset_x, offset_y, render_w, render_h, GL_RGBA, GL_UNSIGNED_BYTE, temp_ptr); unsigned char* ptr = (unsigned char*)(data.dataptr()); bgra_rotate_hwc(temp_ptr, ptr, render_w, render_h, 180); } else{ unsigned char* ptr = (unsigned char*)data.dataptr(); glReadPixels(offset_x, offset_y, render_w, render_h, GL_RGBA, GL_UNSIGNED_BYTE, ptr); } output_sig->setData(data); } } // namespace eagleeye
33.189474
119
0.643197
[ "render" ]
fc09b76d905f83255b8e2047eae3ffd38d2f8842
1,807
hpp
C++
qubus/include/qubus/qtl/IR/multi_index_expr.hpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
qubus/include/qubus/qtl/IR/multi_index_expr.hpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
qubus/include/qubus/qtl/IR/multi_index_expr.hpp
qubusproject/Qubus
0feb8d6df00459c5af402545dbe7c82ee3ec4b7c
[ "BSL-1.0" ]
null
null
null
#ifndef QUBUS_QTL_IR_MULTI_INDEX_EXPR_HPP #define QUBUS_QTL_IR_MULTI_INDEX_EXPR_HPP #include <hpx/config.hpp> #include <qubus/qtl/index.hpp> #include <qubus/IR/variable_declaration.hpp> #include <qubus/IR/access.hpp> #include <memory> #include <vector> namespace qubus { namespace qtl { class multi_index_expr final : public access_expr_base<multi_index_expr> { public: multi_index_expr() = default; explicit multi_index_expr(variable_declaration multi_index_, std::vector<variable_declaration> element_indices_); virtual ~multi_index_expr() = default; const variable_declaration& multi_index() const; const std::vector<variable_declaration>& element_indices() const; multi_index_expr* clone() const override final; const expression& child(std::size_t index) const override final; std::size_t arity() const override final; std::unique_ptr<expression> substitute_subexpressions( std::vector<std::unique_ptr<expression>> new_children) const override final; private: variable_declaration multi_index_; std::vector<variable_declaration> element_indices_; mutable annotation_map annotations_; }; bool operator==(const multi_index_expr& lhs, const multi_index_expr& rhs); bool operator!=(const multi_index_expr& lhs, const multi_index_expr& rhs); template <long int Rank> std::unique_ptr<multi_index_expr> capture_multi_index(const multi_index<Rank>& idx) { auto multi_index = idx.var(); std::vector<variable_declaration> element_indices; element_indices.reserve(idx.rank()); for (long int i = 0; i < idx.rank(); ++i) { element_indices.push_back(idx[i].var()); } return std::make_unique<multi_index_expr>(std::move(multi_index), std::move(element_indices)); } } } #endif
26.188406
98
0.740454
[ "vector" ]
fc0e8e58b35b82920c7c75cb0c279097534aab0a
48,656
cpp
C++
src/hierarchy.cpp
matt-deboer/QuadriFlow
cf07b472932c2fe7277de3800eb5b7a3eb46179f
[ "MIT" ]
null
null
null
src/hierarchy.cpp
matt-deboer/QuadriFlow
cf07b472932c2fe7277de3800eb5b7a3eb46179f
[ "MIT" ]
null
null
null
src/hierarchy.cpp
matt-deboer/QuadriFlow
cf07b472932c2fe7277de3800eb5b7a3eb46179f
[ "MIT" ]
null
null
null
#include "qflow/hierarchy.hpp" #include <fstream> #include <algorithm> #include <unordered_map> #include "qflow/config.hpp" #include "qflow/field-math.hpp" #include <queue> #include "qflow/localsat.hpp" #include "pcg32/pcg32.h" #ifdef WITH_TBB # include "tbb/tbb.h" # include "pss/parallel_stable_sort.h" #endif namespace qflow { Hierarchy::Hierarchy() { mAdj.resize(MAX_DEPTH + 1); mV.resize(MAX_DEPTH + 1); mN.resize(MAX_DEPTH + 1); mA.resize(MAX_DEPTH + 1); mPhases.resize(MAX_DEPTH + 1); mToLower.resize(MAX_DEPTH); mToUpper.resize(MAX_DEPTH); rng_seed = 0; mCQ.reserve(MAX_DEPTH + 1); mCQw.reserve(MAX_DEPTH + 1); mCO.reserve(MAX_DEPTH + 1); mCOw.reserve(MAX_DEPTH + 1); } #undef max void Hierarchy::Initialize(double scale, int with_scale) { this->with_scale = with_scale; generate_graph_coloring_deterministic(mAdj[0], mV[0].cols(), mPhases[0]); for (int i = 0; i < MAX_DEPTH; ++i) { DownsampleGraph(mAdj[i], mV[i], mN[i], mA[i], mV[i + 1], mN[i + 1], mA[i + 1], mToUpper[i], mToLower[i], mAdj[i + 1]); generate_graph_coloring_deterministic(mAdj[i + 1], mV[i + 1].cols(), mPhases[i + 1]); if (mV[i + 1].cols() == 1) { mAdj.resize(i + 2); mV.resize(i + 2); mN.resize(i + 2); mA.resize(i + 2); mToUpper.resize(i + 1); mToLower.resize(i + 1); break; } } mQ.resize(mV.size()); mO.resize(mV.size()); mS.resize(mV.size()); mK.resize(mV.size()); mCO.resize(mV.size()); mCOw.resize(mV.size()); mCQ.resize(mV.size()); mCQw.resize(mV.size()); //Set random seed srand(rng_seed); mScale = scale; for (int i = 0; i < mV.size(); ++i) { mQ[i].resize(mN[i].rows(), mN[i].cols()); mO[i].resize(mN[i].rows(), mN[i].cols()); mS[i].resize(2, mN[i].cols()); mK[i].resize(2, mN[i].cols()); for (int j = 0; j < mN[i].cols(); ++j) { Vector3d s, t; coordinate_system(mN[i].col(j), s, t); //rand() is not thread safe! double angle = ((double)rand()) / RAND_MAX * 2 * M_PI; double x = ((double)rand()) / RAND_MAX * 2 - 1.f; double y = ((double)rand()) / RAND_MAX * 2 - 1.f; mQ[i].col(j) = s * std::cos(angle) + t * std::sin(angle); mO[i].col(j) = mV[i].col(j) + (s * x + t * y) * scale; if (with_scale) { mS[i].col(j) = Vector2d(1.0f, 1.0f); mK[i].col(j) = Vector2d(0.0, 0.0); } } } #ifdef WITH_CUDA printf("copy to device...\n"); CopyToDevice(); printf("copy to device finish...\n"); #endif } #ifdef WITH_TBB void Hierarchy::generate_graph_coloring_deterministic(const AdjacentMatrix& adj, int size, std::vector<std::vector<int>>& phases) { struct ColorData { uint8_t nColors; uint32_t nNodes[256]; ColorData() : nColors(0) {} }; const uint8_t INVALID_COLOR = 0xFF; phases.clear(); /* Generate a permutation */ std::vector<uint32_t> perm(size); std::vector<tbb::spin_mutex> mutex(size); for (uint32_t i = 0; i < size; ++i) perm[i] = i; tbb::parallel_for(tbb::blocked_range<uint32_t>(0u, size, GRAIN_SIZE), [&](const tbb::blocked_range<uint32_t>& range) { pcg32 rng; rng.advance(range.begin()); for (uint32_t i = range.begin(); i != range.end(); ++i) { uint32_t j = i, k = rng.nextUInt(size - i) + i; if (j == k) continue; if (j > k) std::swap(j, k); tbb::spin_mutex::scoped_lock l0(mutex[j]); tbb::spin_mutex::scoped_lock l1(mutex[k]); std::swap(perm[j], perm[k]); } }); std::vector<uint8_t> color(size, INVALID_COLOR); ColorData colorData = tbb::parallel_reduce( tbb::blocked_range<uint32_t>(0u, size, GRAIN_SIZE), ColorData(), [&](const tbb::blocked_range<uint32_t>& range, ColorData colorData) -> ColorData { std::vector<uint32_t> neighborhood; bool possible_colors[256]; for (uint32_t pidx = range.begin(); pidx != range.end(); ++pidx) { uint32_t i = perm[pidx]; neighborhood.clear(); neighborhood.push_back(i); // for (const Link *link = adj[i]; link != adj[i + 1]; ++link) for (auto& link : adj[i]) neighborhood.push_back(link.id); std::sort(neighborhood.begin(), neighborhood.end()); for (uint32_t j : neighborhood) mutex[j].lock(); std::fill(possible_colors, possible_colors + colorData.nColors, true); // for (const Link *link = adj[i]; link != adj[i + 1]; ++link) { for (auto& link : adj[i]) { uint8_t c = color[link.id]; if (c != INVALID_COLOR) { while (c >= colorData.nColors) { possible_colors[colorData.nColors] = true; colorData.nNodes[colorData.nColors] = 0; colorData.nColors++; } possible_colors[c] = false; } } uint8_t chosen_color = INVALID_COLOR; for (uint8_t j = 0; j < colorData.nColors; ++j) { if (possible_colors[j]) { chosen_color = j; break; } } if (chosen_color == INVALID_COLOR) { if (colorData.nColors == INVALID_COLOR - 1) throw std::runtime_error( "Ran out of colors during graph coloring! " "The input mesh is very likely corrupt."); colorData.nNodes[colorData.nColors] = 1; color[i] = colorData.nColors++; } else { colorData.nNodes[chosen_color]++; color[i] = chosen_color; } for (uint32_t j : neighborhood) mutex[j].unlock(); } return colorData; }, [](ColorData c1, ColorData c2) -> ColorData { ColorData result; result.nColors = std::max(c1.nColors, c2.nColors); memset(result.nNodes, 0, sizeof(uint32_t) * result.nColors); for (uint8_t i = 0; i < c1.nColors; ++i) result.nNodes[i] += c1.nNodes[i]; for (uint8_t i = 0; i < c2.nColors; ++i) result.nNodes[i] += c2.nNodes[i]; return result; }); phases.resize(colorData.nColors); for (int i = 0; i < colorData.nColors; ++i) phases[i].reserve(colorData.nNodes[i]); for (uint32_t i = 0; i < size; ++i) phases[color[i]].push_back(i); } #else void Hierarchy::generate_graph_coloring_deterministic(const AdjacentMatrix& adj, int size, std::vector<std::vector<int>>& phases) { phases.clear(); std::vector<uint32_t> perm(size); for (uint32_t i = 0; i < size; ++i) perm[i] = i; pcg32 rng; rng.shuffle(perm.begin(), perm.end()); std::vector<int> color(size, -1); std::vector<uint8_t> possible_colors; std::vector<int> size_per_color; int ncolors = 0; for (uint32_t i = 0; i < size; ++i) { uint32_t ip = perm[i]; std::fill(possible_colors.begin(), possible_colors.end(), 1); for (auto& link : adj[ip]) { int c = color[link.id]; if (c >= 0) possible_colors[c] = 0; } int chosen_color = -1; for (uint32_t j = 0; j < possible_colors.size(); ++j) { if (possible_colors[j]) { chosen_color = j; break; } } if (chosen_color < 0) { chosen_color = ncolors++; possible_colors.resize(ncolors); size_per_color.push_back(0); } color[ip] = chosen_color; size_per_color[chosen_color]++; } phases.resize(ncolors); for (int i = 0; i < ncolors; ++i) phases[i].reserve(size_per_color[i]); for (uint32_t i = 0; i < size; ++i) phases[color[i]].push_back(i); } #endif void Hierarchy::DownsampleGraph(const AdjacentMatrix adj, const MatrixXd& V, const MatrixXd& N, const VectorXd& A, MatrixXd& V_p, MatrixXd& N_p, VectorXd& A_p, MatrixXi& to_upper, VectorXi& to_lower, AdjacentMatrix& adj_p) { struct Entry { int i, j; double order; inline Entry() { i = j = -1; }; inline Entry(int i, int j, double order) : i(i), j(j), order(order) {} inline bool operator<(const Entry& e) const { return order > e.order; } inline bool operator==(const Entry& e) const { return order == e.order; } }; int nLinks = 0; for (auto& adj_i : adj) nLinks += adj_i.size(); std::vector<Entry> entries(nLinks); std::vector<int> bases(adj.size()); for (int i = 1; i < bases.size(); ++i) { bases[i] = bases[i - 1] + adj[i - 1].size(); } #ifdef WITH_OMP #pragma omp parallel for #endif for (int i = 0; i < V.cols(); ++i) { int base = bases[i]; auto& ad = adj[i]; auto entry_it = entries.begin() + base; for (auto it = ad.begin(); it != ad.end(); ++it, ++entry_it) { int k = it->id; double dp = N.col(i).dot(N.col(k)); double ratio = A[i] > A[k] ? (A[i] / A[k]) : (A[k] / A[i]); *entry_it = Entry(i, k, dp * ratio); } } #ifdef WITH_TBB pss::parallel_stable_sort(entries.begin(), entries.end(), std::less<Entry>()); #else std::stable_sort(entries.begin(), entries.end(), std::less<Entry>()); #endif std::vector<bool> mergeFlag(V.cols(), false); int nCollapsed = 0; for (int i = 0; i < nLinks; ++i) { const Entry& e = entries[i]; if (mergeFlag[e.i] || mergeFlag[e.j]) continue; mergeFlag[e.i] = mergeFlag[e.j] = true; entries[nCollapsed++] = entries[i]; } int vertexCount = V.cols() - nCollapsed; // Allocate memory for coarsened graph V_p.resize(3, vertexCount); N_p.resize(3, vertexCount); A_p.resize(vertexCount); to_upper.resize(2, vertexCount); to_lower.resize(V.cols()); #ifdef WITH_OMP #pragma omp parallel for #endif for (int i = 0; i < nCollapsed; ++i) { const Entry& e = entries[i]; const double area1 = A[e.i], area2 = A[e.j], surfaceArea = area1 + area2; if (surfaceArea > RCPOVERFLOW) V_p.col(i) = (V.col(e.i) * area1 + V.col(e.j) * area2) / surfaceArea; else V_p.col(i) = (V.col(e.i) + V.col(e.j)) * 0.5f; Vector3d normal = N.col(e.i) * area1 + N.col(e.j) * area2; double norm = normal.norm(); N_p.col(i) = norm > RCPOVERFLOW ? Vector3d(normal / norm) : Vector3d::UnitX(); A_p[i] = surfaceArea; to_upper.col(i) << e.i, e.j; to_lower[e.i] = i; to_lower[e.j] = i; } int offset = nCollapsed; for (int i = 0; i < V.cols(); ++i) { if (!mergeFlag[i]) { int idx = offset++; V_p.col(idx) = V.col(i); N_p.col(idx) = N.col(i); A_p[idx] = A[i]; to_upper.col(idx) << i, -1; to_lower[i] = idx; } } adj_p.resize(V_p.cols()); std::vector<int> capacity(V_p.cols()); std::vector<std::vector<Link>> scratches(V_p.cols()); #ifdef WITH_OMP #pragma omp parallel for #endif for (int i = 0; i < V_p.cols(); ++i) { int t = 0; for (int j = 0; j < 2; ++j) { int upper = to_upper(j, i); if (upper == -1) continue; t += adj[upper].size(); } scratches[i].reserve(t); adj_p[i].reserve(t); } #ifdef WITH_OMP #pragma omp parallel for #endif for (int i = 0; i < V_p.cols(); ++i) { auto& scratch = scratches[i]; for (int j = 0; j < 2; ++j) { int upper = to_upper(j, i); if (upper == -1) continue; auto& ad = adj[upper]; for (auto& link : ad) scratch.push_back(Link(to_lower[link.id], link.weight)); } std::sort(scratch.begin(), scratch.end()); int id = -1; auto& ad = adj_p[i]; for (auto& link : scratch) { if (link.id != i) { if (id != link.id) { ad.push_back(link); id = link.id; } else { ad.back().weight += link.weight; } } } } } void Hierarchy::SaveToFile(FILE* fp) { Save(fp, mScale); Save(fp, mF); Save(fp, mE2E); Save(fp, mAdj); Save(fp, mV); Save(fp, mN); Save(fp, mA); Save(fp, mToLower); Save(fp, mToUpper); Save(fp, mQ); Save(fp, mO); Save(fp, mS); Save(fp, mK); Save(fp, this->mPhases); } void Hierarchy::LoadFromFile(FILE* fp) { Read(fp, mScale); Read(fp, mF); Read(fp, mE2E); Read(fp, mAdj); Read(fp, mV); Read(fp, mN); Read(fp, mA); Read(fp, mToLower); Read(fp, mToUpper); Read(fp, mQ); Read(fp, mO); Read(fp, mS); Read(fp, mK); Read(fp, this->mPhases); } void Hierarchy::UpdateGraphValue(std::vector<Vector3i>& FQ, std::vector<Vector3i>& F2E, std::vector<Vector2i>& edge_diff) { FQ = std::move(mFQ[0]); F2E = std::move(mF2E[0]); edge_diff = std::move(mEdgeDiff[0]); } void Hierarchy::DownsampleEdgeGraph(std::vector<Vector3i>& FQ, std::vector<Vector3i>& F2E, std::vector<Vector2i>& edge_diff, std::vector<int>& allow_changes, int level) { std::vector<Vector2i> E2F(edge_diff.size(), Vector2i(-1, -1)); for (int i = 0; i < F2E.size(); ++i) { for (int j = 0; j < 3; ++j) { int e = F2E[i][j]; if (E2F[e][0] == -1) E2F[e][0] = i; else E2F[e][1] = i; } } int levels = (level == -1) ? 100 : level; mFQ.resize(levels); mF2E.resize(levels); mE2F.resize(levels); mEdgeDiff.resize(levels); mAllowChanges.resize(levels); mSing.resize(levels); mToUpperEdges.resize(levels - 1); mToUpperOrients.resize(levels - 1); for (int i = 0; i < FQ.size(); ++i) { Vector2i diff(0, 0); for (int j = 0; j < 3; ++j) { diff += rshift90(edge_diff[F2E[i][j]], FQ[i][j]); } if (diff != Vector2i::Zero()) { mSing[0].push_back(i); } } mAllowChanges[0] = allow_changes; mFQ[0] = std::move(FQ); mF2E[0] = std::move(F2E); mE2F[0] = std::move(E2F); mEdgeDiff[0] = std::move(edge_diff); for (int l = 0; l < levels - 1; ++l) { auto& FQ = mFQ[l]; auto& E2F = mE2F[l]; auto& F2E = mF2E[l]; auto& Allow = mAllowChanges[l]; auto& EdgeDiff = mEdgeDiff[l]; auto& Sing = mSing[l]; std::vector<int> fixed_faces(F2E.size(), 0); for (auto& s : Sing) { fixed_faces[s] = 1; } auto& toUpper = mToUpperEdges[l]; auto& toUpperOrients = mToUpperOrients[l]; toUpper.resize(E2F.size(), -1); toUpperOrients.resize(E2F.size(), 0); auto& nFQ = mFQ[l + 1]; auto& nE2F = mE2F[l + 1]; auto& nF2E = mF2E[l + 1]; auto& nAllow = mAllowChanges[l + 1]; auto& nEdgeDiff = mEdgeDiff[l + 1]; auto& nSing = mSing[l + 1]; for (int i = 0; i < E2F.size(); ++i) { if (EdgeDiff[i] != Vector2i::Zero()) continue; if ((E2F[i][0] >= 0 && fixed_faces[E2F[i][0]]) || (E2F[i][1] >= 0 && fixed_faces[E2F[i][1]])) { continue; } for (int j = 0; j < 2; ++j) { int f = E2F[i][j]; if (f < 0) continue; for (int k = 0; k < 3; ++k) { int neighbor_e = F2E[f][k]; for (int m = 0; m < 2; ++m) { int neighbor_f = E2F[neighbor_e][m]; if (neighbor_f < 0) continue; if (fixed_faces[neighbor_f] == 0) fixed_faces[neighbor_f] = 1; } } } if (E2F[i][0] >= 0) fixed_faces[E2F[i][0]] = 2; if (E2F[i][1] >= 0) fixed_faces[E2F[i][1]] = 2; toUpper[i] = -2; } for (int i = 0; i < E2F.size(); ++i) { if (toUpper[i] == -2) continue; if ((E2F[i][0] < 0 || fixed_faces[E2F[i][0]] == 2) && (E2F[i][1] < 0 || fixed_faces[E2F[i][1]] == 2)) { toUpper[i] = -3; continue; } } int numE = 0; for (int i = 0; i < toUpper.size(); ++i) { if (toUpper[i] == -1) { if ((E2F[i][0] < 0 || fixed_faces[E2F[i][0]] < 2) && (E2F[i][1] < 0 || fixed_faces[E2F[i][1]] < 2)) { nE2F.push_back(E2F[i]); toUpperOrients[i] = 0; toUpper[i] = numE++; continue; } int f0 = (E2F[i][1] < 0 || fixed_faces[E2F[i][0]] < 2) ? E2F[i][0] : E2F[i][1]; int e = i; int f = f0; std::vector<std::pair<int, int>> paths; paths.push_back(std::make_pair(i, 0)); while (true) { if (E2F[e][0] == f) f = E2F[e][1]; else if (E2F[e][1] == f) f = E2F[e][0]; if (f < 0 || fixed_faces[f] < 2) { for (int j = 0; j < paths.size(); ++j) { auto& p = paths[j]; toUpper[p.first] = numE; int orient = p.second; if (j > 0) orient = (orient + toUpperOrients[paths[j - 1].first]) % 4; toUpperOrients[p.first] = orient; } nE2F.push_back(Vector2i(f0, f)); numE += 1; break; } int ind0 = -1, ind1 = -1; int e0 = e; for (int j = 0; j < 3; ++j) { if (F2E[f][j] == e) { ind0 = j; break; } } for (int j = 0; j < 3; ++j) { int e1 = F2E[f][j]; if (e1 != e && toUpper[e1] != -2) { e = e1; ind1 = j; break; } } if (ind1 != -1) { paths.push_back(std::make_pair(e, (FQ[f][ind1] - FQ[f][ind0] + 6) % 4)); } else { if (EdgeDiff[e] != Vector2i::Zero()) { printf("Unsatisfied !!!...\n"); printf("%d %d %d: %d %d\n", F2E[f][0], F2E[f][1], F2E[f][2], e0, e); exit(0); } for (auto& p : paths) { toUpper[p.first] = numE; toUpperOrients[p.first] = 0; } numE += 1; nE2F.push_back(Vector2i(f0, f0)); break; } } } } nEdgeDiff.resize(numE); nAllow.resize(numE * 2, 1); for (int i = 0; i < toUpper.size(); ++i) { if (toUpper[i] >= 0 && toUpperOrients[i] == 0) { nEdgeDiff[toUpper[i]] = EdgeDiff[i]; } if (toUpper[i] >= 0) { int dimension = toUpperOrients[i] % 2; if (Allow[i * 2 + dimension] == 0) nAllow[toUpper[i] * 2] = 0; else if (Allow[i * 2 + dimension] == 2) nAllow[toUpper[i] * 2] = 2; if (Allow[i * 2 + 1 - dimension] == 0) nAllow[toUpper[i] * 2 + 1] = 0; else if (Allow[i * 2 + 1 - dimension] == 2) nAllow[toUpper[i] * 2 + 1] = 2; } } std::vector<int> upperface(F2E.size(), -1); for (int i = 0; i < F2E.size(); ++i) { Vector3i eid; for (int j = 0; j < 3; ++j) { eid[j] = toUpper[F2E[i][j]]; } if (eid[0] >= 0 && eid[1] >= 0 && eid[2] >= 0) { Vector3i eid_orient; for (int j = 0; j < 3; ++j) { eid_orient[j] = (FQ[i][j] + 4 - toUpperOrients[F2E[i][j]]) % 4; } upperface[i] = nF2E.size(); nF2E.push_back(eid); nFQ.push_back(eid_orient); } } for (int i = 0; i < nE2F.size(); ++i) { for (int j = 0; j < 2; ++j) { if (nE2F[i][j] >= 0) nE2F[i][j] = upperface[nE2F[i][j]]; } } for (auto& s : Sing) { if (upperface[s] >= 0) nSing.push_back(upperface[s]); } mToUpperFaces.push_back(std::move(upperface)); if (nEdgeDiff.size() == EdgeDiff.size()) { levels = l + 1; break; } } mFQ.resize(levels); mF2E.resize(levels); mAllowChanges.resize(levels); mE2F.resize(levels); mEdgeDiff.resize(levels); mSing.resize(levels); mToUpperEdges.resize(levels - 1); mToUpperOrients.resize(levels - 1); } int Hierarchy::FixFlipSat(int depth, int threshold) { if (system("which minisat > /dev/null 2>&1")) { printf("minisat not found, \"-sat\" will not be used!\n"); return 0; } if (system("which timeout > /dev/null 2>&1")) { printf("timeout not found, \"-sat\" will not be used!\n"); return 0; } auto& F2E = mF2E[depth]; auto& E2F = mE2F[depth]; auto& FQ = mFQ[depth]; auto& EdgeDiff = mEdgeDiff[depth]; auto& AllowChanges = mAllowChanges[depth]; // build E2E std::vector<int> E2E(F2E.size() * 3, -1); for (int i = 0; i < E2F.size(); ++i) { int f1 = E2F[i][0]; int f2 = E2F[i][1]; int t1 = 0; int t2 = 2; if (f1 != -1) while (F2E[f1][t1] != i) t1 += 1; if (f2 != -1) while (F2E[f2][t2] != i) t2 -= 1; t1 += f1 * 3; t2 += f2 * 3; if (f1 != -1) E2E[t1] = (f2 == -1) ? -1 : t2; if (f2 != -1) E2E[t2] = (f1 == -1) ? -1 : t1; } auto IntegerArea = [&](int f) { Vector2i diff1 = rshift90(EdgeDiff[F2E[f][0]], FQ[f][0]); Vector2i diff2 = rshift90(EdgeDiff[F2E[f][1]], FQ[f][1]); return diff1[0] * diff2[1] - diff1[1] * diff2[0]; }; std::deque<std::pair<int, int>> Q; std::vector<bool> mark_dedges(F2E.size() * 3, false); for (int f = 0; f < F2E.size(); ++f) { if (IntegerArea(f) < 0) { for (int j = 0; j < 3; ++j) { if (mark_dedges[f * 3 + j]) continue; Q.push_back(std::make_pair(f * 3 + j, 0)); mark_dedges[f * 3 + j] = true; } } } int mark_count = 0; while (!Q.empty()) { int e0 = Q.front().first; int depth = Q.front().second; Q.pop_front(); mark_count++; int e = e0, e1; do { e1 = E2E[e]; if (e1 == -1) break; int length = EdgeDiff[F2E[e1 / 3][e1 % 3]].array().abs().sum(); if (length == 0 && !mark_dedges[e1]) { mark_dedges[e1] = true; Q.push_front(std::make_pair(e1, depth)); } e = (e1 / 3) * 3 + (e1 + 1) % 3; mark_dedges[e] = true; } while (e != e0); if (e1 == -1) { do { e1 = E2E[e]; if (e1 == -1) break; int length = EdgeDiff[F2E[e1 / 3][e1 % 3]].array().abs().sum(); if (length == 0 && !mark_dedges[e1]) { mark_dedges[e1] = true; Q.push_front(std::make_pair(e1, depth)); } e = (e1 / 3) * 3 + (e1 + 2) % 3; mark_dedges[e] = true; } while (e != e0); } do { e1 = E2E[e]; if (e1 == -1) break; int length = EdgeDiff[F2E[e1 / 3][e1 % 3]].array().abs().sum(); if (length > 0 && depth + length <= threshold && !mark_dedges[e1]) { mark_dedges[e1] = true; Q.push_back(std::make_pair(e1, depth + length)); } e = e1 / 3 * 3 + (e1 + 1) % 3; mark_dedges[e] = true; } while (e != e0); if (e1 == -1) { do { e1 = E2E[e]; if (e1 == -1) break; int length = EdgeDiff[F2E[e1 / 3][e1 % 3]].array().abs().sum(); if (length > 0 && depth + length <= threshold && !mark_dedges[e1]) { mark_dedges[e1] = true; Q.push_back(std::make_pair(e1, depth + length)); } e = e1 / 3 * 3 + (e1 + 2) % 3; mark_dedges[e] = true; } while (e != e0); } } lprintf("[FlipH] Depth %2d: marked = %d\n", depth, mark_count); std::vector<bool> flexible(EdgeDiff.size(), false); for (int i = 0; i < F2E.size(); ++i) { for (int j = 0; j < 3; ++j) { int dedge = i * 3 + j; int edgeid = F2E[i][j]; if (mark_dedges[dedge]) { flexible[edgeid] = true; } } } for (int i = 0; i < flexible.size(); ++i) { if (E2F[i][0] == E2F[i][1]) flexible[i] = false; if (AllowChanges[i] == 0) flexible[i] = false; } // Reindexing and solve int num_group = 0; std::vector<int> groups(EdgeDiff.size(), -1); std::vector<int> indices(EdgeDiff.size(), -1); for (int i = 0; i < EdgeDiff.size(); ++i) { if (groups[i] == -1 && flexible[i]) { // group it std::queue<int> q; q.push(i); groups[i] = num_group; while (!q.empty()) { int e = q.front(); q.pop(); int f[] = {E2F[e][0], E2F[e][1]}; for (int j = 0; j < 2; ++j) { if (f[j] == -1) continue; for (int k = 0; k < 3; ++k) { int e1 = F2E[f[j]][k]; if (flexible[e1] && groups[e1] == -1) { groups[e1] = num_group; q.push(e1); } } } } num_group += 1; } } std::vector<int> num_edges(num_group); std::vector<int> num_flips(num_group); std::vector<std::vector<int>> values(num_group); std::vector<std::vector<Vector3i>> variable_eq(num_group); std::vector<std::vector<Vector3i>> constant_eq(num_group); std::vector<std::vector<Vector4i>> variable_ge(num_group); std::vector<std::vector<Vector2i>> constant_ge(num_group); for (int i = 0; i < groups.size(); ++i) { if (groups[i] != -1) { indices[i] = num_edges[groups[i]]++; values[groups[i]].push_back(EdgeDiff[i][0]); values[groups[i]].push_back(EdgeDiff[i][1]); } } std::vector<int> num_edges_flexible = num_edges; std::map<std::pair<int, int>, int> fixed_variables; for (int i = 0; i < F2E.size(); ++i) { Vector2i var[3]; Vector2i cst[3]; int gind = 0; while (gind < 3 && groups[F2E[i][gind]] == -1) gind += 1; if (gind == 3) continue; int group = groups[F2E[i][gind]]; int ind[3] = {-1, -1, -1}; for (int j = 0; j < 3; ++j) { int g = groups[F2E[i][j]]; if (g != group) { if (g == -1) { auto key = std::make_pair(F2E[i][j], group); auto it = fixed_variables.find(key); if (it == fixed_variables.end()) { ind[j] = num_edges[group]; values[group].push_back(EdgeDiff[F2E[i][j]][0]); values[group].push_back(EdgeDiff[F2E[i][j]][1]); fixed_variables[key] = num_edges[group]++; } else { ind[j] = it->second; } } } else { ind[j] = indices[F2E[i][j]]; } } for (int j = 0; j < 3; ++j) assert(ind[j] != -1); for (int j = 0; j < 3; ++j) { var[j] = rshift90(Vector2i(ind[j] * 2 + 1, ind[j] * 2 + 2), FQ[i][j]); cst[j] = var[j].array().sign(); var[j] = var[j].array().abs() - 1; } num_flips[group] += IntegerArea(i) < 0; variable_eq[group].push_back(Vector3i(var[0][0], var[1][0], var[2][0])); constant_eq[group].push_back(Vector3i(cst[0][0], cst[1][0], cst[2][0])); variable_eq[group].push_back(Vector3i(var[0][1], var[1][1], var[2][1])); constant_eq[group].push_back(Vector3i(cst[0][1], cst[1][1], cst[2][1])); variable_ge[group].push_back(Vector4i(var[0][0], var[1][1], var[0][1], var[1][0])); constant_ge[group].push_back(Vector2i(cst[0][0] * cst[1][1], cst[0][1] * cst[1][0])); } int flip_before = 0, flip_after = 0; for (int i = 0; i < F2E.size(); ++i) { int area = IntegerArea(i); if (area < 0) flip_before++; } for (int i = 0; i < num_group; ++i) { std::vector<bool> flexible(values[i].size(), true); for (int j = num_edges_flexible[i] * 2; j < flexible.size(); ++j) { flexible[j] = false; } SolveSatProblem(values[i].size(), values[i], flexible, variable_eq[i], constant_eq[i], variable_ge[i], constant_ge[i]); } for (int i = 0; i < EdgeDiff.size(); ++i) { int group = groups[i]; if (group == -1) continue; EdgeDiff[i][0] = values[group][2 * indices[i] + 0]; EdgeDiff[i][1] = values[group][2 * indices[i] + 1]; } for (int i = 0; i < F2E.size(); ++i) { Vector2i diff(0, 0); for (int j = 0; j < 3; ++j) { diff += rshift90(EdgeDiff[F2E[i][j]], FQ[i][j]); } assert(diff == Vector2i::Zero()); int area = IntegerArea(i); if (area < 0) flip_after++; } lprintf("[FlipH] FlipArea, Before: %d After %d\n", flip_before, flip_after); return flip_after; } void Hierarchy::PushDownwardFlip(int depth) { auto& EdgeDiff = mEdgeDiff[depth]; auto& nEdgeDiff = mEdgeDiff[depth - 1]; auto& toUpper = mToUpperEdges[depth - 1]; auto& toUpperOrients = mToUpperOrients[depth - 1]; auto& toUpperFaces = mToUpperFaces[depth - 1]; for (int i = 0; i < toUpper.size(); ++i) { if (toUpper[i] >= 0) { int orient = (4 - toUpperOrients[i]) % 4; nEdgeDiff[i] = rshift90(EdgeDiff[toUpper[i]], orient); } else { nEdgeDiff[i] = Vector2i(0, 0); } } auto& nF2E = mF2E[depth - 1]; auto& nFQ = mFQ[depth - 1]; for (int i = 0; i < nF2E.size(); ++i) { Vector2i diff(0, 0); for (int j = 0; j < 3; ++j) { diff += rshift90(nEdgeDiff[nF2E[i][j]], nFQ[i][j]); } if (diff != Vector2i::Zero()) { printf("Fail!!!!!!! %d\n", i); for (int j = 0; j < 3; ++j) { Vector2i d = rshift90(nEdgeDiff[nF2E[i][j]], nFQ[i][j]); printf("<%d %d %d>\n", nF2E[i][j], nFQ[i][j], toUpperOrients[nF2E[i][j]]); printf("%d %d\n", d[0], d[1]); printf("%d -> %d\n", nF2E[i][j], toUpper[nF2E[i][j]]); } printf("%d -> %d\n", i, toUpperFaces[i]); exit(1); } } } void Hierarchy::FixFlip() { int l = mF2E.size() - 1; auto& F2E = mF2E[l]; auto& E2F = mE2F[l]; auto& FQ = mFQ[l]; auto& EdgeDiff = mEdgeDiff[l]; auto& AllowChange = mAllowChanges[l]; // build E2E std::vector<int> E2E(F2E.size() * 3, -1); for (int i = 0; i < E2F.size(); ++i) { int v1 = E2F[i][0]; int v2 = E2F[i][1]; int t1 = 0; int t2 = 2; if (v1 != -1) while (F2E[v1][t1] != i) t1 += 1; if (v2 != -1) while (F2E[v2][t2] != i) t2 -= 1; t1 += v1 * 3; t2 += v2 * 3; if (v1 != -1) E2E[t1] = (v2 == -1) ? -1 : t2; if (v2 != -1) E2E[t2] = (v1 == -1) ? -1 : t1; } auto Area = [&](int f) { Vector2i diff1 = rshift90(EdgeDiff[F2E[f][0]], FQ[f][0]); Vector2i diff2 = rshift90(EdgeDiff[F2E[f][1]], FQ[f][1]); return diff1[0] * diff2[1] - diff1[1] * diff2[0]; }; std::vector<int> valences(F2E.size() * 3, -10000); // comment this line auto CheckShrink = [&](int deid, int allowed_edge_length) { // Check if we want shrink direct edge deid so that all edge length is smaller than // allowed_edge_length if (deid == -1) { return false; } std::vector<int> corresponding_faces; std::vector<int> corresponding_edges; std::vector<Vector2i> corresponding_diff; int deid0 = deid; while (deid != -1) { deid = deid / 3 * 3 + (deid + 2) % 3; if (E2E[deid] == -1) break; deid = E2E[deid]; if (deid == deid0) break; } Vector2i diff = EdgeDiff[F2E[deid / 3][deid % 3]]; do { corresponding_diff.push_back(diff); corresponding_edges.push_back(deid); corresponding_faces.push_back(deid / 3); // transform to the next face deid = E2E[deid]; if (deid == -1) { return false; } // transform for the target incremental diff diff = -rshift90(diff, FQ[deid / 3][deid % 3]); deid = deid / 3 * 3 + (deid + 1) % 3; // transform to local diff = rshift90(diff, (4 - FQ[deid / 3][deid % 3]) % 4); } while (deid != corresponding_edges.front()); // check diff if (deid != -1 && diff != corresponding_diff.front()) { return false; } std::unordered_map<int, Vector2i> new_values; for (int i = 0; i < corresponding_diff.size(); ++i) { int deid = corresponding_edges[i]; int eid = F2E[deid / 3][deid % 3]; new_values[eid] = EdgeDiff[eid]; } for (int i = 0; i < corresponding_diff.size(); ++i) { int deid = corresponding_edges[i]; int eid = F2E[deid / 3][deid % 3]; for (int j = 0; j < 2; ++j) { if (corresponding_diff[i][j] != 0 && AllowChange[eid * 2 + j] == 0) return false; } auto& res = new_values[eid]; res -= corresponding_diff[i]; int edge_thres = allowed_edge_length; if (abs(res[0]) > edge_thres || abs(res[1]) > edge_thres) { return false; } if ((abs(res[0]) > 1 && abs(res[1]) != 0) || (abs(res[1]) > 1 && abs(res[0]) != 0)) return false; } int prev_area = 0, current_area = 0; for (int f = 0; f < corresponding_faces.size(); ++f) { int area = Area(corresponding_faces[f]); if (area < 0) prev_area += 1; } for (auto& p : new_values) { std::swap(EdgeDiff[p.first], p.second); } for (int f = 0; f < corresponding_faces.size(); ++f) { int area = Area(corresponding_faces[f]); if (area < 0) { current_area += 1; } } if (current_area < prev_area) { return true; } for (auto& p : new_values) { std::swap(EdgeDiff[p.first], p.second); } return false; }; std::queue<int> flipped; for (int i = 0; i < F2E.size(); ++i) { int area = Area(i); if (area < 0) { flipped.push(i); } } bool update = false; int max_len = 1; while (!update && max_len <= 2) { while (!flipped.empty()) { int f = flipped.front(); if (Area(f) >= 0) { flipped.pop(); continue; } for (int i = 0; i < 3; ++i) { if (CheckShrink(f * 3 + i, max_len) || CheckShrink(E2E[f * 3 + i], max_len)) { update = true; break; } } flipped.pop(); } max_len += 1; } if (update) { Hierarchy flip_hierarchy; flip_hierarchy.DownsampleEdgeGraph(mFQ.back(), mF2E.back(), mEdgeDiff.back(), mAllowChanges.back(), -1); flip_hierarchy.FixFlip(); flip_hierarchy.UpdateGraphValue(mFQ.back(), mF2E.back(), mEdgeDiff.back()); } PropagateEdge(); } void Hierarchy::PropagateEdge() { for (int level = mToUpperEdges.size(); level > 0; --level) { auto& EdgeDiff = mEdgeDiff[level]; auto& nEdgeDiff = mEdgeDiff[level - 1]; auto& FQ = mFQ[level]; auto& nFQ = mFQ[level - 1]; auto& F2E = mF2E[level - 1]; auto& toUpper = mToUpperEdges[level - 1]; auto& toUpperFace = mToUpperFaces[level - 1]; auto& toUpperOrients = mToUpperOrients[level - 1]; for (int i = 0; i < toUpper.size(); ++i) { if (toUpper[i] >= 0) { int orient = (4 - toUpperOrients[i]) % 4; nEdgeDiff[i] = rshift90(EdgeDiff[toUpper[i]], orient); } else { nEdgeDiff[i] = Vector2i(0, 0); } } for (int i = 0; i < toUpperFace.size(); ++i) { if (toUpperFace[i] == -1) continue; Vector3i eid_orient = FQ[toUpperFace[i]]; for (int j = 0; j < 3; ++j) { nFQ[i][j] = (eid_orient[j] + toUpperOrients[F2E[i][j]]) % 4; } } } } void Hierarchy::clearConstraints() { int levels = mV.size(); if (levels == 0) return; for (int i = 0; i < levels; ++i) { int size = mV[i].cols(); mCQ[i].resize(3, size); mCO[i].resize(3, size); mCQw[i].resize(size); mCOw[i].resize(size); mCQw[i].setZero(); mCOw[i].setZero(); } } void Hierarchy::propagateConstraints() { int levels = mV.size(); if (levels == 0) return; for (int l = 0; l < levels - 1; ++l) { auto& N = mN[l]; auto& N_next = mN[l + 1]; auto& V = mV[l]; auto& V_next = mV[l + 1]; auto& CQ = mCQ[l]; auto& CQ_next = mCQ[l + 1]; auto& CQw = mCQw[l]; auto& CQw_next = mCQw[l + 1]; auto& CO = mCO[l]; auto& CO_next = mCO[l + 1]; auto& COw = mCOw[l]; auto& COw_next = mCOw[l + 1]; auto& toUpper = mToUpper[l]; MatrixXd& S = mS[l]; for (uint32_t i = 0; i != mV[l + 1].cols(); ++i) { Vector2i upper = toUpper.col(i); Vector3d cq = Vector3d::Zero(), co = Vector3d::Zero(); float cqw = 0.0f, cow = 0.0f; bool has_cq0 = CQw[upper[0]] != 0; bool has_cq1 = upper[1] != -1 && CQw[upper[1]] != 0; bool has_co0 = COw[upper[0]] != 0; bool has_co1 = upper[1] != -1 && COw[upper[1]] != 0; if (has_cq0 && !has_cq1) { cq = CQ.col(upper[0]); cqw = CQw[upper[0]]; } else if (has_cq1 && !has_cq0) { cq = CQ.col(upper[1]); cqw = CQw[upper[1]]; } else if (has_cq1 && has_cq0) { Vector3d q_i = CQ.col(upper[0]); Vector3d n_i = CQ.col(upper[0]); Vector3d q_j = CQ.col(upper[1]); Vector3d n_j = CQ.col(upper[1]); auto result = compat_orientation_extrinsic_4(q_i, n_i, q_j, n_j); cq = result.first * CQw[upper[0]] + result.second * CQw[upper[1]]; cqw = (CQw[upper[0]] + CQw[upper[1]]); } if (cq != Vector3d::Zero()) { Vector3d n = N_next.col(i); cq -= n.dot(cq) * n; if (cq.squaredNorm() > RCPOVERFLOW) cq.normalize(); } if (has_co0 && !has_co1) { co = CO.col(upper[0]); cow = COw[upper[0]]; } else if (has_co1 && !has_co0) { co = CO.col(upper[1]); cow = COw[upper[1]]; } else if (has_co1 && has_co0) { double scale_x = mScale; double scale_y = mScale; if (with_scale) { // FIXME // scale_x *= S(0, i); // scale_y *= S(1, i); } double inv_scale_x = 1.0f / scale_x; double inv_scale_y = 1.0f / scale_y; double scale_x_1 = mScale; double scale_y_1 = mScale; if (with_scale) { // FIXME // scale_x_1 *= S(0, j); // scale_y_1 *= S(1, j); } double inv_scale_x_1 = 1.0f / scale_x_1; double inv_scale_y_1 = 1.0f / scale_y_1; auto result = compat_position_extrinsic_4( V.col(upper[0]), N.col(upper[0]), CQ.col(upper[0]), CO.col(upper[0]), V.col(upper[1]), N.col(upper[1]), CQ.col(upper[1]), CO.col(upper[1]), scale_x, scale_y, inv_scale_x, inv_scale_y, scale_x_1, scale_y_1, inv_scale_x_1, inv_scale_y_1); cow = COw[upper[0]] + COw[upper[1]]; co = (result.first * COw[upper[0]] + result.second * COw[upper[1]]) / cow; } if (co != Vector3d::Zero()) { Vector3d n = N_next.col(i), v = V_next.col(i); co -= n.dot(cq - v) * n; } #if 0 cqw *= 0.5f; cow *= 0.5f; #else if (cqw > 0) cqw = 1; if (cow > 0) cow = 1; #endif CQw_next[i] = cqw; COw_next[i] = cow; CQ_next.col(i) = cq; CO_next.col(i) = co; } } } #ifdef WITH_CUDA #include <cuda_runtime.h> void Hierarchy::CopyToDevice() { if (cudaAdj.empty()) { cudaAdj.resize(mAdj.size()); cudaAdjOffset.resize(mAdj.size()); for (int i = 0; i < mAdj.size(); ++i) { std::vector<int> offset(mAdj[i].size() + 1, 0); for (int j = 0; j < mAdj[i].size(); ++j) { offset[j + 1] = offset[j] + mAdj[i][j].size(); } cudaMalloc(&cudaAdjOffset[i], sizeof(int) * (mAdj[i].size() + 1)); cudaMemcpy(cudaAdjOffset[i], offset.data(), sizeof(int) * (mAdj[i].size() + 1), cudaMemcpyHostToDevice); // cudaAdjOffset[i] = (int*)malloc(sizeof(int) * (mAdj[i].size() + 1)); // memcpy(cudaAdjOffset[i], offset.data(), sizeof(int) * (mAdj[i].size() + // 1)); cudaMalloc(&cudaAdj[i], sizeof(Link) * offset.back()); // cudaAdj[i] = (Link*)malloc(sizeof(Link) * offset.back()); std::vector<Link> plainlink(offset.back()); for (int j = 0; j < mAdj[i].size(); ++j) { memcpy(plainlink.data() + offset[j], mAdj[i][j].data(), mAdj[i][j].size() * sizeof(Link)); } cudaMemcpy(cudaAdj[i], plainlink.data(), plainlink.size() * sizeof(Link), cudaMemcpyHostToDevice); } } if (cudaN.empty()) { cudaN.resize(mN.size()); for (int i = 0; i < mN.size(); ++i) { cudaMalloc(&cudaN[i], sizeof(glm::dvec3) * mN[i].cols()); // cudaN[i] = (glm::dvec3*)malloc(sizeof(glm::dvec3) * mN[i].cols()); } } for (int i = 0; i < mN.size(); ++i) { cudaMemcpy(cudaN[i], mN[i].data(), sizeof(glm::dvec3) * mN[i].cols(), cudaMemcpyHostToDevice); // memcpy(cudaN[i], mN[i].data(), sizeof(glm::dvec3) * mN[i].cols()); } if (cudaV.empty()) { cudaV.resize(mV.size()); for (int i = 0; i < mV.size(); ++i) { cudaMalloc(&cudaV[i], sizeof(glm::dvec3) * mV[i].cols()); // cudaV[i] = (glm::dvec3*)malloc(sizeof(glm::dvec3) * mV[i].cols()); } } for (int i = 0; i < mV.size(); ++i) { cudaMemcpy(cudaV[i], mV[i].data(), sizeof(glm::dvec3) * mV[i].cols(), cudaMemcpyHostToDevice); // memcpy(cudaV[i], mV[i].data(), sizeof(glm::dvec3) * mV[i].cols()); } if (cudaQ.empty()) { cudaQ.resize(mQ.size()); for (int i = 0; i < mQ.size(); ++i) { cudaMalloc(&cudaQ[i], sizeof(glm::dvec3) * mQ[i].cols()); // cudaQ[i] = (glm::dvec3*)malloc(sizeof(glm::dvec3) * mQ[i].cols()); } } for (int i = 0; i < mQ.size(); ++i) { cudaMemcpy(cudaQ[i], mQ[i].data(), sizeof(glm::dvec3) * mQ[i].cols(), cudaMemcpyHostToDevice); // memcpy(cudaQ[i], mQ[i].data(), sizeof(glm::dvec3) * mQ[i].cols()); } if (cudaO.empty()) { cudaO.resize(mO.size()); for (int i = 0; i < mO.size(); ++i) { cudaMalloc(&cudaO[i], sizeof(glm::dvec3) * mO[i].cols()); // cudaO[i] = (glm::dvec3*)malloc(sizeof(glm::dvec3) * mO[i].cols()); } } for (int i = 0; i < mO.size(); ++i) { cudaMemcpy(cudaO[i], mO[i].data(), sizeof(glm::dvec3) * mO[i].cols(), cudaMemcpyHostToDevice); // memcpy(cudaO[i], mO[i].data(), sizeof(glm::dvec3) * mO[i].cols()); } if (cudaPhases.empty()) { cudaPhases.resize(mPhases.size()); for (int i = 0; i < mPhases.size(); ++i) { cudaPhases[i].resize(mPhases[i].size()); for (int j = 0; j < mPhases[i].size(); ++j) { cudaMalloc(&cudaPhases[i][j], sizeof(int) * mPhases[i][j].size()); // cudaPhases[i][j] = (int*)malloc(sizeof(int) * // mPhases[i][j].size()); } } } for (int i = 0; i < mPhases.size(); ++i) { for (int j = 0; j < mPhases[i].size(); ++j) { cudaMemcpy(cudaPhases[i][j], mPhases[i][j].data(), sizeof(int) * mPhases[i][j].size(), cudaMemcpyHostToDevice); // memcpy(cudaPhases[i][j], mPhases[i][j].data(), sizeof(int) * // mPhases[i][j].size()); } } if (cudaToUpper.empty()) { cudaToUpper.resize(mToUpper.size()); for (int i = 0; i < mToUpper.size(); ++i) { cudaMalloc(&cudaToUpper[i], mToUpper[i].cols() * sizeof(glm::ivec2)); // cudaToUpper[i] = (glm::ivec2*)malloc(mToUpper[i].cols() * // sizeof(glm::ivec2)); } } for (int i = 0; i < mToUpper.size(); ++i) { cudaMemcpy(cudaToUpper[i], mToUpper[i].data(), sizeof(glm::ivec2) * mToUpper[i].cols(), cudaMemcpyHostToDevice); // memcpy(cudaToUpper[i], mToUpper[i].data(), sizeof(glm::ivec2) * // mToUpper[i].cols()); } cudaDeviceSynchronize(); } void Hierarchy::CopyToHost() {} #endif } // namespace qflow
36.202381
117
0.450263
[ "mesh", "vector", "transform" ]
fc1805ebfa6adc8d05a378b8ef5d8fc86ce4524e
2,497
cpp
C++
projects/tail/tests/traits.cpp
ecosnail/ecosnail
10b03f5924da41bca01031341a6cb10de624198e
[ "MIT" ]
null
null
null
projects/tail/tests/traits.cpp
ecosnail/ecosnail
10b03f5924da41bca01031341a6cb10de624198e
[ "MIT" ]
null
null
null
projects/tail/tests/traits.cpp
ecosnail/ecosnail
10b03f5924da41bca01031341a6cb10de624198e
[ "MIT" ]
null
null
null
#include <ecosnail/tail.hpp> #include <map> #include <vector> #include <type_traits> namespace tail = ecosnail::tail; #define DEMAND(CONDITION) \ static_assert(CONDITION, #CONDITION) #define FORBID(CONDITION) \ static_assert(!(CONDITION), "!(" #CONDITION ")") #define SAME_TYPE(U, V) \ static_assert(std::is_same<U, V>(), "types differ: " #U " <-> " #V) int main() {} void isIteratorTest() { using Struct = struct {}; // Simple types and references are not iterators FORBID(tail::IsIterator<int>()); FORBID(tail::IsIterator<const int>()); FORBID(tail::IsIterator<int&>()); FORBID(tail::IsIterator<const int&>()); FORBID(tail::IsIterator<Struct>()); FORBID(tail::IsIterator<const Struct>()); FORBID(tail::IsIterator<Struct&>()); FORBID(tail::IsIterator<const Struct&>()); // Pointers have iterator_traits, and are considered to be iterators DEMAND(tail::IsIterator<int*>()); DEMAND(tail::IsIterator<const int*>()); DEMAND(tail::IsIterator<Struct*>()); DEMAND(tail::IsIterator<const Struct*>()); // Standard container iterators are recognized using Vector = std::vector<int>; using Map = std::map<int, int>; DEMAND(tail::IsIterator<Map::iterator>()); DEMAND(tail::IsIterator<Map::const_iterator>()); DEMAND(tail::IsIterator<Vector::iterator>()); DEMAND(tail::IsIterator<Vector::const_iterator>()); } void isConstIteratorTest() { using Struct = struct {}; // If a type is not an iterator, it is not a const iterator FORBID(tail::IsConstIterator<int>()); FORBID(tail::IsConstIterator<const int>()); FORBID(tail::IsConstIterator<int&>()); FORBID(tail::IsConstIterator<const int&>()); FORBID(tail::IsConstIterator<Struct>()); FORBID(tail::IsConstIterator<const Struct>()); FORBID(tail::IsConstIterator<Struct&>()); FORBID(tail::IsConstIterator<const Struct&>()); // Constant pointers are considered const iterators FORBID(tail::IsConstIterator<int*>()); DEMAND(tail::IsConstIterator<const int*>()); FORBID(tail::IsConstIterator<Struct*>()); DEMAND(tail::IsConstIterator<const Struct*>()); // Iterators from standard containers using Vector = std::vector<int>; using Map = std::map<int, int>; FORBID(tail::IsConstIterator<Vector::iterator>()); DEMAND(tail::IsConstIterator<Vector::const_iterator>()); FORBID(tail::IsConstIterator<Map::iterator>()); DEMAND(tail::IsConstIterator<Map::const_iterator>()); }
29.034884
72
0.672006
[ "vector" ]
fc2622a7efb5f595b8f0fdf33094b4e4b285fe36
19,472
cpp
C++
bob/io/base/file.cpp
bioidiap/bob.io.base
37df660c8ee6ccd298e5a6ab495b38139a29da93
[ "BSD-3-Clause" ]
null
null
null
bob/io/base/file.cpp
bioidiap/bob.io.base
37df660c8ee6ccd298e5a6ab495b38139a29da93
[ "BSD-3-Clause" ]
12
2015-06-30T13:44:32.000Z
2016-06-08T11:56:33.000Z
bob/io/base/file.cpp
bioidiap/bob.io.base
37df660c8ee6ccd298e5a6ab495b38139a29da93
[ "BSD-3-Clause" ]
2
2015-07-16T13:35:57.000Z
2015-11-02T12:34:40.000Z
/** * @author Andre Anjos <andre.anjos@idiap.ch> * @date Tue 5 Nov 11:16:09 2013 * * @brief Bindings to bob::io::base::File */ #define BOB_IO_BASE_MODULE #include "bobskin.h" #include <bob.io.base/api.h> #include <numpy/arrayobject.h> #include <bob.blitz/capi.h> #include <bob.blitz/cleanup.h> #include <bob.extension/documentation.h> #include <stdexcept> #include <bob.io.base/CodecRegistry.h> #include <bob.io.base/utils.h> /* Creates an exception message including the name of the given file, if possible */ inline const std::string exception_message(PyBobIoFileObject* self, const std::string& name){ std::ostringstream str; str << name << " ("; try{ str << "'" << self->f->filename() << "'"; } catch (...){ str << "<unkown>"; } str << ")"; return str.str(); } static auto s_file = bob::extension::ClassDoc( "File", "Use this object to read and write data into files" ) .add_constructor( bob::extension::FunctionDoc( "File", "Opens a file for reading or writing", "Normally, we read the file matching the extension to one of the available codecs installed with the present release of Bob. " "If you set the ``pretend_extension`` parameter though, we will read the file as it had a given extension. " "The value should start with a ``'.'``. " "For example ``'.hdf5'``, to make the file be treated like an HDF5 file.", true ) .add_prototype("filename, [mode], [pretend_extension]", "") .add_parameter("filename", "str", "The file path to the file you want to open") .add_parameter("mode", "one of ('r', 'w', 'a')", "[Default: ``'r'``] A single character indicating if you'd like to ``'r'``\\ ead, ``'w'``\\ rite or ``'a'``\\ ppend into the file; if you choose ``'w'`` and the file already exists, it will be truncated") .add_parameter("pretend_extension", "str", "[optional] An extension to use; see :py:func:`bob.io.base.extensions` for a list of (currently) supported extensions") ); /* How to create a new PyBobIoFileObject */ static PyObject* PyBobIoFile_New(PyTypeObject* type, PyObject*, PyObject*) { /* Allocates the python object itself */ PyBobIoFileObject* self = (PyBobIoFileObject*)type->tp_alloc(type, 0); self->f.reset(); return reinterpret_cast<PyObject*>(self); } static void PyBobIoFile_Delete (PyBobIoFileObject* o) { o->f.reset(); Py_TYPE(o)->tp_free((PyObject*)o); } int PyBobIo_FilenameConverter (PyObject* o, const char** b) { #if PY_VERSION_HEX >= 0x03000000 if (PyUnicode_Check(o)) { *b = PyUnicode_AsUTF8(o); } else { PyObject* temp = PyObject_Bytes(o); if (!temp) return 0; auto temp_ = make_safe(temp); *b = PyBytes_AsString(temp); } #else if (PyUnicode_Check(o)) { PyObject* temp = PyUnicode_AsEncodedString(o, Py_FileSystemDefaultEncoding, "strict"); if (!temp) return 0; auto temp_ = make_safe(temp); *b = PyString_AsString(temp); } else { *b = PyString_AsString(o); } #endif return b != 0; } /* The __init__(self) method */ static int PyBobIoFile_init(PyBobIoFileObject* self, PyObject *args, PyObject* kwds) { BOB_TRY /* Parses input arguments in a single shot */ static char** kwlist = s_file.kwlist(); const char* filename; const char* pretend_extension = 0; #if PY_VERSION_HEX >= 0x03000000 # define MODE_CHAR "C" int mode = 'r'; #else # define MODE_CHAR "c" char mode = 'r'; #endif if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&|" MODE_CHAR "s", kwlist, &PyBobIo_FilenameConverter, &filename, &mode, &pretend_extension)) return -1; #undef MODE_CHAR if (mode != 'r' && mode != 'w' && mode != 'a') { PyErr_Format(PyExc_ValueError, "file open mode string should have 1 element and be either 'r' (read), 'w' (write) or 'a' (append)"); return -1; } if (pretend_extension) { self->f = bob::io::base::open(filename, mode, pretend_extension); } else { self->f = bob::io::base::open(filename, mode); } return 0; ///< SUCCESS BOB_CATCH_MEMBER("constructor", -1); } static PyObject* PyBobIoFile_repr(PyBobIoFileObject* self) { return PyString_FromFormat("%s(filename='%s', codec='%s')", Py_TYPE(self)->tp_name, self->f->filename(), self->f->name()); } static auto s_filename = bob::extension::VariableDoc( "filename", "str", "The path to the file being read/written" ); static PyObject* PyBobIoFile_Filename(PyBobIoFileObject* self) { return Py_BuildValue("s", self->f->filename()); } static auto s_codec_name = bob::extension::VariableDoc( "codec_name", "str", "Name of the File class implementation", "This variable is available for compatibility reasons with the previous versions of this library." ); static PyObject* PyBobIoFile_CodecName(PyBobIoFileObject* self) { return Py_BuildValue("s", self->f->name()); } static PyGetSetDef PyBobIoFile_getseters[] = { { s_filename.name(), (getter)PyBobIoFile_Filename, 0, s_filename.doc(), 0, }, { s_codec_name.name(), (getter)PyBobIoFile_CodecName, 0, s_codec_name.doc(), 0, }, {0} /* Sentinel */ }; static Py_ssize_t PyBobIoFile_len (PyBobIoFileObject* self) { Py_ssize_t retval = self->f->size(); return retval; } int PyBobIo_AsTypenum (bob::io::base::array::ElementType type) { switch(type) { case bob::io::base::array::t_bool: return NPY_BOOL; case bob::io::base::array::t_int8: return NPY_INT8; case bob::io::base::array::t_int16: return NPY_INT16; case bob::io::base::array::t_int32: return NPY_INT32; case bob::io::base::array::t_int64: return NPY_INT64; case bob::io::base::array::t_uint8: return NPY_UINT8; case bob::io::base::array::t_uint16: return NPY_UINT16; case bob::io::base::array::t_uint32: return NPY_UINT32; case bob::io::base::array::t_uint64: return NPY_UINT64; case bob::io::base::array::t_float32: return NPY_FLOAT32; case bob::io::base::array::t_float64: return NPY_FLOAT64; #ifdef NPY_FLOAT128 case bob::io::base::array::t_float128: return NPY_FLOAT128; #endif case bob::io::base::array::t_complex64: return NPY_COMPLEX64; case bob::io::base::array::t_complex128: return NPY_COMPLEX128; #ifdef NPY_COMPLEX256 case bob::io::base::array::t_complex256: return NPY_COMPLEX256; #endif default: PyErr_Format(PyExc_TypeError, "unsupported Bob/C++ element type (%s)", bob::io::base::array::stringize(type)); } return NPY_NOTYPE; } static PyObject* PyBobIoFile_getIndex (PyBobIoFileObject* self, Py_ssize_t i) { if (i < 0) i += self->f->size(); ///< adjust for negative indexing if (i < 0 || (size_t)i >= self->f->size()) { PyErr_Format(PyExc_IndexError, "file index out of range - `%s' only contains %" PY_FORMAT_SIZE_T "d object(s)", self->f->filename(), self->f->size()); return 0; } const bob::io::base::array::typeinfo& info = self->f->type(); npy_intp shape[NPY_MAXDIMS]; for (size_t k=0; k<info.nd; ++k) shape[k] = info.shape[k]; int type_num = PyBobIo_AsTypenum(info.dtype); if (type_num == NPY_NOTYPE) return 0; ///< failure PyObject* retval = PyArray_SimpleNew(info.nd, shape, type_num); if (!retval) return 0; auto retval_ = make_safe(retval); bobskin skin((PyArrayObject*)retval, info.dtype); self->f->read(skin, i); return Py_BuildValue("O", retval); } static PyObject* PyBobIoFile_getSlice (PyBobIoFileObject* self, PySliceObject* slice) { Py_ssize_t start, stop, step, slicelength; #if PY_VERSION_HEX < 0x03000000 if (PySlice_GetIndicesEx(slice, #else if (PySlice_GetIndicesEx(reinterpret_cast<PyObject*>(slice), #endif self->f->size(), &start, &stop, &step, &slicelength) < 0) return 0; //creates the return array const bob::io::base::array::typeinfo& info = self->f->type(); int type_num = PyBobIo_AsTypenum(info.dtype); if (type_num == NPY_NOTYPE) return 0; ///< failure if (slicelength <= 0) return PyArray_SimpleNew(0, 0, type_num); npy_intp shape[NPY_MAXDIMS]; shape[0] = slicelength; for (size_t k=0; k<info.nd; ++k) shape[k+1] = info.shape[k]; PyObject* retval = PyArray_SimpleNew(info.nd+1, shape, type_num); if (!retval) return 0; auto retval_ = make_safe(retval); Py_ssize_t counter = 0; for (auto i = start; (start<=stop)?i<stop:i>stop; i+=step) { //get slice to fill PyObject* islice = Py_BuildValue("n", counter++); if (!islice) return 0; auto islice_ = make_safe(islice); PyObject* item = PyObject_GetItem(retval, islice); if (!item) return 0; auto item_ = make_safe(item); bobskin skin((PyArrayObject*)item, info.dtype); self->f->read(skin, i); } return Py_BuildValue("O", retval); } static PyObject* PyBobIoFile_getItem (PyBobIoFileObject* self, PyObject* item) { if (PyIndex_Check(item)) { Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError); if (i == -1 && PyErr_Occurred()) return 0; return PyBobIoFile_getIndex(self, i); } if (PySlice_Check(item)) { return PyBobIoFile_getSlice(self, (PySliceObject*)item); } else { PyErr_Format(PyExc_TypeError, "File indices must be integers, not %s", Py_TYPE(item)->tp_name); return 0; } } static PyMappingMethods PyBobIoFile_Mapping = { (lenfunc)PyBobIoFile_len, //mp_length (binaryfunc)PyBobIoFile_getItem, //mp_subscript 0 /* (objobjargproc)PyBobIoFile_SetItem //mp_ass_subscript */ }; static auto s_read = bob::extension::FunctionDoc( "read", "Reads a specific object in the file, or the whole file", "This method reads data from the file. " "If you specified an ``index``, it reads just the object indicated by the index, as you would do using the ``[]`` operator. " "If the ``index`` is not specified, reads the whole contents of the file into a :py:class:`numpy.ndarray`.", true ) .add_prototype("[index]", "data") .add_parameter("index", "int", "[optional] The index to the object one wishes to retrieve from the file; negative indexing is supported; if not given, implies retrieval of the whole file contents.") .add_return("data", ":py:class:`numpy.ndarray`", "The contents of the file, as array") ; static PyObject* PyBobIoFile_read(PyBobIoFileObject* self, PyObject *args, PyObject* kwds) { BOB_TRY /* Parses input arguments in a single shot */ static char** kwlist = s_read.kwlist(); Py_ssize_t i = PY_SSIZE_T_MIN; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|n", kwlist, &i)) return 0; if (i != PY_SSIZE_T_MIN) { // reads a specific object inside the file if (i < 0) i += self->f->size(); if (i < 0 || (size_t)i >= self->f->size()) { PyErr_Format(PyExc_IndexError, "file index out of range - `%s' only contains %" PY_FORMAT_SIZE_T "d object(s)", self->f->filename(), self->f->size()); return 0; } return PyBobIoFile_getIndex(self, i); } // reads the whole file in a single shot const bob::io::base::array::typeinfo& info = self->f->type_all(); npy_intp shape[NPY_MAXDIMS]; for (size_t k=0; k<info.nd; ++k) shape[k] = info.shape[k]; int type_num = PyBobIo_AsTypenum(info.dtype); if (type_num == NPY_NOTYPE) return 0; ///< failure PyObject* retval = PyArray_SimpleNew(info.nd, shape, type_num); if (!retval) return 0; auto retval_ = make_safe(retval); bobskin skin((PyArrayObject*)retval, info.dtype); self->f->read_all(skin); return Py_BuildValue("O", retval); BOB_CATCH_MEMBER(exception_message(self, s_read.name()).c_str(), 0) } static auto s_write = bob::extension::FunctionDoc( "write", "Writes the contents of an object to the file", "This method writes data to the file. " "It acts like the given array is the only piece of data that will ever be written to such a file. " "No more data appending may happen after a call to this method.", true ) .add_prototype("data") .add_parameter("data", "array_like", "The array to be written into the file; it can be a :py:class:`numpy.ndarray`, a :py:class:`bob.blitz.array` or any other object which can be converted to either of them") ; static PyObject* PyBobIoFile_write(PyBobIoFileObject* self, PyObject *args, PyObject* kwds) { BOB_TRY /* Parses input arguments in a single shot */ static char** kwlist = s_write.kwlist(); PyBlitzArrayObject* bz = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kwlist, &PyBlitzArray_Converter, &bz)) return 0; auto bz_ = make_safe(bz); bobskin skin(bz); self->f->write(skin); Py_RETURN_NONE; BOB_CATCH_MEMBER(exception_message(self, s_write.name()).c_str(), 0) } static auto s_append = bob::extension::FunctionDoc( "append", "Adds the contents of an object to the file", "This method appends data to the file. " "If the file does not exist, creates a new file, else, makes sure that the inserted array respects the previously set file structure.", true ) .add_prototype("data", "position") .add_parameter("data", "array_like", "The array to be written into the file; it can be a :py:class:`numpy.ndarray`, a :py:class:`bob.blitz.array` or any other object which can be converted to either of them") .add_return("position", "int", "The current position of the newly written data") ; static PyObject* PyBobIoFile_append(PyBobIoFileObject* self, PyObject *args, PyObject* kwds) { BOB_TRY /* Parses input arguments in a single shot */ static char** kwlist = s_append.kwlist(); PyBlitzArrayObject* bz = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kwlist, &PyBlitzArray_Converter, &bz)) return 0; auto bz_ = make_safe(bz); Py_ssize_t pos = -1; bobskin skin(bz); pos = self->f->append(skin); return Py_BuildValue("n", pos); BOB_CATCH_MEMBER(exception_message(self, s_append.name()).c_str(), 0) } PyObject* PyBobIo_TypeInfoAsTuple (const bob::io::base::array::typeinfo& ti) { int type_num = PyBobIo_AsTypenum(ti.dtype); if (type_num == NPY_NOTYPE) return 0; PyObject* retval = Py_BuildValue("NNN", reinterpret_cast<PyObject*>(PyArray_DescrFromType(type_num)), PyTuple_New(ti.nd), //shape PyTuple_New(ti.nd) //strides ); if (!retval) return 0; PyObject* shape = PyTuple_GET_ITEM(retval, 1); PyObject* stride = PyTuple_GET_ITEM(retval, 2); for (Py_ssize_t i=0; (size_t)i<ti.nd; ++i) { PyTuple_SET_ITEM(shape, i, Py_BuildValue("n", ti.shape[i])); PyTuple_SET_ITEM(stride, i, Py_BuildValue("n", ti.stride[i])); } return retval; } static auto s_describe = bob::extension::FunctionDoc( "describe", "Returns a description (dtype, shape, stride) of data at the file", 0, true ) .add_prototype("[all]", "dtype, shape, stride") .add_parameter("all", "bool", "[Default: ``False``] If set to ``True``, returns the shape and strides for reading the whole file contents in one shot.") .add_return("dtype", ":py:class:`numpy.dtype`", "The data type of the object") .add_return("shape", "tuple", "The shape of the object") .add_return("stride", "tuple", "The stride of the object") ; static PyObject* PyBobIoFile_describe(PyBobIoFileObject* self, PyObject *args, PyObject* kwds) { BOB_TRY /* Parses input arguments in a single shot */ static const char* const_kwlist[] = {"all", 0}; static char** kwlist = const_cast<char**>(const_kwlist); PyObject* all = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, &all)) return 0; const bob::io::base::array::typeinfo* info = 0; if (all && PyObject_IsTrue(all)) info = &self->f->type_all(); else info = &self->f->type(); /* Now return type description and tuples with shape and strides */ return PyBobIo_TypeInfoAsTuple(*info); BOB_CATCH_MEMBER(exception_message(self, s_describe.name()).c_str(), 0) } static PyMethodDef PyBobIoFile_methods[] = { { s_read.name(), (PyCFunction)PyBobIoFile_read, METH_VARARGS|METH_KEYWORDS, s_read.doc(), }, { s_write.name(), (PyCFunction)PyBobIoFile_write, METH_VARARGS|METH_KEYWORDS, s_write.doc(), }, { s_append.name(), (PyCFunction)PyBobIoFile_append, METH_VARARGS|METH_KEYWORDS, s_append.doc(), }, { s_describe.name(), (PyCFunction)PyBobIoFile_describe, METH_VARARGS|METH_KEYWORDS, s_describe.doc(), }, {0} /* Sentinel */ }; /********************************** * Definition of Iterator to File * **********************************/ PyDoc_STRVAR(s_fileiterator_str, BOB_EXT_MODULE_PREFIX ".File.iter"); /* How to create a new PyBobIoFileIteratorObject */ static PyObject* PyBobIoFileIterator_New(PyTypeObject* type, PyObject*, PyObject*) { /* Allocates the python object itself */ PyBobIoFileIteratorObject* self = (PyBobIoFileIteratorObject*)type->tp_alloc(type, 0); return reinterpret_cast<PyObject*>(self); } static PyObject* PyBobIoFileIterator_iter (PyBobIoFileIteratorObject* self) { return reinterpret_cast<PyObject*>(self); } static PyObject* PyBobIoFileIterator_next (PyBobIoFileIteratorObject* self) { if ((size_t)self->curpos >= self->pyfile->f->size()) { Py_XDECREF((PyObject*)self->pyfile); self->pyfile = 0; return 0; } return PyBobIoFile_getIndex(self->pyfile, self->curpos++); } static PyObject* PyBobIoFile_iter (PyBobIoFileObject* self) { PyBobIoFileIteratorObject* retval = (PyBobIoFileIteratorObject*)PyBobIoFileIterator_New(&PyBobIoFileIterator_Type, 0, 0); if (!retval) return 0; retval->pyfile = self; retval->curpos = 0; return Py_BuildValue("N", retval); } #if PY_VERSION_HEX >= 0x03000000 # define Py_TPFLAGS_HAVE_ITER 0 #endif PyTypeObject PyBobIoFileIterator_Type = { PyVarObject_HEAD_INIT(0, 0) 0 }; PyTypeObject PyBobIoFile_Type = { PyVarObject_HEAD_INIT(0, 0) 0 }; bool init_File(PyObject* module){ // initialize the iterator PyBobIoFileIterator_Type.tp_name = s_fileiterator_str; PyBobIoFileIterator_Type.tp_basicsize = sizeof(PyBobIoFileIteratorObject); PyBobIoFileIterator_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER; PyBobIoFileIterator_Type.tp_iter = (getiterfunc)PyBobIoFileIterator_iter; PyBobIoFileIterator_Type.tp_iternext = (iternextfunc)PyBobIoFileIterator_next; // initialize the File PyBobIoFile_Type.tp_name = s_file.name(); PyBobIoFile_Type.tp_basicsize = sizeof(PyBobIoFileObject); PyBobIoFile_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; PyBobIoFile_Type.tp_doc = s_file.doc(); // set the functions PyBobIoFile_Type.tp_new = PyBobIoFile_New; PyBobIoFile_Type.tp_init = reinterpret_cast<initproc>(PyBobIoFile_init); PyBobIoFile_Type.tp_dealloc = reinterpret_cast<destructor>(PyBobIoFile_Delete); PyBobIoFile_Type.tp_methods = PyBobIoFile_methods; PyBobIoFile_Type.tp_getset = PyBobIoFile_getseters; PyBobIoFile_Type.tp_iter = (getiterfunc)PyBobIoFile_iter; PyBobIoFile_Type.tp_str = reinterpret_cast<reprfunc>(PyBobIoFile_repr); PyBobIoFile_Type.tp_repr = reinterpret_cast<reprfunc>(PyBobIoFile_repr); PyBobIoFile_Type.tp_as_mapping = &PyBobIoFile_Mapping; // check that everything is fine if (PyType_Ready(&PyBobIoFile_Type) < 0) return false; if (PyType_Ready(&PyBobIoFileIterator_Type) < 0) return false; // add the type to the module Py_INCREF(&PyBobIoFile_Type); bool success = PyModule_AddObject(module, s_file.name(), (PyObject*)&PyBobIoFile_Type) >= 0; if (!success) return false; Py_INCREF(&PyBobIoFileIterator_Type); success = PyModule_AddObject(module, s_fileiterator_str, (PyObject*)&PyBobIoFileIterator_Type) >= 0; return success; }
32.238411
255
0.691917
[ "object", "shape" ]
fc275072447d54c4c7d26de8d023e0123714cf9c
1,527
cc
C++
test/unit_test/ccb_test.cc
creativewebmatrixsolutions/CWMS-vowpal_wabbit
55480a5e2bfa41db8afcef7e4da31aea4dbc0d14
[ "BSD-3-Clause" ]
1
2015-03-20T01:53:03.000Z
2015-03-20T01:53:03.000Z
test/unit_test/ccb_test.cc
anirudhacharya/vowpal_wabbit
ba09cdb8ca49537a0eb99413c9b92217ef243930
[ "BSD-3-Clause" ]
null
null
null
test/unit_test/ccb_test.cc
anirudhacharya/vowpal_wabbit
ba09cdb8ca49537a0eb99413c9b92217ef243930
[ "BSD-3-Clause" ]
null
null
null
#define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include <boost/test/test_tools.hpp> #include "test_common.h" #include "vw.h" #include "example.h" #include <vector> #include "conditional_contextual_bandit.h" BOOST_AUTO_TEST_CASE(ccb_generate_interactions) { auto& vw = *VW::initialize("--ccb_explore_adf", nullptr, false, nullptr, nullptr); auto shared_ex = VW::read_example(vw, "ccb shared |User f"); multi_ex actions; actions.push_back(VW::read_example(vw, "ccb action |Action f")); actions.push_back(VW::read_example(vw, "ccb action |Other f |Action f")); std::vector<std::string> interactions; std::vector<std::string> compare_set = {{'U', (char)ccb_id_namespace}, {'A', (char)ccb_id_namespace}, {'O', (char)ccb_id_namespace}}; CCB::calculate_and_insert_interactions(shared_ex, actions, interactions); std::sort(compare_set.begin(), compare_set.end()); std::sort(interactions.begin(), interactions.end()); check_vectors(interactions, compare_set); interactions = {"UA", "UO", "UOA"}; compare_set = {"UA", "UO", "UOA", {'U', 'A', (char)ccb_id_namespace}, {'U', 'O', (char)ccb_id_namespace}, {'U', 'O', 'A', (char)ccb_id_namespace}, {'U', (char)ccb_id_namespace}, {'A', (char)ccb_id_namespace}, {'O', (char)ccb_id_namespace}}; CCB::calculate_and_insert_interactions(shared_ex, actions, interactions); std::sort(compare_set.begin(), compare_set.end()); std::sort(interactions.begin(), interactions.end()); check_vectors(interactions, compare_set); }
38.175
108
0.707924
[ "vector" ]
fc2b913654e173f2775e12c40e3533fa476102bb
1,441
cpp
C++
Codeforces/B_And_It_s_Non_Zero.cpp
rs-ravi2/Codes
8fc8bb64b429b3825e52394916c623ffcd0d5e21
[ "MIT" ]
null
null
null
Codeforces/B_And_It_s_Non_Zero.cpp
rs-ravi2/Codes
8fc8bb64b429b3825e52394916c623ffcd0d5e21
[ "MIT" ]
null
null
null
Codeforces/B_And_It_s_Non_Zero.cpp
rs-ravi2/Codes
8fc8bb64b429b3825e52394916c623ffcd0d5e21
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using vb = vector<bool>; using vvb = vector<vb>; using vi = vector<int>; using vvi = vector<vi>; using vl = vector<long>; using vll = vector<long long>; using vvl = vector<vl>; using vc = vector<char>; using vvc = vector<vc>; using vs = vector<string>; using pii = pair<int, int>; using pll = pair<long long, long long>; using mii = map<int, int>; using mll = map<long long, long long>; using umii = unordered_map<int, int>; using umll = unordered_map<long long, long long>; const ll mod = 1e9 + 7, inf = 1e18; #define loop(a, b, c) for (auto a = b; a < c; a++) #define pb push_back #define pp pop_back #define mp make_pair #define F first #define endl "\n" #define S second #define all(x) x.begin(), x.end() #define fast ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); int Dp[200001][20]; void solveTestCases(){ int l, r; cin >> l >> r; vll check(20, 0); int maxElement = 0; loop(i,0,20){ maxElement = max(maxElement, Dp[r][i] - Dp[l - 1][i]); } cout << (r - l + 1 - maxElement) << endl; } int main(){ fast; int t; cin >> t; loop(i,0,200001){ int check = i, idx = 0; while (check){ Dp[i][idx++] += (check % 2); check /= 2; } loop(j,0,20){ Dp[i][j] += Dp[i - 1][j]; } } while(t--){ solveTestCases(); } return 0; }
21.833333
62
0.565579
[ "vector" ]
fc31e762f3027718749219142055cbcbbfca3569
15,721
cpp
C++
qtmultimedia/src/imports/multimedia/qdeclarativeplaylist.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qtmultimedia/src/imports/multimedia/qdeclarativeplaylist.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qtmultimedia/src/imports/multimedia/qdeclarativeplaylist.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdeclarativeplaylist_p.h" QT_BEGIN_NAMESPACE /*! \qmltype PlaylistItem \instantiates QDeclarativePlaylistItem \since 5.6 \inqmlmodule QtMultimedia \ingroup multimedia_qml \ingroup multimedia_audio_qml \ingroup multimedia_video_qml \brief Defines an item in a Playlist. \sa Playlist */ /*! \qmlproperty url QtMultimedia::PlaylistItem::source This property holds the source URL of the item. \sa Playlist */ QDeclarativePlaylistItem::QDeclarativePlaylistItem(QObject *parent) : QObject(parent) { } QUrl QDeclarativePlaylistItem::source() const { return m_source; } void QDeclarativePlaylistItem::setSource(const QUrl &source) { m_source = source; } /*! \qmltype Playlist \instantiates QDeclarativePlaylist \since 5.6 \brief For specifying a list of media to be played. \inqmlmodule QtMultimedia \ingroup multimedia_qml \ingroup multimedia_audio_qml \ingroup multimedia_video_qml The Playlist type provides a way to play a list of media with the MediaPlayer, Audio and Video types. It can be used as a data source for view elements (such as ListView) and other elements that interact with model data (such as Repeater). When used as a data model, each playlist item's source URL can be accessed using the \c source role. \qml Item { width: 400; height: 300; Audio { id: player; playlist: Playlist { id: playlist PlaylistItem { source: "song1.ogg"; } PlaylistItem { source: "song2.ogg"; } PlaylistItem { source: "song3.ogg"; } } } ListView { model: playlist; delegate: Text { font.pixelSize: 16; text: source; } } MouseArea { anchors.fill: parent; onPressed: { if (player.playbackState != Audio.PlayingState) { player.play(); } else { player.pause(); } } } } \endqml \sa MediaPlayer, Audio, Video */ void QDeclarativePlaylist::_q_mediaAboutToBeInserted(int start, int end) { emit itemAboutToBeInserted(start, end); beginInsertRows(QModelIndex(), start, end); } void QDeclarativePlaylist::_q_mediaInserted(int start, int end) { endInsertRows(); emit itemCountChanged(); emit itemInserted(start, end); } void QDeclarativePlaylist::_q_mediaAboutToBeRemoved(int start, int end) { emit itemAboutToBeRemoved(start, end); beginRemoveRows(QModelIndex(), start, end); } void QDeclarativePlaylist::_q_mediaRemoved(int start, int end) { endRemoveRows(); emit itemCountChanged(); emit itemRemoved(start, end); } void QDeclarativePlaylist::_q_mediaChanged(int start, int end) { emit dataChanged(createIndex(start, 0), createIndex(end, 0)); emit itemChanged(start, end); } void QDeclarativePlaylist::_q_loadFailed() { m_error = m_playlist->error(); m_errorString = m_playlist->errorString(); emit error(Error(m_error), m_errorString); emit errorChanged(); emit loadFailed(); } QDeclarativePlaylist::QDeclarativePlaylist(QObject *parent) : QAbstractListModel(parent) , m_playlist(0) , m_error(QMediaPlaylist::NoError) , m_readOnly(false) { } QDeclarativePlaylist::~QDeclarativePlaylist() { delete m_playlist; } /*! \qmlproperty enumeration QtMultimedia::Playlist::playbackMode This property holds the order in which items in the playlist are played. \table \header \li Value \li Description \row \li CurrentItemOnce \li The current item is played only once. \row \li CurrentItemInLoop \li The current item is played repeatedly in a loop. \row \li Sequential \li Playback starts from the current and moves through each successive item until the last is reached and then stops. The next item is a null item when the last one is currently playing. \row \li Loop \li Playback restarts at the first item after the last has finished playing. \row \li Random \li Play items in random order. \endtable */ QDeclarativePlaylist::PlaybackMode QDeclarativePlaylist::playbackMode() const { return PlaybackMode(m_playlist->playbackMode()); } void QDeclarativePlaylist::setPlaybackMode(PlaybackMode mode) { if (playbackMode() == mode) return; m_playlist->setPlaybackMode(QMediaPlaylist::PlaybackMode(mode)); } /*! \qmlproperty url QtMultimedia::Playlist::currentItemsource This property holds the source URL of the current item in the playlist. */ QUrl QDeclarativePlaylist::currentItemSource() const { return m_playlist->currentMedia().canonicalUrl(); } /*! \qmlproperty int QtMultimedia::Playlist::currentIndex This property holds the position of the current item in the playlist. */ int QDeclarativePlaylist::currentIndex() const { return m_playlist->currentIndex(); } void QDeclarativePlaylist::setCurrentIndex(int index) { if (currentIndex() == index) return; m_playlist->setCurrentIndex(index); } /*! \qmlproperty int QtMultimedia::Playlist::itemCount This property holds the number of items in the playlist. */ int QDeclarativePlaylist::itemCount() const { return m_playlist->mediaCount(); } /*! \qmlproperty bool QtMultimedia::Playlist::readOnly This property indicates if the playlist can be modified. */ bool QDeclarativePlaylist::readOnly() const { // There's no signal to tell whether or not the read only state changed, so we consider it fixed // after its initial retrieval in componentComplete(). return m_readOnly; } /*! \qmlproperty enumeration QtMultimedia::Playlist::error This property holds the error condition of the playlist. \table \header \li Value \li Description \row \li NoError \li No errors \row \li FormatError \li Format error. \row \li FormatNotSupportedError \li Format not supported. \row \li NetworkError \li Network error. \row \li AccessDeniedError \li Access denied error. \endtable */ QDeclarativePlaylist::Error QDeclarativePlaylist::error() const { return Error(m_error); } /*! \qmlproperty string QtMultimedia::Playlist::errorString This property holds a string describing the current error condition of the playlist. */ QString QDeclarativePlaylist::errorString() const { return m_errorString; } /*! \qmlmethod url QtMultimedia::Playlist::itemSource(index) Returns the source URL of the item at the given \a index in the playlist. */ QUrl QDeclarativePlaylist::itemSource(int index) { return m_playlist->media(index).canonicalUrl(); } /*! \qmlmethod int QtMultimedia::Playlist::nextIndex(steps) Returns the index of the item in the playlist which would be current after calling next() \a steps times. Returned value depends on the size of the playlist, the current position and the playback mode. \sa playbackMode, previousIndex() */ int QDeclarativePlaylist::nextIndex(int steps) { return m_playlist->nextIndex(steps); } /*! \qmlmethod int QtMultimedia::Playlist::previousIndex(steps) Returns the index of the item in the playlist which would be current after calling previous() \a steps times. Returned value depends on the size of the playlist, the current position and the playback mode. \sa playbackMode, nextIndex() */ int QDeclarativePlaylist::previousIndex(int steps) { return m_playlist->previousIndex(steps); } /*! \qmlmethod QtMultimedia::Playlist::next() Advances to the next item in the playlist. */ void QDeclarativePlaylist::next() { m_playlist->next(); } /*! \qmlmethod QtMultimedia::Playlist::previous() Returns to the previous item in the playlist. */ void QDeclarativePlaylist::previous() { m_playlist->previous(); } /*! \qmlmethod QtMultimedia::Playlist::shuffle() Shuffles items in the playlist. */ void QDeclarativePlaylist::shuffle() { m_playlist->shuffle(); } /*! \qmlmethod QtMultimedia::Playlist::load(location, format) Loads a playlist from the given \a location. If \a format is specified, it is used, otherwise the format is guessed from the location name and the data. New items are appended to the playlist. \c onloaded() is emitted if the playlist loads successfully, otherwise \c onLoadFailed() is emitted with \l error and \l errorString defined accordingly. */ void QDeclarativePlaylist::load(const QUrl &location, const QString &format) { m_error = QMediaPlaylist::NoError; m_errorString = QString(); emit errorChanged(); m_playlist->load(location, format.toLatin1().constData()); } /*! \qmlmethod bool QtMultimedia::Playlist::save(location, format) Saves the playlist to the given \a location. If \a format is specified, it is used, otherwise the format is guessed from the location name. Returns true if the playlist is saved successfully. */ bool QDeclarativePlaylist::save(const QUrl &location, const QString &format) { return m_playlist->save(location, format.toLatin1().constData()); } /*! \qmlmethod bool QtMultimedia::Playlist::addItem(source) Appends the \a source URL to the playlist. Returns true if the \a source is added successfully. */ bool QDeclarativePlaylist::addItem(const QUrl &source) { return m_playlist->addMedia(QMediaContent(source)); } /*! \qmlmethod bool QtMultimedia::Playlist::insertItem(index, source) Inserts the \a source URL to the playlist at the given \a index. Returns true if the \a source is added successfully. */ bool QDeclarativePlaylist::insertItem(int index, const QUrl &source) { return m_playlist->insertMedia(index, QMediaContent(source)); } /*! \qmlmethod bool QtMultimedia::Playlist::removeItem(index) Removed the item at the given \a index from the playlist. Returns true if the \a source is removed successfully. */ bool QDeclarativePlaylist::removeItem(int index) { return m_playlist->removeMedia(index); } /*! \qmlmethod bool QtMultimedia::Playlist::clear() Removes all the items from the playlist. Returns true if the operation is successful. */ bool QDeclarativePlaylist::clear() { return m_playlist->clear(); } int QDeclarativePlaylist::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; return m_playlist->mediaCount(); } QVariant QDeclarativePlaylist::data(const QModelIndex &index, int role) const { Q_UNUSED(role); if (!index.isValid()) return QVariant(); return m_playlist->media(index.row()).canonicalUrl(); } QHash<int, QByteArray> QDeclarativePlaylist::roleNames() const { QHash<int, QByteArray> roleNames; roleNames[SourceRole] = "source"; return roleNames; } void QDeclarativePlaylist::classBegin() { m_playlist = new QMediaPlaylist(this); connect(m_playlist, SIGNAL(currentIndexChanged(int)), this, SIGNAL(currentIndexChanged())); connect(m_playlist, SIGNAL(playbackModeChanged(QMediaPlaylist::PlaybackMode)), this, SIGNAL(playbackModeChanged())); connect(m_playlist, SIGNAL(currentMediaChanged(QMediaContent)), this, SIGNAL(currentItemSourceChanged())); connect(m_playlist, SIGNAL(mediaAboutToBeInserted(int,int)), this, SLOT(_q_mediaAboutToBeInserted(int,int))); connect(m_playlist, SIGNAL(mediaInserted(int,int)), this, SLOT(_q_mediaInserted(int,int))); connect(m_playlist, SIGNAL(mediaAboutToBeRemoved(int,int)), this, SLOT(_q_mediaAboutToBeRemoved(int,int))); connect(m_playlist, SIGNAL(mediaRemoved(int,int)), this, SLOT(_q_mediaRemoved(int,int))); connect(m_playlist, SIGNAL(mediaChanged(int,int)), this, SLOT(_q_mediaChanged(int,int))); connect(m_playlist, SIGNAL(loaded()), this, SIGNAL(loaded())); connect(m_playlist, SIGNAL(loadFailed()), this, SLOT(_q_loadFailed())); if (m_playlist->isReadOnly()) { m_readOnly = true; emit readOnlyChanged(); } } void QDeclarativePlaylist::componentComplete() { } /*! \qmlsignal QtMultimedia::Playlist::itemAboutToBeInserted(start, end) This signal is emitted when items are to be inserted into the playlist at \a start and ending at \a end. The corresponding handler is \c onItemAboutToBeInserted. */ /*! \qmlsignal QtMultimedia::Playlist::itemInserted(start, end) This signal is emitted after items have been inserted into the playlist. The new items are those between \a start and \a end inclusive. The corresponding handler is \c onItemInserted. */ /*! \qmlsignal QtMultimedia::Playlist::itemAboutToBeRemoved(start, end) This signal emitted when items are to be deleted from the playlist at \a start and ending at \a end. The corresponding handler is \c onItemAboutToBeRemoved. */ /*! \qmlsignal QtMultimedia::Playlist::itemRemoved(start, end) This signal is emitted after items have been removed from the playlist. The removed items are those between \a start and \a end inclusive. The corresponding handler is \c onMediaRemoved. */ /*! \qmlsignal QtMultimedia::Playlist::itemChanged(start, end) This signal is emitted after items have been changed in the playlist between \a start and \a end positions inclusive. The corresponding handler is \c onItemChanged. */ /*! \qmlsignal QtMultimedia::Playlist::loaded() This signal is emitted when the playlist loading succeeded. The corresponding handler is \c onLoaded. */ /*! \qmlsignal QtMultimedia::Playlist::loadFailed() This signal is emitted when the playlist loading failed. \l error and \l errorString can be checked for more information on the failure. The corresponding handler is \c onLoadFailed. */ QT_END_NAMESPACE #include "moc_qdeclarativeplaylist_p.cpp"
27.05852
100
0.694803
[ "model" ]
fc3db1bf1082ef407f162be3de3a4460ea68a267
51,907
cpp
C++
multimedia/dshow/filters/image2/core/imagesyncren.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/dshow/filters/image2/core/imagesyncren.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/dshow/filters/image2/core/imagesyncren.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/******************************Module*Header*******************************\ * Module Name: ImageSyncRen.cpp * * Implements the IImageSync interface of the core Image Synchronization * Object - based on DShow base classes CBaseRenderer and CBaseVideoRenderer. * * * Created: Wed 01/12/2000 * Author: Stephen Estrop [StEstrop] * * Copyright (c) 2000 Microsoft Corporation \**************************************************************************/ #include <streams.h> #include <windowsx.h> #include <limits.h> #include "ImageSyncObj.h" #include "resource.h" #include "dxmperf.h" ///////////////////////////////////////////////////////////////////////////// // CImageSync // ///////////////////////////////////////////////////////////////////////////// // -------------------------------------------------------------------------- // Some helper inline functions // -------------------------------------------------------------------------- __inline bool IsDiscontinuity(DWORD dwSampleFlags) { return 0 != (dwSampleFlags & VMRSample_Discontinuity); } __inline bool IsTimeValid(DWORD dwSampleFlags) { return 0 != (dwSampleFlags & VMRSample_TimeValid); } __inline bool IsSyncPoint(DWORD dwSampleFlags) { return 0 != (dwSampleFlags & VMRSample_SyncPoint); } /*****************************Private*Routine******************************\ * TimeDiff * * Helper function for clamping time differences * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ __inline int TimeDiff(REFERENCE_TIME rt) { AMTRACE((TEXT("TimeDiff"))); if (rt < - (50 * UNITS)) { return -(50 * UNITS); } else if (rt > 50 * UNITS) { return 50 * UNITS; } else { return (int)rt; } } /*****************************Private*Routine******************************\ * DoRenderSample * * Here is where the actual presentation occurs. * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::DoRenderSample( VMRPRESENTATIONINFO* lpPresInfo ) { AMTRACE((TEXT("CImageSync::DoRenderSample"))); if (m_ImagePresenter) { return m_ImagePresenter->PresentImage(m_dwUserID, lpPresInfo); } return S_FALSE; } /*****************************Private*Routine******************************\ * RecordFrameLateness * * update the statistics: * m_iTotAcc, m_iSumSqAcc, m_iSumSqFrameTime, m_iSumFrameTime, m_cFramesDrawn * Note that because the properties page reports using these variables, * 1. We need to be inside a critical section * 2. They must all be updated together. Updating the sums here and the count * elsewhere can result in imaginary jitter (i.e. attempts to find square roots * of negative numbers) in the property page code. * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ void CImageSync::RecordFrameLateness( int trLate, int trFrame ) { AMTRACE((TEXT("CImageSync::RecordFrameLateness"))); // // Record how timely we are. // int tLate = trLate/10000; // // Best estimate of moment of appearing on the screen is average of // start and end draw times. Here we have only the end time. This may // tend to show us as spuriously late by up to 1/2 frame rate achieved. // Decoder probably monitors draw time. We don't bother. // // MSR_INTEGER( m_idFrameAccuracy, tLate ); // // This is a hack - we can get frames that are ridiculously late // especially (at start-up) and they sod up the statistics. // So ignore things that are more than 1 sec off. // if (tLate>1000 || tLate<-1000) { if (m_cFramesDrawn<=1) { tLate = 0; } else if (tLate>0) { tLate = 1000; } else { tLate = -1000; } } // // The very first frame often has a bogus time, so I'm just // not going to count it into the statistics. ??? // if (m_cFramesDrawn>1) { m_iTotAcc += tLate; m_iSumSqAcc += (tLate*tLate); } // // calculate inter-frame time. Doesn't make sense for first frame // second frame suffers from bogus first frame stamp. // if (m_cFramesDrawn>2) { int tFrame = trFrame/10000; // convert to mSec else it overflows // // This is a hack. It can overflow anyway (a pause can cause // a very long inter-frame time) and it overflows at 2**31/10**7 // or about 215 seconds i.e. 3min 35sec // if (tFrame>1000||tFrame<0) tFrame = 1000; m_iSumSqFrameTime += tFrame*tFrame; ASSERT(m_iSumSqFrameTime>=0); m_iSumFrameTime += tFrame; } ++m_cFramesDrawn; } /*****************************Private*Routine******************************\ * ThrottleWait * * * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ void CImageSync::ThrottleWait() { AMTRACE((TEXT("CImageSync::ThrottleWait"))); if (m_trThrottle > 0) { int iThrottle = m_trThrottle/10000; // convert to mSec // MSR_INTEGER( m_idThrottle, iThrottle); // DbgLog((LOG_TRACE, 0, TEXT("Throttle %d ms"), iThrottle)); Sleep(iThrottle); } else { Sleep(0); } } /*****************************Private*Routine******************************\ * OnRenderStart * * Called just before we start drawing. All we do is to get the current clock * time (from the system) and return. We have to store the start render time * in a member variable because it isn't used until we complete the drawing * The rest is just performance logging. * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ void CImageSync::OnRenderStart( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::OnRenderStart"))); if (PerflogTracingEnabled()) { REFERENCE_TIME rtClock = 0; if (NULL != m_pClock) { m_pClock->GetTime(&rtClock); rtClock -= m_tStart; } PERFLOG_VIDEOREND(pSample->rtStart, rtClock, lpSurf); } RecordFrameLateness(m_trLate, m_trFrame); m_tRenderStart = timeGetTime(); } /*****************************Private*Routine******************************\ * OnRenderEnd * * Called directly after drawing an image. We calculate the time spent in the * drawing code and if this doesn't appear to have any odd looking spikes in * it then we add it to the current average draw time. Measurement spikes may * occur if the drawing thread is interrupted and switched to somewhere else. * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ void CImageSync::OnRenderEnd( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::OnRenderEnd"))); // // The renderer time can vary erratically if we are interrupted so we do // some smoothing to help get more sensible figures out but even that is // not enough as figures can go 9,10,9,9,83,9 and we must disregard 83 // // convert mSec->UNITS int tr = (timeGetTime() - m_tRenderStart)*10000; if (tr < m_trRenderAvg*2 || tr < 2 * m_trRenderLast) { // DO_MOVING_AVG(m_trRenderAvg, tr); m_trRenderAvg = (tr + (AVGPERIOD-1)*m_trRenderAvg)/AVGPERIOD; } m_trRenderLast = tr; ThrottleWait(); } /*****************************Private*Routine******************************\ * Render * * This is called when a sample comes due for rendering. We pass the sample * on to the derived class. After rendering we will initialise the timer for * the next sample, NOTE signal that the last one fired first, if we don't * do this it thinks there is still one outstanding that hasn't completed * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::Render( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::Render"))); // // If the media sample is NULL then we will have been notified by the // clock that another sample is ready but in the mean time someone has // stopped us streaming which causes the next sample to be released // if (pSample == NULL) { return S_FALSE; } // // If we havn't been given anything to renderer with we are hosed too. // if (m_ImagePresenter == NULL) { return S_FALSE; } // // Time how long the rendering takes // OnRenderStart(pSample); HRESULT hr = DoRenderSample(pSample); OnRenderEnd(pSample); return hr; } /*****************************Private*Routine******************************\ * SendQuality * * Send a message to indicate what our supplier should do about quality. * Theory: * What a supplier wants to know is "is the frame I'm working on NOW * going to be late?". * F1 is the frame at the supplier (as above) * Tf1 is the due time for F1 * T1 is the time at that point (NOW!) * Tr1 is the time that f1 WILL actually be rendered * L1 is the latency of the graph for frame F1 = Tr1-T1 * D1 (for delay) is how late F1 will be beyond its due time i.e. * D1 = (Tr1-Tf1) which is what the supplier really wants to know. * Unfortunately Tr1 is in the future and is unknown, so is L1 * * We could estimate L1 by its value for a previous frame, * L0 = Tr0-T0 and work off * D1' = ((T1+L0)-Tf1) = (T1 + (Tr0-T0) -Tf1) * Rearranging terms: * D1' = (T1-T0) + (Tr0-Tf1) * adding (Tf0-Tf0) and rearranging again: * = (T1-T0) + (Tr0-Tf0) + (Tf0-Tf1) * = (T1-T0) - (Tf1-Tf0) + (Tr0-Tf0) * But (Tr0-Tf0) is just D0 - how late frame zero was, and this is the * Late field in the quality message that we send. * The other two terms just state what correction should be applied before * using the lateness of F0 to predict the lateness of F1. * (T1-T0) says how much time has actually passed (we have lost this much) * (Tf1-Tf0) says how much time should have passed if we were keeping pace * (we have gained this much). * * Suppliers should therefore work off: * Quality.Late + (T1-T0) - (Tf1-Tf0) * and see if this is "acceptably late" or even early (i.e. negative). * They get T1 and T0 by polling the clock, they get Tf1 and Tf0 from * the time stamps in the frames. They get Quality.Late from us. * * * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::SendQuality( REFERENCE_TIME trLate, REFERENCE_TIME trRealStream ) { AMTRACE((TEXT("CImageSync::SendQuality"))); Quality q; HRESULT hr; // // If we are the main user of time, then report this as Flood/Dry. // If our suppliers are, then report it as Famine/Glut. // // We need to take action, but avoid hunting. Hunting is caused by // 1. Taking too much action too soon and overshooting // 2. Taking too long to react (so averaging can CAUSE hunting). // // The reason why we use trLate as well as Wait is to reduce hunting; // if the wait time is coming down and about to go into the red, we do // NOT want to rely on some average which is only telling is that it used // to be OK once. // q.TimeStamp = (REFERENCE_TIME)trRealStream; if (m_trFrameAvg < 0) { q.Type = Famine; // guess } // // Is the greater part of the time taken bltting or something else // else if (m_trFrameAvg > 2*m_trRenderAvg) { q.Type = Famine; // mainly other } else { q.Type = Flood; // mainly bltting } q.Proportion = 1000; // default if (m_trFrameAvg < 0) { // // leave it alone - we don't know enough // } else if ( trLate> 0 ) { // // try to catch up over the next second // We could be Really, REALLY late, but rendering all the frames // anyway, just because it's so cheap. // q.Proportion = 1000 - (int)((trLate)/(UNITS/1000)); if (q.Proportion<500) { q.Proportion = 500; // don't go daft. (could've been negative!) } else { } } else if (m_trWaitAvg > 20000 && trLate < -20000 ) { // // Go cautiously faster - aim at 2mSec wait. // if (m_trWaitAvg>=m_trFrameAvg) { // // This can happen because of some fudges. // The waitAvg is how long we originally planned to wait // The frameAvg is more honest. // It means that we are spending a LOT of time waiting // q.Proportion = 2000; // double. } else { if (m_trFrameAvg+20000 > m_trWaitAvg) { q.Proportion = 1000 * (m_trFrameAvg / (m_trFrameAvg + 20000 - m_trWaitAvg)); } else { // // We're apparently spending more than the whole frame time waiting. // Assume that the averages are slightly out of kilter, but that we // are indeed doing a lot of waiting. (This leg probably never // happens, but the code avoids any potential divide by zero). // q.Proportion = 2000; } } if (q.Proportion>2000) { q.Proportion = 2000; // don't go crazy. } } // // Tell the supplier how late frames are when they get rendered // That's how late we are now. // If we are in directdraw mode then the guy upstream can see the drawing // times and we'll just report on the start time. He can figure out any // offset to apply. If we are in DIB Section mode then we will apply an // extra offset which is half of our drawing time. This is usually small // but can sometimes be the dominant effect. For this we will use the // average drawing time rather than the last frame. If the last frame took // a long time to draw and made us late, that's already in the lateness // figure. We should not add it in again unless we expect the next frame // to be the same. We don't, we expect the average to be a better shot. // In direct draw mode the RenderAvg will be zero. // q.Late = trLate + m_trRenderAvg / 2; // log what we're doing // MSR_INTEGER(m_idQualityRate, q.Proportion); // MSR_INTEGER( m_idQualityTime, (int)q.Late / 10000 ); // // We can't call the supplier directly - they have to call us when // Receive returns. So save this message and return S_FALSE or S_OK // depending upon whether the previous quality message was retrieved or // not. // BOOL bLastMessageRead = m_bLastQualityMessageRead; m_bLastQualityMessageRead = false; m_bQualityMsgValid = true; m_QualityMsg = q; return bLastMessageRead ? S_OK : S_FALSE; } /*****************************Private*Routine******************************\ * PreparePerformanceData * * Put data on one side that describes the lateness of the current frame. * We don't yet know whether it will actually be drawn. In direct draw mode, * this decision is up to the filter upstream, and it could change its mind. * The rules say that if it did draw it must call Receive(). One way or * another we eventually get into either OnRenderStart or OnDirectRender and * these both call RecordFrameLateness to update the statistics. * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ void CImageSync::PreparePerformanceData( int trLate, int trFrame ) { AMTRACE((TEXT("CImageSync::PreparePerformanceData"))); m_trLate = trLate; m_trFrame = trFrame; } /******************************Public*Routine******************************\ * ShouldDrawSampleNow * * We are called to decide whether the current sample is to be * be drawn or not. There must be a reference clock in operation. * * Return S_OK if it is to be drawn Now (as soon as possible) * * Return S_FALSE if it is to be drawn when it's due * * Return an error if we want to drop it * m_nNormal=-1 indicates that we dropped the previous frame and so this * one should be drawn early. Respect it and update it. * Use current stream time plus a number of heuristics (detailed below) * to make the decision * * History: * Tue 01/11/2000 - StEstrop - Modified from CBaseRenderer * \**************************************************************************/ HRESULT CImageSync::ShouldDrawSampleNow( VMRPRESENTATIONINFO* pSample, REFERENCE_TIME *ptrStart, REFERENCE_TIME *ptrEnd ) { AMTRACE((TEXT("CImageSync::ShouldDrawSampleNow"))); // // Don't call us unless there's a clock interface to synchronise with // ASSERT(m_pClock); // MSR_INTEGER(m_idTimeStamp, (int)((*ptrStart)>>32)); // high order 32 bits // MSR_INTEGER(m_idTimeStamp, (int)(*ptrStart)); // low order 32 bits // // We lose a bit of time depending on the monitor type waiting for the next // screen refresh. On average this might be about 8mSec - so it will be // later than we think when the picture appears. To compensate a bit // we bias the media samples by -8mSec i.e. 80000 UNITs. // We don't ever make a stream time negative (call it paranoia) // if (*ptrStart>=80000) { *ptrStart -= 80000; *ptrEnd -= 80000; // bias stop to to retain valid frame duration } // // Cache the time stamp now. We will want to compare what we did with what // we started with (after making the monitor allowance). // m_trRememberStampForPerf = *ptrStart; // // Get reference times (current and late) // the real time now expressed as stream time. // REFERENCE_TIME trRealStream; m_pClock->GetTime(&trRealStream); #ifdef PERF // // While the reference clock is expensive: // Remember the offset from timeGetTime and use that. // This overflows all over the place, but when we subtract to get // differences the overflows all cancel out. // m_llTimeOffset = trRealStream-timeGetTime()*10000; #endif trRealStream -= m_tStart; // convert to stream time (this is a reftime) // // We have to wory about two versions of "lateness". The truth, which we // try to work out here and the one measured against m_trTarget which // includes long term feedback. We report statistics against the truth // but for operational decisions we work to the target. // We use TimeDiff to make sure we get an integer because we // may actually be late (or more likely early if there is a big time // gap) by a very long time. // const int trTrueLate = TimeDiff(trRealStream - *ptrStart); const int trLate = trTrueLate; // MSR_INTEGER(m_idSchLateTime, trTrueLate/10000); // // Send quality control messages upstream, measured against target // HRESULT hr = SendQuality(trLate, trRealStream); // // Note: the filter upstream is allowed to this FAIL meaning "you do it". // m_bSupplierHandlingQuality = (hr==S_OK); // // Decision time! Do we drop, draw when ready or draw immediately? // const int trDuration = (int)(*ptrEnd - *ptrStart); { // // We need to see if the frame rate of the file has just changed. // This would make comparing our previous frame rate with the current // frame rate difficult. Hang on a moment though. I've seen files // where the frames vary between 33 and 34 mSec so as to average // 30fps. A minor variation like that won't hurt us. // int t = m_trDuration/32; if (trDuration > m_trDuration+t || trDuration < m_trDuration-t ) { // // There's a major variation. Reset the average frame rate to // exactly the current rate to disable decision 9002 for this frame, // and remember the new rate. // m_trFrameAvg = trDuration; m_trDuration = trDuration; } } // MSR_INTEGER(m_idEarliness, m_trEarliness/10000); // MSR_INTEGER(m_idRenderAvg, m_trRenderAvg/10000); // MSR_INTEGER(m_idFrameAvg, m_trFrameAvg/10000); // MSR_INTEGER(m_idWaitAvg, m_trWaitAvg/10000); // MSR_INTEGER(m_idDuration, trDuration/10000); #ifdef PERF if (S_OK==IsDiscontinuity(dwSampleFlags)) { MSR_INTEGER(m_idDecision, 9000); } #endif // // Control the graceful slide back from slow to fast machine mode. // After a frame drop accept an early frame and set the earliness to here // If this frame is already later than the earliness then slide it to here // otherwise do the standard slide (reduce by about 12% per frame). // Note: earliness is normally NEGATIVE // BOOL bJustDroppedFrame = ( m_bSupplierHandlingQuality // Can't use the pin sample properties because we might // not be in Receive when we call this && (S_OK == IsDiscontinuity(pSample->dwFlags))// he just dropped one ) || (m_nNormal==-1); // we just dropped one // // Set m_trEarliness (slide back from slow to fast machine mode) // if (trLate>0) { m_trEarliness = 0; // we are no longer in fast machine mode at all! } else if ( (trLate>=m_trEarliness) || bJustDroppedFrame) { m_trEarliness = trLate; // Things have slipped of their own accord } else { m_trEarliness = m_trEarliness - m_trEarliness/8; // graceful slide } // // prepare the new wait average - but don't pollute the old one until // we have finished with it. // int trWaitAvg; { // // We never mix in a negative wait. This causes us to believe // in fast machines slightly more. // int trL = trLate<0 ? -trLate : 0; trWaitAvg = (trL + m_trWaitAvg*(AVGPERIOD-1))/AVGPERIOD; } int trFrame; { REFERENCE_TIME tr = trRealStream - m_trLastDraw; // Cd be large - 4 min pause! if (tr>10000000) { tr = 10000000; // 1 second - arbitrarily. } trFrame = int(tr); } // // We will DRAW this frame IF... // if ( // ...the time we are spending drawing is a small fraction of the total // observed inter-frame time so that dropping it won't help much. (3*m_trRenderAvg <= m_trFrameAvg) // ...or our supplier is NOT handling things and the next frame would // be less timely than this one or our supplier CLAIMS to be handling // things, and is now less than a full FOUR frames late. || ( m_bSupplierHandlingQuality ? (trLate <= trDuration*4) : (trLate+trLate < trDuration) ) // ...or we are on average waiting for over eight milliseconds then // this may be just a glitch. Draw it and we'll hope to catch up. || (m_trWaitAvg > 80000) // ...or we haven't drawn an image for over a second. We will update // the display, which stops the video looking hung. // Do this regardless of how late this media sample is. || ((trRealStream - m_trLastDraw) > UNITS) ) { HRESULT Result; // // We are going to play this frame. We may want to play it early. // We will play it early if we think we are in slow machine mode. // If we think we are NOT in slow machine mode, we will still play // it early by m_trEarliness as this controls the graceful slide back. // and in addition we aim at being m_trTarget late rather than "on time". // BOOL bPlayASAP = FALSE; // // we will play it AT ONCE (slow machine mode) if... // // ...we are playing catch-up if ( bJustDroppedFrame) { bPlayASAP = TRUE; // MSR_INTEGER(m_idDecision, 9001); } // // ...or if we are running below the true frame rate // exact comparisons are glitchy, for these measurements, // so add an extra 5% or so // else if ( (m_trFrameAvg > trDuration + trDuration/16) // It's possible to get into a state where we are losing ground, but // are a very long way ahead. To avoid this or recover from it // we refuse to play early by more than 10 frames. && (trLate > - trDuration*10) ){ bPlayASAP = TRUE; // MSR_INTEGER(m_idDecision, 9002); } // // We will NOT play it at once if we are grossly early. On very slow frame // rate movies - e.g. clock.avi - it is not a good idea to leap ahead just // because we got starved (for instance by the net) and dropped one frame // some time or other. If we are more than 900mSec early, then wait. // if (trLate<-9000000) { bPlayASAP = FALSE; } if (bPlayASAP) { m_nNormal = 0; // MSR_INTEGER(m_idDecision, 0); // // When we are here, we are in slow-machine mode. trLate may well // oscillate between negative and positive when the supplier is // dropping frames to keep sync. We should not let that mislead // us into thinking that we have as much as zero spare time! // We just update with a zero wait. // m_trWaitAvg = (m_trWaitAvg*(AVGPERIOD-1))/AVGPERIOD; // // Assume that we draw it immediately. Update inter-frame stats // m_trFrameAvg = (trFrame + m_trFrameAvg*(AVGPERIOD-1))/AVGPERIOD; #ifndef PERF // // if this is NOT a perf build, then report what we know so far // without looking at the clock any more. This assumes that we // actually wait for exactly the time we hope to. it also reports // how close we get to the hacked up time stamps that we now have // rather than the ones we originally started with. It will // therefore be a little optimistic. However it's fast. // PreparePerformanceData(trTrueLate, trFrame); #endif m_trLastDraw = trRealStream; if (m_trEarliness > trLate) { m_trEarliness = trLate; // if we are actually early, this is neg } Result = S_OK; // Draw it now } else { ++m_nNormal; // // Set the average frame rate to EXACTLY the ideal rate. // If we are exiting slow-machine mode then we will have caught up // and be running ahead, so as we slide back to exact timing we will // have a longer than usual gap at this point. If we record this // real gap then we'll think that we're running slow and go back // into slow-machine mode and vever get it straight. // m_trFrameAvg = trDuration; // MSR_INTEGER(m_idDecision, 1); // // Play it early by m_trEarliness and by m_trTarget // { int trE = m_trEarliness; if (trE < -m_trFrameAvg) { trE = -m_trFrameAvg; } *ptrStart += trE; // N.B. earliness is negative } int Delay = -trTrueLate; Result = Delay<=0 ? S_OK : S_FALSE; // OK = draw now, FALSE = wait m_trWaitAvg = trWaitAvg; // // Predict when it will actually be drawn and update frame stats // if (Result==S_FALSE) { // We are going to wait trFrame = TimeDiff(*ptrStart-m_trLastDraw); m_trLastDraw = *ptrStart; } else { // trFrame is already = trRealStream-m_trLastDraw; m_trLastDraw = trRealStream; } #ifndef PERF int iAccuracy; if (Delay>0) { // Report lateness based on when we intend to play it iAccuracy = TimeDiff(*ptrStart-m_trRememberStampForPerf); } else { // Report lateness based on playing it *now*. iAccuracy = trTrueLate; // trRealStream-RememberStampForPerf; } PreparePerformanceData(iAccuracy, trFrame); #endif } return Result; } // // We are going to drop this frame! // Of course in DirectDraw mode the guy upstream may draw it anyway. // // // This will probably give a large negative wack to the wait avg. // m_trWaitAvg = trWaitAvg; #ifdef PERF // Respect registry setting - debug only! if (m_bDrawLateFrames) { return S_OK; // draw it when it's ready } // even though it's late. #endif // // We are going to drop this frame so draw the next one early // n.b. if the supplier is doing direct draw then he may draw it anyway // but he's doing something funny to arrive here in that case. // // MSR_INTEGER(m_idDecision, 2); m_nNormal = -1; return E_FAIL; // drop it } /*****************************Private*Routine******************************\ * CheckSampleTime * * Check the sample times for this samples (note the sample times are * passed in by reference not value). We return S_FALSE to say schedule this * sample according to the times on the sample. We also return S_OK in * which case the object should simply render the sample data immediately * * History: * Tue 01/11/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::CheckSampleTimes( VMRPRESENTATIONINFO* pSample, REFERENCE_TIME *pStartTime, REFERENCE_TIME *pEndTime ) { AMTRACE((TEXT("CImageSync::CheckSampleTimes"))); ASSERT(m_dwAdvise == 0); // // If the stop time for this sample is before or the same as start time, // then just ignore it // if (IsTimeValid(pSample->dwFlags)) { if (*pEndTime < *pStartTime) { return VFW_E_START_TIME_AFTER_END; } } else { // no time set in the sample... draw it now? return S_OK; } // Can't synchronise without a clock so we return S_OK which tells the // caller that the sample should be rendered immediately without going // through the overhead of setting a timer advise link with the clock if (m_pClock == NULL) { return S_OK; } return ShouldDrawSampleNow(pSample, pStartTime, pEndTime); } /*****************************Private*Routine******************************\ * ScheduleSample * * * * History: * Thu 01/13/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::ScheduleSample( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::ScheduleSample"))); HRESULT hr = ScheduleSampleWorker(pSample); if (FAILED(hr)) { #if defined( EHOME_WMI_INSTRUMENTATION ) PERFLOG_STREAMTRACE( 1, PERFINFO_STREAMTRACE_VMR_DROPPED_FRAME, 0, pSample->rtStart, pSample->rtEnd, 0, 0 ); #endif ++m_cFramesDropped; } // // m_cFramesDrawn must NOT be updated here. It has to be updated // in RecordFrameLateness at the same time as the other statistics. // return hr; } /*****************************Private*Routine******************************\ * ScheduleSampleWorker * * Responsible for setting up one shot advise links with the clock * * Returns a filure code (probably VFW_E_SAMPLE_REJECTED) if the sample was * dropped (not drawn at all). * * Returns S_OK if the sample is scheduled to be drawn and in this case also * arrange for m_RenderEvent to be set at the appropriate time * * History: * Tue 01/11/2000 - StEstrop - Modified from CBaseRenderer * \**************************************************************************/ HRESULT CImageSync::ScheduleSampleWorker( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::ScheduleSampleWorker"))); // // If the samples times arn't valid or if there is no // reference clock // REFERENCE_TIME startTime = pSample->rtStart; REFERENCE_TIME endTime = pSample->rtEnd; HRESULT hr = CheckSampleTimes(pSample, &startTime, &endTime); if (FAILED(hr)) { if (hr != VFW_E_START_TIME_AFTER_END) { hr = VFW_E_SAMPLE_REJECTED; } return hr; } // // If we don't have a reference clock then we cannot set up the advise // time so we simply set the event indicating an image to render. This // will cause us to run flat out without any timing or synchronisation // if (hr == S_OK) { EXECUTE_ASSERT(SetEvent((HANDLE)m_RenderEvent)); return S_OK; } ASSERT(m_dwAdvise == 0); ASSERT(m_pClock); ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent, 0)); // // We do have a valid reference clock interface so we can ask it to // set an event when the image comes due for rendering. We pass in // the reference time we were told to start at and also the current // stream time which is the offset from the start reference time // #if defined( EHOME_WMI_INSTRUMENTATION ) PERFLOG_STREAMTRACE( 1, PERFINFO_STREAMTRACE_VMR_BEGIN_ADVISE, startTime, m_tStart, 0, 0, 0 ); #endif hr = m_pClock->AdviseTime( (REFERENCE_TIME)m_tStart, // Start run time startTime, // Stream time (HEVENT)(HANDLE)m_RenderEvent, // Render notification &m_dwAdvise); // Advise cookie if (SUCCEEDED(hr)) { return S_OK; } // // We could not schedule the next sample for rendering despite the fact // we have a valid sample here. This is a fair indication that either // the system clock is wrong or the time stamp for the sample is duff // ASSERT(m_dwAdvise == 0); return VFW_E_SAMPLE_REJECTED; } /*****************************Private*Routine******************************\ * OnWaitStart() * * Called when we start waiting for a rendering event. * Used to update times spent waiting and not waiting. * * * History: * Tue 01/11/2000 - StEstrop - Modified from CBaseRenderer * \**************************************************************************/ void CImageSync::OnWaitStart() { AMTRACE((TEXT("CImageSync::OnWaitStart"))); #ifdef PERF MSR_START(m_idWaitReal); #endif //PERF } /*****************************Private*Routine******************************\ * OnWaitEnd * * * History: * Tue 01/11/2000 - StEstrop - Modified from CBaseRenderer * \**************************************************************************/ void CImageSync::OnWaitEnd() { AMTRACE((TEXT("CImageSync::OnWaitEnd"))); #ifdef PERF MSR_STOP(m_idWaitReal); // // for a perf build we want to know just exactly how late we REALLY are. // even if this means that we have to look at the clock again. // REFERENCE_TIME trRealStream; // the real time now expressed as stream time. // // We will be discarding overflows like mad here! // This is wrong really because timeGetTime() can wrap but it's // only for PERF // REFERENCE_TIME tr = timeGetTime()*10000; trRealStream = tr + m_llTimeOffset; trRealStream -= m_tStart; // convert to stream time (this is a reftime) if (m_trRememberStampForPerf==0) { // // This is probably the poster frame at the start, and it is not scheduled // in the usual way at all. Just count it. The rememberstamp gets set // in ShouldDrawSampleNow, so this does bogus frame recording until we // actually start playing. // PreparePerformanceData(0, 0); } else { int trLate = (int)(trRealStream - m_trRememberStampForPerf); int trFrame = (int)(tr - m_trRememberFrameForPerf); PreparePerformanceData(trLate, trFrame); } m_trRememberFrameForPerf = tr; #endif //PERF } /*****************************Private*Routine******************************\ * WaitForRenderTime * * Wait until the clock sets the timer event or we're otherwise signalled. We * set an arbitrary timeout for this wait and if it fires then we display the * current renderer state on the debugger. It will often fire if the filter's * left paused in an application however it may also fire during stress tests * if the synchronisation with application seeks and state changes is faulty * * History: * Tue 01/11/2000 - StEstrop - Modified from CBaseRenderer * \**************************************************************************/ HRESULT CImageSync::WaitForRenderTime() { AMTRACE((TEXT("CImageSync::WaitForRenderTime"))); HANDLE WaitObjects[] = { m_ThreadSignal, m_RenderEvent }; DWORD Result = WAIT_TIMEOUT; // // Wait for either the time to arrive or for us to be stopped // OnWaitStart(); while (Result == WAIT_TIMEOUT) { Result = WaitForMultipleObjects(2, WaitObjects, FALSE, RENDER_TIMEOUT); //#ifdef DEBUG // if (Result == WAIT_TIMEOUT) DisplayRendererState(); //#endif } OnWaitEnd(); // // We may have been awoken without the timer firing // if (Result == WAIT_OBJECT_0) { return VFW_E_STATE_CHANGED; } SignalTimerFired(); return S_OK; } /*****************************Private*Routine******************************\ * SignalTimerFired * * We must always reset the current advise time to zero after a timer fires * because there are several possible ways which lead us not to do any more * scheduling such as the pending image being cleared after state changes * * History: * Tue 01/11/2000 - StEstrop - Modified from CBaseRenderer * \**************************************************************************/ void CImageSync::SignalTimerFired() { AMTRACE((TEXT("CImageSync::SignalTimerFired"))); m_dwAdvise = 0; #if defined( EHOME_WMI_INSTRUMENTATION ) PERFLOG_STREAMTRACE( 1, PERFINFO_STREAMTRACE_VMR_END_ADVISE, 0, 0, 0, 0, 0 ); #endif } /*****************************Private*Routine******************************\ * SaveSample * * * * History: * Thu 01/13/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::SaveSample( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::SaveSample"))); CAutoLock cRendererLock(&m_RendererLock); if (m_pSample) { return E_FAIL; } m_pSample = pSample; return S_OK; } /*****************************Private*Routine******************************\ * GetSavedSample * * * * History: * Thu 01/13/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::GetSavedSample( VMRPRESENTATIONINFO** ppSample ) { AMTRACE((TEXT("CImageSync::GetSavedSample"))); CAutoLock cRendererLock(&m_RendererLock); if (!m_pSample) { DbgLog((LOG_TRACE, 1, TEXT("CImageSync::GetSavedSample Sample not available") )); return E_FAIL; } *ppSample = m_pSample; return S_OK; } /*****************************Private*Routine******************************\ * HaveSavedSample * * Checks if there is a sample waiting at the renderer * * History: * Thu 01/13/2000 - StEstrop - Created * \**************************************************************************/ BOOL CImageSync::HaveSavedSample() { AMTRACE((TEXT("CImageSync::HaveSavedSample"))); CAutoLock cRendererLock(&m_RendererLock); DbgLog((LOG_TRACE, 1, TEXT("CImageSync::HaveSavedSample = %d"), m_pSample != NULL)); return m_pSample != NULL; } /*****************************Private*Routine******************************\ * ClearSavedSample * * * * History: * Thu 01/13/2000 - StEstrop - Created * \**************************************************************************/ void CImageSync::ClearSavedSample() { AMTRACE((TEXT("CImageSync::ClearSavedSample"))); CAutoLock cRendererLock(&m_RendererLock); m_pSample = NULL; } /*****************************Private*Routine******************************\ * CancelNotification * * Cancel any notification currently scheduled. This is called by the owning * window object when it is told to stop streaming. If there is no timer link * outstanding then calling this is benign otherwise we go ahead and cancel * We must always reset the render event as the quality management code can * signal immediate rendering by setting the event without setting an advise * link. If we're subsequently stopped and run the first attempt to setup an * advise link with the reference clock will find the event still signalled * * History: * Tue 01/11/2000 - StEstrop - Modified from CBaseRenderer * \**************************************************************************/ HRESULT CImageSync::CancelNotification() { AMTRACE((TEXT("CImageSync::CancelNotification"))); ASSERT(m_dwAdvise == 0 || m_pClock); DWORD_PTR dwAdvise = m_dwAdvise; // // Have we a live advise link // if (m_dwAdvise) { m_pClock->Unadvise(m_dwAdvise); SignalTimerFired(); ASSERT(m_dwAdvise == 0); } // // Clear the event and return our status // m_RenderEvent.Reset(); return (dwAdvise ? S_OK : S_FALSE); } /*****************************Private*Routine******************************\ * OnReceiveFirstSample * * * * History: * Wed 01/12/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::OnReceiveFirstSample( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::OnReceiveFirstSample"))); return DoRenderSample(pSample); } /*****************************Private*Routine******************************\ * PrepareReceive * * Called when the source delivers us a sample. We go through a few checks to * make sure the sample can be rendered. If we are running (streaming) then we * have the sample scheduled with the reference clock, if we are not streaming * then we have received an sample in paused mode so we can complete any state * transition. On leaving this function everything will be unlocked so an app * thread may get in and change our state to stopped (for example) in which * case it will also signal the thread event so that our wait call is stopped * * History: * Thu 01/13/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::PrepareReceive( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::PrepareReceive"))); CAutoLock cILock(&m_InterfaceLock); m_bInReceive = TRUE; // Check our flushing state if (m_bFlushing) { m_bInReceive = FALSE; return E_FAIL; } CAutoLock cRLock(&m_RendererLock); // // Return an error if we already have a sample waiting for rendering // source pins must serialise the Receive calls - we also check that // no data is being sent after the source signalled an end of stream // if (HaveSavedSample() || m_bEOS || m_bAbort) { Ready(); m_bInReceive = FALSE; return E_UNEXPECTED; } // // Schedule the next sample if we are streaming // if (IsStreaming()) { if (FAILED(ScheduleSample(pSample))) { ASSERT(WAIT_TIMEOUT == WaitForSingleObject((HANDLE)m_RenderEvent,0)); ASSERT(CancelNotification() == S_FALSE); m_bInReceive = FALSE; return VFW_E_SAMPLE_REJECTED; } EXECUTE_ASSERT(S_OK == SaveSample(pSample)); } // // else we are not streaming yet, just save the sample and wait in Receive // until BeginImageSequence is called. BeginImageSequence passes a base // start time with which we schedule the saved sample. // else { // ASSERT(IsFirstSample(dwSampleFlags)); EXECUTE_ASSERT(S_OK == SaveSample(pSample)); } // Store the sample end time for EC_COMPLETE handling m_SignalTime = pSample->rtEnd; return S_OK; } /*****************************Private*Routine******************************\ * FrameStepWorker * * * * History: * Tue 08/29/2000 - StEstrop - Created * \**************************************************************************/ void CImageSync::FrameStepWorker() { AMTRACE((TEXT("CImageSync::FrameStepWorker"))); CAutoLock cLock(&m_InterfaceLock); if (m_lFramesToStep == 1) { m_lFramesToStep--; m_InterfaceLock.Unlock(); m_lpEventNotify->NotifyEvent(EC_STEP_COMPLETE, FALSE, 0); DWORD dw = WaitForSingleObject(m_StepEvent, INFINITE); m_InterfaceLock.Lock(); ASSERT(m_lFramesToStep != 0); } } /******************************Public*Routine******************************\ * Receive * * Return the buffer to the renderer along with time stamps relating to * when the buffer should be presented. * * History: * Tue 01/11/2000 - StEstrop - Created * \**************************************************************************/ STDMETHODIMP CImageSync::Receive( VMRPRESENTATIONINFO* lpPresInfo ) { AMTRACE((TEXT("CImageSync::Receive"))); // // Frame step hack-o-matic // // This code acts as a gate - for a frame step of N frames // it discards N-1 frames and then lets the Nth frame thru the // the gate to be rendered in the normal way i.e. at the correct // time. The next time Receive is called the gate is shut and // the thread blocks. The gate only opens again when the step // is cancelled or another frame step request comes in. // // StEstrop - Thu 10/21/1999 // { CAutoLock cLock(&m_InterfaceLock); // // do we have frames to discard ? // if (m_lFramesToStep > 1) { m_lFramesToStep--; if (m_lFramesToStep > 0) { return NOERROR; } } } return ReceiveWorker(lpPresInfo); } /******************************Public*Routine******************************\ * ReceiveWorker * * Return the buffer to the renderer along with time stamps relating to * when the buffer should be presented. * * History: * Tue 01/11/2000 - StEstrop - Created * \**************************************************************************/ HRESULT CImageSync::ReceiveWorker( VMRPRESENTATIONINFO* pSample ) { AMTRACE((TEXT("CImageSync::ReceiveWorker"))); ASSERT(pSample); // // Prepare for this Receive call, this may return the VFW_E_SAMPLE_REJECTED // error code to say don't bother - depending on the quality management. // HRESULT hr = PrepareReceive(pSample); ASSERT(m_bInReceive == SUCCEEDED(hr)); if (FAILED(hr)) { if (hr == VFW_E_SAMPLE_REJECTED) { return S_OK; } return hr; } // // We special case "first samples" // BOOL bSampleRendered = FALSE; if (m_State == ImageSync_State_Cued) { // // no need to use InterlockedExchange // m_bInReceive = FALSE; { // // We must hold both these locks // CAutoLock cILock(&m_InterfaceLock); if (m_State == ImageSync_State_Stopped) return S_OK; m_bInReceive = TRUE; CAutoLock cRLock(&m_RendererLock); hr = OnReceiveFirstSample(pSample); bSampleRendered = TRUE; } Ready(); } // // Having set an advise link with the clock we sit and wait. We may be // awoken by the clock firing or by the CancelRender event. // if (FAILED(WaitForRenderTime())) { m_bInReceive = FALSE; return hr; } DbgLog((LOG_TIMING, 3, TEXT("CImageSync::ReceiveWorker WaitForRenderTime completed for this video sample") )); m_bInReceive = FALSE; // // Deal with this sample - We must hold both these locks // { CAutoLock cILock(&m_InterfaceLock); if (m_State == ImageSync_State_Stopped) return S_OK; CAutoLock cRLock(&m_RendererLock); if (!bSampleRendered) { hr = Render(m_pSample); } } FrameStepWorker(); { CAutoLock cILock(&m_InterfaceLock); CAutoLock cRLock(&m_RendererLock); // // Clean up // ClearSavedSample(); SendEndOfStream(); CancelNotification(); } return hr; } /******************************Public*Routine******************************\ * GetQualityControlMessage * * ask for quality control information from the renderer * * History: * Tue 01/11/2000 - StEstrop - Created * \**************************************************************************/ STDMETHODIMP CImageSync::GetQualityControlMessage( Quality* pQualityMsg ) { AMTRACE((TEXT("CImageSync::GetQualityControlMessage"))); CAutoLock cILock(&m_InterfaceLock); CAutoLock cRLock(&m_RendererLock); if (!pQualityMsg) { return E_POINTER; } if (m_bQualityMsgValid) { *pQualityMsg = m_QualityMsg; m_bLastQualityMessageRead = TRUE; return S_OK; } else return S_FALSE; }
30.426143
95
0.558923
[ "render", "object" ]
fc49e8f6a06c77bc2bb1455f5c3ffb63ca910e2e
740
cpp
C++
Series.cpp
chrismarquez/movieDb
d2ae85a2450b9fd422fdcd74985fb8d91227da0c
[ "MIT" ]
null
null
null
Series.cpp
chrismarquez/movieDb
d2ae85a2450b9fd422fdcd74985fb8d91227da0c
[ "MIT" ]
null
null
null
Series.cpp
chrismarquez/movieDb
d2ae85a2450b9fd422fdcd74985fb8d91227da0c
[ "MIT" ]
1
2020-06-12T19:43:37.000Z
2020-06-12T19:43:37.000Z
// // Created by christopher on 12/06/20. // #include "Series.h" #include <utility> Series::Series(string id, string name, int duration, string genre) : AbstractVideo(std::move(id), std::move(name), duration, std::move(genre)) { } double Series::getScore() const { auto score = 0.0; auto episodeCount = 0; for (auto&& season : episodes) { for (auto&& episode : season) { score += episode.getScore(); episodeCount++; } } return score / episodeCount; } void Series::addSeason(const vector<IVideo>& season) { episodes.push_back(season); } void Series::addEpisode(IVideo &episode) { auto lastSeason = episodes[episodes.size() - 1]; lastSeason.push_back(episode); }
21.764706
77
0.633784
[ "vector" ]
fc4a07126070dd5fca2e9c91c4c5f31099dc1af6
20,730
cpp
C++
src/world/CShapeBox.cpp
lfloegel/Rigged-Bow
8a2e86304888d55b8d1537d2cc79089115ef5f94
[ "BSD-3-Clause" ]
null
null
null
src/world/CShapeBox.cpp
lfloegel/Rigged-Bow
8a2e86304888d55b8d1537d2cc79089115ef5f94
[ "BSD-3-Clause" ]
null
null
null
src/world/CShapeBox.cpp
lfloegel/Rigged-Bow
8a2e86304888d55b8d1537d2cc79089115ef5f94
[ "BSD-3-Clause" ]
null
null
null
//============================================================================== /* Software License Agreement (BSD License) Copyright (c) 2003-2016, CHAI3D. (www.chai3d.org) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of CHAI3D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. . \author <http://www.chai3d.org> \author Francois Conti \version $MAJOR.$MINOR.$RELEASE $Rev: 2174 $ */ //============================================================================== //------------------------------------------------------------------------------ #include "world/CShapeBox.h" //------------------------------------------------------------------------------ #include "shaders/CShaderProgram.h" //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace chai3d { //------------------------------------------------------------------------------ //============================================================================== /*! Constructor of cShapeBox. \param a_sizeX Size of box along axis X. \param a_sizeY Size of box along axis Y. \param a_sizeZ Size of box along axis Z. \param a_material Material property to be applied to object. */ //============================================================================== cShapeBox::cShapeBox(const double& a_sizeX, const double& a_sizeY, const double& a_sizeZ, cMaterialPtr a_material) { // enable display list m_useDisplayList = true; // initialize dimension setSize(a_sizeX, a_sizeY, a_sizeZ); // set material properties if (a_material == nullptr) { m_material = cMaterial::create(); m_material->setShininess(100); m_material->m_ambient.set ((float)0.3, (float)0.3, (float)0.3); m_material->m_diffuse.set ((float)0.1, (float)0.7, (float)0.8); m_material->m_specular.set((float)1.0, (float)1.0, (float)1.0); } else { m_material = a_material; } }; //============================================================================== /*! This method creates a copy of itself. \param a_duplicateMaterialData If __true__, material (if available) is duplicated, otherwise it is shared. \param a_duplicateTextureData If __true__, texture data (if available) is duplicated, otherwise it is shared. \param a_duplicateMeshData If __true__, mesh data (if available) is duplicated, otherwise it is shared. \param a_buildCollisionDetector If __true__, collision detector (if available) is duplicated, otherwise it is shared. \return Pointer to new object. */ //============================================================================== cShapeBox* cShapeBox::copy(const bool a_duplicateMaterialData, const bool a_duplicateTextureData, const bool a_duplicateMeshData, const bool a_buildCollisionDetector) { // create new instance cShapeBox* obj = new cShapeBox(2.0 * m_hSizeX, 2.0 * m_hSizeY, 2.0 * m_hSizeZ); // copy generic properties copyShapeBoxProperties(obj, a_duplicateMaterialData, a_duplicateTextureData, a_duplicateMeshData, a_buildCollisionDetector); // return return (obj); } //============================================================================== /*! This method copies all properties of this multi-mesh to another. \param a_obj Destination object where properties are copied to. \param a_duplicateMaterialData If __true__, material (if available) is duplicated, otherwise it is shared. \param a_duplicateTextureData If __true__, texture data (if available) is duplicated, otherwise it is shared. \param a_duplicateMeshData If __true__, mesh data (if available) is duplicated, otherwise it is shared. \param a_buildCollisionDetector If __true__, collision detector (if available) is duplicated, otherwise it is shared. */ //============================================================================== void cShapeBox::copyShapeBoxProperties(cShapeBox* a_obj, const bool a_duplicateMaterialData, const bool a_duplicateTextureData, const bool a_duplicateMeshData, const bool a_buildCollisionDetector) { // copy properties of cGenericObject copyGenericObjectProperties(a_obj, a_duplicateMaterialData, a_duplicateTextureData, a_duplicateMeshData, a_buildCollisionDetector); // copy properties of cShapeBox a_obj->m_hSizeX = m_hSizeX; a_obj->m_hSizeY = m_hSizeY; a_obj->m_hSizeZ = m_hSizeZ; } //============================================================================== /*! This method sets the dimensions of the box along each axis. \param a_sizeX Size of box along axis X. \param a_sizeY Size of box along axis Y. \param a_sizeZ Size of box along axis Z. */ //============================================================================== void cShapeBox::setSize(const double& a_sizeX, const double& a_sizeY, const double& a_sizeZ) { // set dimensions m_hSizeX = 0.5 * fabs(a_sizeX); m_hSizeY = 0.5 * fabs(a_sizeY); m_hSizeZ = 0.5 * fabs(a_sizeZ); // update bounding box updateBoundaryBox(); // invalidate display list markForUpdate(false); } //============================================================================== /*! This method renders the object using OpenGL \param a_options Render options. */ //============================================================================== void cShapeBox::render(cRenderOptions& a_options) { #ifdef C_USE_OPENGL ///////////////////////////////////////////////////////////////////////// // ENABLE SHADER ///////////////////////////////////////////////////////////////////////// if ((m_shaderProgram != nullptr) && (!a_options.m_creating_shadow_map)) { // enable shader m_shaderProgram->use(this, a_options); } ///////////////////////////////////////////////////////////////////////// // Render parts that use material properties ///////////////////////////////////////////////////////////////////////// if (SECTION_RENDER_PARTS_WITH_MATERIALS(a_options, m_useTransparency)) { // render material properties if (m_useMaterialProperty) { m_material->render(a_options); } if (!m_displayList.render(m_useDisplayList)) { // create display list if requested m_displayList.begin(m_useDisplayList); // render box glBegin(GL_POLYGON); glNormal3d(1.0, 0.0, 0.0); glVertex3d(m_hSizeX, m_hSizeY, m_hSizeZ); glVertex3d(m_hSizeX,-m_hSizeY, m_hSizeZ); glVertex3d(m_hSizeX,-m_hSizeY,-m_hSizeZ); glVertex3d(m_hSizeX, m_hSizeY,-m_hSizeZ); glEnd(); glBegin(GL_POLYGON); glNormal3d(-1.0, 0.0, 0.0); glVertex3d(-m_hSizeX, m_hSizeY,-m_hSizeZ); glVertex3d(-m_hSizeX,-m_hSizeY,-m_hSizeZ); glVertex3d(-m_hSizeX,-m_hSizeY, m_hSizeZ); glVertex3d(-m_hSizeX, m_hSizeY, m_hSizeZ); glEnd(); glBegin(GL_POLYGON); glNormal3d(0.0, 1.0, 0.0); glVertex3d( m_hSizeX, m_hSizeY,-m_hSizeZ); glVertex3d(-m_hSizeX, m_hSizeY,-m_hSizeZ); glVertex3d(-m_hSizeX, m_hSizeY, m_hSizeZ); glVertex3d( m_hSizeX, m_hSizeY, m_hSizeZ); glEnd(); glBegin(GL_POLYGON); glNormal3d(0.0,-1.0, 0.0); glVertex3d( m_hSizeX,-m_hSizeY, m_hSizeZ); glVertex3d(-m_hSizeX,-m_hSizeY, m_hSizeZ); glVertex3d(-m_hSizeX,-m_hSizeY,-m_hSizeZ); glVertex3d( m_hSizeX,-m_hSizeY,-m_hSizeZ); glEnd(); glBegin(GL_POLYGON); glNormal3d(0.0, 0.0, 1.0); glVertex3d( m_hSizeX, m_hSizeY, m_hSizeZ); glVertex3d(-m_hSizeX, m_hSizeY, m_hSizeZ); glVertex3d(-m_hSizeX,-m_hSizeY, m_hSizeZ); glVertex3d( m_hSizeX,-m_hSizeY, m_hSizeZ); glEnd(); glBegin(GL_POLYGON); glNormal3d(0.0, 0.0,-1.0); glVertex3d( m_hSizeX,-m_hSizeY,-m_hSizeZ); glVertex3d(-m_hSizeX,-m_hSizeY,-m_hSizeZ); glVertex3d(-m_hSizeX, m_hSizeY,-m_hSizeZ); glVertex3d( m_hSizeX, m_hSizeY,-m_hSizeZ); glEnd(); // finalize display list m_displayList.end(true); } } ///////////////////////////////////////////////////////////////////////// // DISABLE SHADER ///////////////////////////////////////////////////////////////////////// if ((m_shaderProgram != nullptr) && (!a_options.m_creating_shadow_map)) { // disable shader m_shaderProgram->disable(); } #endif } //============================================================================== /*! This method uses the position of the tool and searches for the nearest point located at the surface of the current object and identifies if the point is located inside or outside of the object. \param a_toolPos Position of the tool. \param a_toolVel Velocity of the tool. \param a_IDN Identification number of the force algorithm. */ //============================================================================== void cShapeBox::computeLocalInteraction(const cVector3d& a_toolPos, const cVector3d& a_toolVel, const unsigned int a_IDN) { // temp variables bool inside; cVector3d projectedPoint; cVector3d normal(1,0,0); // sign double signX = cSign(a_toolPos(0) ); double signY = cSign(a_toolPos(1) ); double signZ = cSign(a_toolPos(2) ); // check if tool is located inside box double tx = (signX * a_toolPos(0) ); double ty = (signY * a_toolPos(1) ); double tz = (signZ * a_toolPos(2) ); inside = false; if (cContains(tx, 0.0, m_hSizeX)) { if (cContains(ty, 0.0, m_hSizeY)) { if (cContains(tz, 0.0, m_hSizeZ)) { inside = true; } } } if (inside) { // tool is located inside box, compute distance from tool to surface double m_distanceX = m_hSizeX - (signX * a_toolPos(0) ); double m_distanceY = m_hSizeY - (signY * a_toolPos(1) ); double m_distanceZ = m_hSizeZ - (signZ * a_toolPos(2) ); // search nearest surface if (m_distanceX < m_distanceY) { if (m_distanceX < m_distanceZ) { projectedPoint(0) = signX * m_hSizeX; projectedPoint(1) = a_toolPos(1) ; projectedPoint(2) = a_toolPos(2) ; normal.set(signX * 1.0, 0.0, 0.0); } else { projectedPoint(0) = a_toolPos(0) ; projectedPoint(1) = a_toolPos(1) ; projectedPoint(2) = signZ * m_hSizeZ; normal.set(0.0, 0.0, signZ * 1.0); } } else { if (m_distanceY < m_distanceZ) { projectedPoint(0) = a_toolPos(0) ; projectedPoint(1) = signY * m_hSizeY; projectedPoint(2) = a_toolPos(2) ; normal.set(0.0, signY * 1.0, 0.0); } else { projectedPoint(0) = a_toolPos(0) ; projectedPoint(1) = a_toolPos(1) ; projectedPoint(2) = signZ * m_hSizeZ; normal.set(0.0, 0.0, signZ * 1.0); } } } else { projectedPoint(0) = cClamp(a_toolPos(0) , -m_hSizeX, m_hSizeX); projectedPoint(1) = cClamp(a_toolPos(1) , -m_hSizeY, m_hSizeY); projectedPoint(2) = cClamp(a_toolPos(2) , -m_hSizeZ, m_hSizeZ); } // return results m_interactionPoint = projectedPoint; cVector3d n = a_toolPos - projectedPoint; if (n.lengthsq() > 0.0) { m_interactionNormal = n; m_interactionNormal.normalize(); } m_interactionInside = inside; } //============================================================================== /*! This method updates the boundary box of this object. */ //============================================================================== void cShapeBox::updateBoundaryBox() { // compute half size lengths m_boundaryBoxMin.set(-m_hSizeX,-m_hSizeY,-m_hSizeZ); m_boundaryBoxMax.set( m_hSizeX, m_hSizeY, m_hSizeZ); } //============================================================================== /*! This method scales the size of this object with given scale factor. \param a_scaleFactor Scale factor. */ //============================================================================== void cShapeBox::scaleObject(const double& a_scaleFactor) { // update dimensions m_hSizeX *= a_scaleFactor; m_hSizeY *= a_scaleFactor; m_hSizeZ *= a_scaleFactor; // update bounding box updateBoundaryBox(); // invalidate display list markForUpdate(false); } //============================================================================== /*! This method determines whether a given segment intersects this object. \n The segment is described by a start point \p a_segmentPointA and end point \p a_segmentPointB. \n All detected collisions are reported in the collision recorder passed by argument \p a_recorder. \n Specifications about the type of collisions reported are specified by argument \p a_settings. \param a_segmentPointA Start point of segment. \param a_segmentPointB End point of segment. \param a_recorder Recorder which stores all collision events. \param a_settings Collision settings information. \return __true__ if a collision has occurred, __false__ otherwise. */ //============================================================================== bool cShapeBox::computeOtherCollisionDetection(cVector3d& a_segmentPointA, cVector3d& a_segmentPointB, cCollisionRecorder& a_recorder, cCollisionSettings& a_settings) { //////////////////////////////////////////////////////////////////////////// // COMPUTE COLLISION //////////////////////////////////////////////////////////////////////////// // ignore shape if requested if (a_settings.m_ignoreShapes) { return (false); } // no collision has occurred yet bool hit = false; // temp variable to store collision data cVector3d collisionPoint; cVector3d collisionNormal; // compute distance between both point composing segment double collisionDistanceSq = 0.0; cVector3d min(-m_hSizeX,-m_hSizeY,-m_hSizeZ); cVector3d max( m_hSizeX, m_hSizeY, m_hSizeZ); // compute collision detection between segment and box if (cIntersectionSegmentBox(a_segmentPointA, a_segmentPointB, min, max, collisionPoint, collisionNormal) > 0) { hit = true; collisionDistanceSq = cDistanceSq(a_segmentPointA, collisionPoint); } //////////////////////////////////////////////////////////////////////////// // REPORT COLLISION //////////////////////////////////////////////////////////////////////////// // here we finally report the new collision to the collision event handler. if (hit) { // we verify if anew collision needs to be created or if we simply // need to update the nearest collision. if (a_settings.m_checkForNearestCollisionOnly) { // no new collision event is create. We just check if we need // to update the nearest collision if(collisionDistanceSq <= a_recorder.m_nearestCollision.m_squareDistance) { // report basic collision data a_recorder.m_nearestCollision.m_type = C_COL_SHAPE; a_recorder.m_nearestCollision.m_object = this; a_recorder.m_nearestCollision.m_localPos = collisionPoint; a_recorder.m_nearestCollision.m_localNormal = collisionNormal; a_recorder.m_nearestCollision.m_squareDistance = collisionDistanceSq; a_recorder.m_nearestCollision.m_adjustedSegmentAPoint = a_segmentPointA; // report advanced collision data if (!a_settings.m_returnMinimalCollisionData) { a_recorder.m_nearestCollision.m_globalPos = cAdd(getGlobalPos(), cMul(getGlobalRot(), a_recorder.m_nearestCollision.m_localPos)); a_recorder.m_nearestCollision.m_globalNormal = cMul(getGlobalRot(), a_recorder.m_nearestCollision.m_localNormal); } } } else { cCollisionEvent newCollisionEvent; // report basic collision data newCollisionEvent.m_type = C_COL_SHAPE; newCollisionEvent.m_object = this; newCollisionEvent.m_triangles = nullptr; newCollisionEvent.m_localPos = collisionPoint; newCollisionEvent.m_localNormal = collisionNormal; newCollisionEvent.m_squareDistance = collisionDistanceSq; newCollisionEvent.m_adjustedSegmentAPoint = a_segmentPointA; // report advanced collision data if (!a_settings.m_returnMinimalCollisionData) { newCollisionEvent.m_globalPos = cAdd(getGlobalPos(), cMul(getGlobalRot(), newCollisionEvent.m_localPos)); newCollisionEvent.m_globalNormal = cMul(getGlobalRot(), newCollisionEvent.m_localNormal); } // add new collision even to collision list a_recorder.m_collisions.push_back(newCollisionEvent); // check if this new collision is a candidate for "nearest one" if(collisionDistanceSq <= a_recorder.m_nearestCollision.m_squareDistance) { a_recorder.m_nearestCollision = newCollisionEvent; } } } // return result return (hit); } //------------------------------------------------------------------------------ } // namespace chai3d //------------------------------------------------------------------------------
37.217235
123
0.524795
[ "mesh", "render", "object", "shape" ]
fc4bb64ef6e078ba7a6fdf79a1d7d09f6390bed1
3,291
cpp
C++
Plugins/AlembicImporter/Source/AlembicLibrary/Private/AbcTransform.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
null
null
null
Plugins/AlembicImporter/Source/AlembicLibrary/Private/AbcTransform.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
null
null
null
Plugins/AlembicImporter/Source/AlembicLibrary/Private/AbcTransform.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
1
2021-01-22T09:11:51.000Z
2021-01-22T09:11:51.000Z
// Copyright Epic Games, Inc. All Rights Reserved. #include "AbcTransform.h" #include "AbcImportUtilities.h" #include "AbcFile.h" THIRD_PARTY_INCLUDES_START #include <Alembic/AbcCoreAbstract/TimeSampling.h> #include <Alembic/AbcGeom/Visibility.h> THIRD_PARTY_INCLUDES_END FAbcTransform::FAbcTransform(const Alembic::AbcGeom::IXform& InTransform, const FAbcFile* InFile, IAbcObject* InParent /*= nullptr*/) : IAbcObject(InTransform, InFile, InParent), Transform(InTransform), Schema(InTransform.getSchema()) { NumSamples = Schema.getNumSamples(); bConstant = Schema.isConstant(); bConstantIdentity = Schema.isConstantIdentity(); InitialValue = FMatrix::Identity; for (int32 Index = 0; Index < MaxNumberOfResidentSamples; ++Index) { ResidentMatrices[Index] = InitialValue; } // Retrieve min and max time/frames information AbcImporterUtilities::GetMinAndMaxTime(Schema, MinTime, MaxTime); AbcImporterUtilities::GetStartTimeAndFrame(Schema, MinTime, StartFrameIndex); } bool FAbcTransform::ReadFirstFrame(const float InTime, const int32 FrameIndex) { // Read matrix sample for sample time const float Time = InTime < MinTime ? MinTime : (InTime > MinTime ? MinTime : InTime); Alembic::Abc::ISampleSelector SampleSelector = AbcImporterUtilities::GenerateAlembicSampleSelector<double>(Time); Alembic::AbcGeom::XformSample MatrixSample; Schema.get(MatrixSample, SampleSelector); InitialValue = AbcImporterUtilities::ConvertAlembicMatrix(MatrixSample.getMatrix()); AbcImporterUtilities::ApplyConversion(InitialValue, File->GetImportSettings()->ConversionSettings); return true; } void FAbcTransform::SetFrameAndTime(const float InTime, const int32 FrameIndex, const EFrameReadFlags InFlags, const int32 TargetIndex /*= INDEX_NONE*/) { if (TargetIndex != INDEX_NONE) { InUseSamples[TargetIndex] = true; ResidentSampleIndices[TargetIndex] = FrameIndex; FrameTimes[TargetIndex] = InTime; if (!bConstantIdentity && !bConstant) { Alembic::Abc::ISampleSelector SampleSelector = AbcImporterUtilities::GenerateAlembicSampleSelector<double>(InTime); Alembic::AbcGeom::XformSample MatrixSample; Schema.get(MatrixSample, SampleSelector); ResidentMatrices[TargetIndex] = AbcImporterUtilities::ConvertAlembicMatrix(MatrixSample.getMatrix()); AbcImporterUtilities::ApplyConversion(ResidentMatrices[TargetIndex], File->GetImportSettings()->ConversionSettings); } } } FMatrix FAbcTransform::GetMatrix(const int32 FrameIndex) const { if (bConstantIdentity || bConstant) { return InitialValue; } // Find matrix within resident samples for (int32 Index = 0; Index < MaxNumberOfResidentSamples; ++Index) { if (ResidentSampleIndices[Index] == FrameIndex) { return Parent ? Parent->GetMatrix(FrameIndex) * ResidentMatrices[Index] : ResidentMatrices[Index]; } } return InitialValue; } bool FAbcTransform::HasConstantTransform() const { return bConstant && (Parent ? Parent->HasConstantTransform() : true); } void FAbcTransform::PurgeFrameData(const int32 FrameIndex) { checkf(InUseSamples[FrameIndex], TEXT("Trying to purge a sample which isn't in use")); InUseSamples[FrameIndex] = false; ResidentSampleIndices[FrameIndex] = INDEX_NONE; }
35.771739
235
0.759648
[ "transform" ]
fc4bf559e6e1af9a9fac69b14949a91dd60203eb
4,107
cc
C++
solvers/create_cost.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
solvers/create_cost.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
solvers/create_cost.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/solvers/create_cost.h" #include <algorithm> #include <unordered_map> #include <unordered_set> #include <vector> #include "drake/common/polynomial.h" #include "drake/common/symbolic_decompose.h" #include "drake/common/unused.h" namespace drake { namespace solvers { namespace internal { using std::make_shared; using std::numeric_limits; using std::ostringstream; using std::runtime_error; using std::set; using std::shared_ptr; using std::unordered_map; using std::vector; using symbolic::Expression; using symbolic::Formula; using symbolic::Variable; namespace { Binding<QuadraticCost> DoParseQuadraticCost( const symbolic::Polynomial& poly, const VectorXDecisionVariable& vars_vec, const unordered_map<Variable::Id, int>& map_var_to_index) { // We want to write the expression e in the form 0.5 * x' * Q * x + b' * x + c // TODO(hongkai.dai): use a sparse matrix to represent Q and b. Eigen::MatrixXd Q(vars_vec.size(), vars_vec.size()); Eigen::VectorXd b(vars_vec.size()); double constant_term; symbolic::DecomposeQuadraticPolynomial(poly, map_var_to_index, &Q, &b, &constant_term); return CreateBinding(make_shared<QuadraticCost>(Q, b, constant_term), vars_vec); } Binding<LinearCost> DoParseLinearCost( const Expression &e, const VectorXDecisionVariable& vars_vec, const unordered_map<Variable::Id, int>& map_var_to_index) { Eigen::RowVectorXd c(vars_vec.size()); double constant_term{}; symbolic::DecomposeAffineExpression(e, map_var_to_index, c, &constant_term); return CreateBinding(make_shared<LinearCost>(c.transpose(), constant_term), vars_vec); } } // anonymous namespace Binding<LinearCost> ParseLinearCost(const Expression& e) { auto p = symbolic::ExtractVariablesFromExpression(e); return DoParseLinearCost(e, p.first, p.second); } Binding<QuadraticCost> ParseQuadraticCost(const Expression& e) { // First build an Eigen vector, that contains all the bound variables. auto p = symbolic::ExtractVariablesFromExpression(e); const auto& vars_vec = p.first; const auto& map_var_to_index = p.second; // Now decomposes the expression into coefficients and monomials. const symbolic::Polynomial poly{e}; return DoParseQuadraticCost(poly, vars_vec, map_var_to_index); } Binding<PolynomialCost> ParsePolynomialCost(const symbolic::Expression& e) { if (!e.is_polynomial()) { ostringstream oss; oss << "Expression" << e << " is not a polynomial. ParsePolynomialCost" " only supports polynomial expression.\n"; throw runtime_error(oss.str()); } const symbolic::Variables& vars = e.GetVariables(); const Polynomiald polynomial = Polynomiald::FromExpression(e); vector<Polynomiald::VarType> polynomial_vars(vars.size()); VectorXDecisionVariable var_vec(vars.size()); int polynomial_var_count = 0; for (const auto& var : vars) { polynomial_vars[polynomial_var_count] = var.get_id(); var_vec[polynomial_var_count] = var; ++polynomial_var_count; } return CreateBinding(make_shared<PolynomialCost>( Vector1<Polynomiald>(polynomial), polynomial_vars), var_vec); } Binding<Cost> ParseCost(const symbolic::Expression& e) { if (!e.is_polynomial()) { ostringstream oss; oss << "Expression " << e << " is not a polynomial. ParseCost does not" << " support non-polynomial expression.\n"; throw runtime_error(oss.str()); } const symbolic::Polynomial poly{e}; const int total_degree{poly.TotalDegree()}; auto e_extracted = symbolic::ExtractVariablesFromExpression(e); const VectorXDecisionVariable& vars_vec = e_extracted.first; const auto& map_var_to_index = e_extracted.second; if (total_degree > 2) { return ParsePolynomialCost(e); } else if (total_degree == 2) { return DoParseQuadraticCost(poly, vars_vec, map_var_to_index); } else { return DoParseLinearCost(e, vars_vec, map_var_to_index); } } } // namespace internal } // namespace solvers } // namespace drake
33.390244
80
0.714634
[ "vector" ]
fc603c85a6570a3b612e383c531a3cf66bccd68b
12,022
cpp
C++
released_plugins/v3d_plugins/marker2others/marker2others_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
released_plugins/v3d_plugins/marker2others/marker2others_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
released_plugins/v3d_plugins/marker2others/marker2others_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/* * marker2others.cpp * save an image's markers to other formats * * Created by Hanchuan Peng, 2012-07-02 */ #include "v3d_message.h" #include "marker2others_plugin.h" #include <vector> #include <iostream> using namespace std; Q_EXPORT_PLUGIN2(marker2others, Marker2OthersPlugin); // void marker2others(V3DPluginCallback2 &callback, QWidget *parent) { v3dhandle curwin = callback.currentImageWindow(); LandmarkList mlist = callback.getLandmark(curwin); QString imgname = callback.getImageName(curwin); if (mlist.isEmpty()) { v3d_msg(QString("The marker list of the current image [%1] is empty. Do nothing.").arg(imgname)); return; } NeuronTree nt; QList <NeuronSWC> & listNeuron = nt.listNeuron; for (int i=0;i<mlist.size();i++) { NeuronSWC n; n.x = mlist[i].x-1; n.y = mlist[i].y-1; n.z = mlist[i].z-1; n.n = i; n.type = 2; n.r = 1; n.pn = -1; //so the first one will be root listNeuron << n; } QString outfilename = imgname + "_marker.swc"; if (outfilename.startsWith("http", Qt::CaseInsensitive)) { QFileInfo ii(outfilename); outfilename = QDir::home().absolutePath() + "/" + ii.fileName(); } QStringList infostr; writeSWC_file(outfilename, nt, &infostr); v3d_msg(QString("The SWC file [%1] has been saved.").arg(outfilename)); return; } void others2marker(V3DPluginCallback2 &callback, QWidget *parent) { v3dhandle curwin = callback.currentImageWindow(); NeuronTree nt = callback.getSWC(curwin); QString imgname = callback.getImageName(curwin); if (!nt.listNeuron.size()) { v3d_msg(QString("The SWC of the current image [%1] is empty. Do nothing.").arg(imgname)); return; } QList <NeuronSWC> & listNeuron = nt.listNeuron; QList <ImageMarker> listLandmarks; for (int i=0;i<listNeuron.size();i++) { ImageMarker m; m.x=listNeuron[i].x; m.y=listNeuron[i].y; m.z=listNeuron[i].z; m.n=listNeuron[i].n; m.name=""; m.type=0; m.shape=0; m.radius=1; m.color.r = 255; m.color.g = 0; m.color.b = 0; listLandmarks.append(m); } QString outfilename = imgname + ".marker"; if (outfilename.startsWith("http", Qt::CaseInsensitive)) { QFileInfo ii(outfilename); outfilename = QDir::home().absolutePath() + "/" + ii.fileName(); } writeMarker_file(outfilename, listLandmarks); v3d_msg(QString("The Marker file [%1] has been saved.").arg(outfilename)); return; } bool others2marker(QString inswc_file) { QString outmarker_file = inswc_file+".marker"; NeuronTree nt=readSWC_file(inswc_file); QList <ImageMarker> listLandmarks; if(!nt.listNeuron.size()) return false; double scale=1; for(int i=0; i<nt.listNeuron.size();i++) { ImageMarker m; m.x=nt.listNeuron[i].x*scale; m.y=nt.listNeuron[i].y*scale; m.z=nt.listNeuron[i].z*scale; m.n=nt.listNeuron[i].n; m.name=""; m.type=0; m.shape=0; m.radius=1; m.color.r = 255; m.color.g = 0; m.color.b = 0; listLandmarks.append(m); } writeMarker_file(outmarker_file,listLandmarks); QString FinishMsg = QString("Marker file [") + outmarker_file + QString("] has been generated."); qDebug()<<FinishMsg; return true; } bool others2marker(const V3DPluginArgList & input, V3DPluginArgList & output) { vector<char*> infiles, inparas, outfiles; if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p); if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p); if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p); if(infiles.empty()) { cerr<<"Need input swc file"<<endl; return false; } QString inswc_file = infiles[0]; QString outmarker_file = inswc_file+".marker"; if(outfiles.size()) outmarker_file = outfiles[0]; int k=0; double scale; if (input.size()>=2) { vector<char*> paras = (*(vector<char*> *)(input.at(1).p)); scale = paras.empty() ? 1.0 : atof(paras[k]); } NeuronTree nt=readSWC_file(inswc_file); QList <ImageMarker> listLandmarks; if(!nt.listNeuron.size()) return false; for(int i=0; i<nt.listNeuron.size();i++) { ImageMarker m; m.x=nt.listNeuron[i].x*scale; m.y=nt.listNeuron[i].y*scale; m.z=nt.listNeuron[i].z*scale; m.n=nt.listNeuron[i].n; m.name=""; m.type=0; m.shape=0; m.radius=1; m.color.r = 255; m.color.g = 0; m.color.b = 0; listLandmarks.append(m); } writeMarker_file(outmarker_file,listLandmarks); return true; } bool marker2apo(const V3DPluginArgList & input, V3DPluginArgList & output) { vector<char*> infiles, inparas, outfiles; if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p); if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p); if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p); if(infiles.empty()) { cerr<<"Need input marker file"<<endl; return false; } if(outfiles.empty()) { cerr<<"Need output apo file"<<endl; return false; } QString inmarker_file = infiles[0]; QString outapo_file = outfiles[0]; int k=0; double scale; if (input.size()>=2) { vector<char*> paras = (*(vector<char*> *)(input.at(1).p)); scale = paras.empty() ? 1.0 : atof(paras[k]); } QList <ImageMarker> listLandmarks = readMarker_file(inmarker_file); QList<CellAPO> file_inmarkers; for(int i=0; i<listLandmarks.size();i++) { CellAPO t; t.x = listLandmarks[i].x*scale; t.y = listLandmarks[i].y*scale; t.z = listLandmarks[i].z*scale; t.color.r = 255; t.color.g = 0; t.color.b = 0; file_inmarkers.push_back(t); } writeAPO_file(outapo_file,file_inmarkers); return true; } bool marker2apo(QString markerFileName) { QList <ImageMarker> listLandmarks = readMarker_file(markerFileName); QList<CellAPO> file_inmarkers; for (int i = 0; i<listLandmarks.size(); i++) { CellAPO t; t.x = listLandmarks[i].x; t.y = listLandmarks[i].y; t.z = listLandmarks[i].z; t.color.r = 255; t.color.g = 0; t.color.b = 0; t.volsize = 314.159; file_inmarkers.push_back(t); } QString saveName = markerFileName + ".apo"; writeAPO_file(saveName, file_inmarkers); QString FinishMsg = QString("An apo file [") + saveName + QString("] has been generated."); v3d_msg(FinishMsg); return true; } bool apo2marker(const V3DPluginArgList & input, V3DPluginArgList & output) { vector<char*> infiles, inparas, outfiles; if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p); if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p); if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p); if(infiles.empty()) { cerr<<"Need input apo file"<<endl; return false; } QString inapo_file = infiles[0]; QString outmarker_file = inapo_file+".marker"; if(outfiles.size()) outmarker_file = outfiles[0]; QList <CellAPO> inapolist=readAPO_file(inapo_file); QList <ImageMarker> listLandmarks; if(!inapolist.size()) return false; int k=0; double scale; if (input.size()>=2) { vector<char*> paras = (*(vector<char*> *)(input.at(1).p)); scale = paras.empty() ? 1.0 : atof(paras[k]); } for(int i=0; i<inapolist.size();i++) { ImageMarker m; m.x=inapolist[i].x*scale; m.y=inapolist[i].y*scale; m.z=inapolist[i].z*scale; m.n=inapolist[i].n; m.name=inapolist[i].name; m.color=inapolist[i].color; m.comment=inapolist[i].comment; m.radius=inapolist[i].volsize; m.type=0; m.shape=0; listLandmarks.append(m); } writeMarker_file(outmarker_file,listLandmarks); return true; } bool apo2marker(QString inapo_file) { QString outmarker_file = inapo_file+".marker"; QList <CellAPO> inapolist=readAPO_file(inapo_file); QList <ImageMarker> listLandmarks; if(!inapolist.size()) return false; double scale=1; for(int i=0; i<inapolist.size();i++) { ImageMarker m; m.x=inapolist[i].x*scale; m.y=inapolist[i].y*scale; m.z=inapolist[i].z*scale; m.n=inapolist[i].n; m.name=inapolist[i].name; m.color=inapolist[i].color; m.comment=inapolist[i].comment; m.radius=inapolist[i].volsize; m.type=0; m.shape=0; listLandmarks.append(m); } writeMarker_file(outmarker_file,listLandmarks); QString FinishMsg = QString("Marker file [") + outmarker_file + QString("] has been generated."); qDebug()<<FinishMsg; return true; } void printHelp(V3DPluginCallback2 &callback, QWidget *parent) { v3d_msg("This plugin converts and saves an image's marker to the SWC format. "); qDebug()<<"This plugin also can convert apo or swc file to marker format"; } void printHelp() { qDebug()<<"vaa3d -x <libname:marker2others> -f marker2apo -i <input_marker_file> -o <out_apo_file>"; qDebug()<<"vaa3d -x <libname:marker2others> -f apo2marker -i <input_apo_file> -o <out_marker_file>"; qDebug()<<"vaa3d -x <libname:marker2others> -f swc2marker -i <input_swc_file> -o <out_marker_file>"; return; } // QStringList Marker2OthersPlugin::menulist() const { return QStringList() << tr("Save markers to SWC format") << tr("Save markers to apo format") << tr("Save apo to marker format") <<tr("Save SWC to markers format") <<tr("Convert SWC to markers format") <<tr("about"); } QStringList Marker2OthersPlugin::funclist() const { return QStringList() <<tr("marker2apo") <<tr("apo2marker") <<tr("swc2marker") <<tr("help"); } void Marker2OthersPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent) { if (menu_name == tr("Save markers to SWC format")) { marker2others(callback,parent); } else if (menu_name == tr("Save markers to apo format")) { QString markerFileName = QFileDialog::getOpenFileName(0, QObject::tr("Select marker file"), "", QObject::tr("Supported file extension (*.marker)")); marker2apo(markerFileName); } else if (menu_name == tr("Save apo to marker format")) { QString apoFileName = QFileDialog::getOpenFileName(0, QObject::tr("Select apo file"), "", QObject::tr("Supported file extension (*.apo)")); apo2marker(apoFileName); } else if (menu_name == tr("Save SWC to markers format")) { others2marker(callback,parent); } else if (menu_name == tr("Convert SWC to markers format")) { QString inswcFile = QFileDialog::getOpenFileName(0, QObject::tr("Select swc file"), "", QObject::tr("Supported file extension (*.swc)")); others2marker(inswcFile); } else if (menu_name == tr("help")) { printHelp(callback,parent); } else { printHelp(callback,parent); } } bool Marker2OthersPlugin::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent) { if (func_name == tr("marker2apo")) { marker2apo(input, output); return true; } else if (func_name == tr("apo2marker")) { apo2marker(input,output); return true; } else if (func_name == tr("swc2marker")) { others2marker(input,output); return true; } else if (func_name == tr("help")) { printHelp(); return true; } return false; }
27.573394
168
0.605556
[ "shape", "vector" ]
fc67f5062617b941ab71f83582d75e36552d1eb6
21,114
cpp
C++
copasi/UI/CQBrowserPaneDM.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/UI/CQBrowserPaneDM.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/UI/CQBrowserPaneDM.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
// Copyright (C) 2011 - 2013 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include <sstream> #include "copasi.h" #include "CQBrowserPaneDM.h" #include "DataModel.txt.h" #include "qtUtilities.h" #include "DataModelGUI.h" #include "utilities/CCopasiTree.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "model/CModel.h" #include "utilities/CCopasiTask.h" #include "report/CReportDefinitionVector.h" #include "plot/COutputDefinitionVector.h" #include "report/CCopasiRootContainer.h" #include "function/CFunctionDB.h" #include "model/CMetabNameInterface.h" CQBrowserPaneDM::CQBrowserPaneDM(QObject * pParent): QAbstractItemModel(pParent), mpRoot(NULL), mpCopasiDM(NULL), mpGuiDM(NULL), mEmitDataChanged(true), mFlags(CQBrowserPaneDM::Model | CQBrowserPaneDM::Tasks | CQBrowserPaneDM::Output | CQBrowserPaneDM::FunctionDB) { // setSortRole(Qt::EditRole); createStaticDM(); } // virtual CQBrowserPaneDM::~CQBrowserPaneDM() { pdelete(mpRoot); } // virtual int CQBrowserPaneDM::columnCount(const QModelIndex & /* parent */) const { return 1; } // virtual QVariant CQBrowserPaneDM::data(const QModelIndex & index, int role) const { CNode * pNode = nodeFromIndex(index); if (pNode == NULL) return QVariant(); switch (role) { case Qt::DisplayRole: // We need to add the number of children to some nodes. switch (pNode->getId()) { case 5: case 42: case 43: case 111: case 112: case 114: case 115: case 116: case 119: return QVariant(pNode->getDisplayRole() + " (" + QString::number(pNode->getNumChildren()) + ")"); break; default: return QVariant(pNode->getDisplayRole()); break; } break; case Qt::EditRole: return QVariant(pNode->getSortRole()); break; } return QVariant(); } // virtual QModelIndex CQBrowserPaneDM::index(int row, int column, const QModelIndex & parent) const { CNode * pParent = nodeFromIndex(parent); if (pParent == NULL) return createIndex(row, column, mpRoot); CNode * pNode = static_cast< CNode * >(pParent->getChild(row)); if (pNode) return createIndex(row, column, pNode); else return QModelIndex(); } // virtual QModelIndex CQBrowserPaneDM::parent(const QModelIndex & index) const { CNode * pNode = nodeFromIndex(index); if (pNode == NULL || pNode == mpRoot) { return QModelIndex(); } CNode * pParent = static_cast< CNode * >(pNode->getParent()); assert(pParent != NULL); return createIndex(pParent->getRow(), 0, pParent); } QModelIndex CQBrowserPaneDM::index(const size_t & id, const std::string & key) const { CNode * pNode = NULL; if (id != C_INVALID_INDEX) { pNode = findNodeFromId(id); } else if (key != "") { pNode = findNodeFromKey(key); } return index(pNode); } // virtual int CQBrowserPaneDM::rowCount(const QModelIndex & parent) const { if (!parent.isValid()) return (mpRoot != NULL) ? 1 : 0; CNode * pParent = nodeFromIndex(parent); return pParent->getNumChildren(); } // virtual bool CQBrowserPaneDM::removeRows(int row, int count, const QModelIndex & parent) { CNode * pParent = nodeFromIndex(parent); if (pParent == NULL) return false; CNode * pNode = static_cast< CNode * >(pParent->getChild(row)); beginRemoveRows(parent, row, row + count - 1); for (int i = 0; i < count && pNode != NULL; i++) { CNode * pTmp = pNode; pNode = static_cast< CNode * >(pNode->getSibling()); delete pTmp; } endRemoveRows(); return true; } CQBrowserPaneDM::CNode * CQBrowserPaneDM::findNodeFromId(const size_t & id) const { CCopasiTree< CNode >::iterator it = mpRoot; CCopasiTree< CNode >::iterator end; for (; it != end; ++it) { if (it->getData().mId == id) { return &*it; } } return NULL; } CQBrowserPaneDM::CNode * CQBrowserPaneDM::findNodeFromKey(const std::string & key) const { CCopasiTree< CNode >::iterator it = mpRoot; CCopasiTree< CNode >::iterator end; for (; it != end; ++it) { if (it->getData().mKey == key) { return &*it; } } return NULL; } size_t CQBrowserPaneDM::getIdFromIndex(const QModelIndex & index) const { CNode * pNode = nodeFromIndex(index); if (pNode == NULL) return C_INVALID_INDEX; return pNode->getId(); } std::string CQBrowserPaneDM::getKeyFromIndex(const QModelIndex & index) const { CNode * pNode = nodeFromIndex(index); if (pNode == NULL) return ""; return pNode->getKey(); } void CQBrowserPaneDM::remove(const std::string & key) { CNode * pNode = findNodeFromKey(key); if (pNode == NULL || pNode->getParent() == NULL) { return; } QModelIndex Parent = index(static_cast< CNode * >(pNode->getParent())); removeRows(pNode->getRow(), 1, Parent); } void CQBrowserPaneDM::rename(const std::string & key, const QString & displayRole) { CNode * pNode = findNodeFromKey(key); if (pNode == NULL) return; if (pNode->getDisplayRole() != displayRole) { pNode->setDisplayRole(displayRole); QModelIndex Index = index(pNode); if (mEmitDataChanged) { emit dataChanged(Index, Index); } } } void CQBrowserPaneDM::add(const size_t & id, const std::string & key, const QString & displayRole, const size_t & parentId) { CNode * pParent = findNodeFromId(parentId); int row = 0; if (pParent != NULL) { row = pParent->getNumChildren(); } beginInsertRows(index(pParent), row, row); new CNode(id, key, displayRole, pParent); endInsertRows(); } void CQBrowserPaneDM::setCopasiDM(const CCopasiDataModel * pDataModel) { if (mpCopasiDM != pDataModel) { mpCopasiDM = pDataModel; mEmitDataChanged = false; clear(); load(); dataChanged(index(0, 0), index(0, 0)); mEmitDataChanged = true; } } void CQBrowserPaneDM::setGuiDM(const DataModelGUI * pDataModel) { if (mpGuiDM) { disconnect(mpGuiDM, SIGNAL(notifyView(ListViews::ObjectType, ListViews::Action, std::string)), this, SLOT(slotNotify(ListViews::ObjectType, ListViews::Action, const std::string &))); } mpGuiDM = pDataModel; if (mpGuiDM) { connect(mpGuiDM, SIGNAL(notifyView(ListViews::ObjectType, ListViews::Action, std::string)), this, SLOT(slotNotify(ListViews::ObjectType, ListViews::Action, std::string))); } } void CQBrowserPaneDM::load() { findNodeFromId(1)->setKey(mpCopasiDM->getModel()->getKey()); load(111); // Compartment load(112); // Species load(114); // Reactions load(115); // Global Quantities load(116); // Events findNodeFromId(118)->setKey(mpCopasiDM->getModel()->getModelParameterSet().getKey()); // Parameter Set findNodeFromId(119)->setKey(mpCopasiDM->getModel()->getKey()); load(119); // Model Parameter Sets findNodeFromId(21)->setKey((*mpCopasiDM->getTaskList())["Steady-State"]->getKey()); findNodeFromId(221)->setKey((*mpCopasiDM->getTaskList())["Elementary Flux Modes"]->getKey()); findNodeFromId(222)->setKey((*mpCopasiDM->getTaskList())["Moieties"]->getKey()); findNodeFromId(2221)->setKey((*mpCopasiDM->getTaskList())["Moieties"]->getKey()); findNodeFromId(23)->setKey((*mpCopasiDM->getTaskList())["Time-Course"]->getKey()); findNodeFromId(24)->setKey((*mpCopasiDM->getTaskList())["Metabolic Control Analysis"]->getKey()); findNodeFromId(27)->setKey((*mpCopasiDM->getTaskList())["Time Scale Separation Analysis"]->getKey()); findNodeFromId(26)->setKey((*mpCopasiDM->getTaskList())["Lyapunov Exponents"]->getKey()); findNodeFromId(28)->setKey((*mpCopasiDM->getTaskList())["Cross Section"]->getKey()); findNodeFromId(31)->setKey((*mpCopasiDM->getTaskList())["Scan"]->getKey()); findNodeFromId(32)->setKey((*mpCopasiDM->getTaskList())["Optimization"]->getKey()); findNodeFromId(33)->setKey((*mpCopasiDM->getTaskList())["Parameter Estimation"]->getKey()); findNodeFromId(34)->setKey((*mpCopasiDM->getTaskList())["Sensitivities"]->getKey()); findNodeFromId(35)->setKey((*mpCopasiDM->getTaskList())["Linear Noise Approximation"]->getKey()); findNodeFromId(42)->setKey(mpCopasiDM->getPlotDefinitionList()->getKey()); load(42); // Plot Specifications findNodeFromId(43)->setKey(mpCopasiDM->getReportDefinitionList()->getKey()); load(43); // Report Specifications load(5); // Functions dataChanged(index(0, 0), index(0, 0)); } void CQBrowserPaneDM::load(const size_t & id) { bool isSpecies = false; const CModel * pModel = mpCopasiDM->getModel(); const CCopasiVector< CCopasiObject > * pVector = NULL; switch (id) { case 111: // Compartment pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(&pModel->getCompartments()); break; case 112: // Species pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(&pModel->getMetabolites()); isSpecies = true; break; case 114: // Reactions pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(&pModel->getReactions()); break; case 115: // Global Quantities pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(&pModel->getModelValues()); break; case 116: // Events pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(&pModel->getEvents()); break; case 119: // Parameter Sets pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(&pModel->getModelParameterSets()); break; case 42: // Plot Specifications pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(mpCopasiDM->getPlotDefinitionList()); break; case 43: // Report Specifications pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(mpCopasiDM->getReportDefinitionList()); break; case 5: // Functions pVector = reinterpret_cast< const CCopasiVector< CCopasiObject > * >(&CCopasiRootContainer::getFunctionList()->loadedFunctions()); break; default: return; break; } // We need to compare the existing nodes with the COPASI data model objects. CNode * pParent = findNodeFromId(id); CCopasiNode< CQBrowserPaneDM::SData > * pChildData = pParent->CCopasiNode< CQBrowserPaneDM::SData >::getChild(); CCopasiVector< CCopasiObject >::const_iterator it = pVector->begin(); CCopasiVector< CCopasiObject >::const_iterator end = pVector->end(); bool changed = false; for (; pChildData != NULL && it != end; pChildData = pChildData->getSibling(), ++it) { CNode * pChild = static_cast< CNode *>(pChildData); pChild->setKey((*it)->getKey()); QString DisplayRole; if (isSpecies) { DisplayRole = FROM_UTF8(CMetabNameInterface::getDisplayName(pModel, *static_cast<const CMetab *>(*it), false)); } else { DisplayRole = FROM_UTF8((*it)->getObjectName()); } if (pChild->getDisplayRole() != DisplayRole) { pChild->setDisplayRole(DisplayRole); changed = true; } } // Remove excess nodes if (pChildData != NULL) { int row = static_cast< CNode *>(pChildData)->getRow(); int count = 0; while (pChildData != NULL) { count++; pChildData = pChildData->getSibling(); } removeRows(row, count, index(pParent)); } // Add missing nodes if (it != end) { int first = pParent->getNumChildren(); int last = first + (end - it) - 1; beginInsertRows(index(pParent), first, last); for (; it != end; ++it) { QString DisplayRole; if (isSpecies) { DisplayRole = FROM_UTF8(CMetabNameInterface::getDisplayName(pModel, *static_cast<const CMetab *>(*it), false)); } else { DisplayRole = FROM_UTF8((*it)->getObjectName()); } new CNode(C_INVALID_INDEX, (*it)->getKey(), DisplayRole, pParent); } endInsertRows(); } if (changed && mEmitDataChanged) { QModelIndex Parent = index(pParent); emit dataChanged(Parent, Parent); } } bool CQBrowserPaneDM::slotNotify(ListViews::ObjectType objectType, ListViews::Action action, std::string key) { if (key == "") { // Load is only reporting actual changes. load(); return true; } const CCopasiObject * pObject = CCopasiRootContainer::getKeyFactory()->get(key); if (pObject == NULL && action != ListViews::DELETE) { return false; } QString DisplayRole; if (pObject != NULL) { // We have a key we can there fore determine the display role. DisplayRole = FROM_UTF8(pObject->getObjectName()); // Species need to be handled differently const CMetab * pMetab = dynamic_cast< const CMetab *>(pObject); if (pMetab != NULL) { const CModel * pModel = pMetab->getModel(); if (pModel != NULL) { DisplayRole = FROM_UTF8(CMetabNameInterface::getDisplayName(pModel, *pMetab, false)); } } } switch (action) { case ListViews::RENAME: case ListViews::CHANGE: switch (objectType) { case ListViews::COMPARTMENT: case ListViews::METABOLITE: case ListViews::REACTION: case ListViews::MODELVALUE: case ListViews::EVENT: case ListViews::PLOT: case ListViews::REPORT: case ListViews::FUNCTION: case ListViews::LAYOUT: case ListViews::MODELPARAMETERSET: rename(key, DisplayRole); break; default: break; } break; case ListViews::DELETE: // TODO CRITICAL We need to be smarter when deleting objects switch (objectType) { case ListViews::COMPARTMENT: case ListViews::METABOLITE: case ListViews::REACTION: case ListViews::MODELVALUE: case ListViews::EVENT: case ListViews::PLOT: case ListViews::REPORT: case ListViews::FUNCTION: case ListViews::LAYOUT: case ListViews::MODELPARAMETERSET: remove(key); break; default: break; } break; case ListViews::ADD: { switch (objectType) { case ListViews::MODEL: load(); break; case ListViews::COMPARTMENT: add(C_INVALID_INDEX, key, DisplayRole, 111); break; case ListViews::METABOLITE: add(C_INVALID_INDEX, key, DisplayRole, 112); break; case ListViews::REACTION: add(C_INVALID_INDEX, key, DisplayRole, 114); break; case ListViews::MODELVALUE: add(C_INVALID_INDEX, key, DisplayRole, 115); break; case ListViews::EVENT: add(C_INVALID_INDEX, key, DisplayRole, 116); break; case ListViews::MODELPARAMETERSET: add(C_INVALID_INDEX, key, DisplayRole, 119); break; case ListViews::PLOT: add(C_INVALID_INDEX, key, DisplayRole, 42); break; case ListViews::REPORT: add(C_INVALID_INDEX, key, DisplayRole, 43); break; case ListViews::FUNCTION: add(C_INVALID_INDEX, key, DisplayRole, 5); break; default: break; } } break; } return true; } QModelIndex CQBrowserPaneDM::index(CQBrowserPaneDM::CNode * pNode) const { if (pNode == NULL) { return QModelIndex(); } if (pNode == mpRoot) { return index(0, 0, QModelIndex()); } QModelIndex Parent = index(static_cast< CNode * >(pNode->getParent())); return index(pNode->getRow(), 0, Parent); } CQBrowserPaneDM::CNode * CQBrowserPaneDM::nodeFromIndex(const QModelIndex & index) { if (!index.isValid()) return NULL; QModelIndex Tmp = index; const QAbstractItemModel *pModel = Tmp.model(); while (pModel->inherits("QSortFilterProxyModel")) { Tmp = static_cast< const QSortFilterProxyModel *>(pModel)->mapToSource(index); pModel = Tmp.model(); } return static_cast< CNode * >(Tmp.internalPointer()); } void CQBrowserPaneDM::createStaticDM() { mpRoot = new CNode(0, "", "COPASI", NULL); std::stringstream in; in.str(DataModeltxt); std::string str1; std::string delimiter("\x0a\x0d"); char c; while (!in.eof()) { str1 = ""; while (!in.fail()) { in.get(c); if (delimiter.find(c) != std::string::npos) break; str1 += c; } if (str1 == "") break; QString data(FROM_UTF8(str1)); int first = data.indexOf(':'); int second = data.indexOf(':', first + 1); int parentId = data.mid(0, first).toInt(); int myId = data.mid(first + 1, second - first - 1).toInt(); QString str = data.mid(second + 1, data.length() - second - 1); CNode * pParent = NULL; if (parentId == 0) { switch (myId) { case 1: pParent = (mFlags & Model) ? mpRoot : NULL; break; case 2: pParent = (mFlags & Tasks) ? mpRoot : NULL; break; case 4: pParent = (mFlags & Output) ? mpRoot : NULL; break; case 5: pParent = (mFlags & FunctionDB) ? mpRoot : NULL; break; } } else { pParent = this->findNodeFromId(parentId); } if (pParent != NULL) { new CNode(myId, "", str, pParent); } } } void CQBrowserPaneDM::clear() { findNodeFromId(111)->deleteChildren(); // Compartment findNodeFromId(112)->deleteChildren(); // Species findNodeFromId(114)->deleteChildren(); // Reactions findNodeFromId(115)->deleteChildren(); // Global Quantities findNodeFromId(116)->deleteChildren(); // Events findNodeFromId(119)->deleteChildren(); // Model Parameter Sets findNodeFromId(42)->deleteChildren(); // Plot Specifications findNodeFromId(43)->deleteChildren(); // Report Specifications findNodeFromId(5)->deleteChildren(); // Functions } CQBrowserPaneDM::CNode::CNode(): CCopasiNode< CQBrowserPaneDM::SData >() {} CQBrowserPaneDM::CNode::CNode(const size_t & id, const std::string & key, const QString & displayRole, CNode * pParent): CCopasiNode< CQBrowserPaneDM::SData >(pParent) { mData.mId = id; mData.mKey = key; mData.mDisplayRole = displayRole; if (pParent != NULL) { pParent->addChild(this); } } CQBrowserPaneDM::CNode::~CNode() {} const size_t & CQBrowserPaneDM::CNode::getId() const { return mData.mId; } void CQBrowserPaneDM::CNode::setDisplayRole(const QString & displayRole) { mData.mDisplayRole = displayRole; } const QString & CQBrowserPaneDM::CNode::getDisplayRole() const { return mData.mDisplayRole; } QString CQBrowserPaneDM::CNode::getSortRole() const { if (mData.mId == C_INVALID_INDEX) { return mData.mDisplayRole; } return QString::number(mData.mId); } void CQBrowserPaneDM::CNode::setKey(const std::string & key) { mData.mKey = key; } const std::string & CQBrowserPaneDM::CNode::getKey() const { return mData.mKey; } int CQBrowserPaneDM::CNode::getRow() const { int count = 0; const CCopasiNode< CQBrowserPaneDM::SData > * pParent = getParent(); if (pParent == NULL) { return 0; } const CCopasiNode< CQBrowserPaneDM::SData > * pChild = pParent->getChild(); while (pChild != NULL && pChild != this) { count++; pChild = pChild->getSibling(); } return (pChild != NULL) ? count : -1; } std::ostream & operator<<(std::ostream &os, const CQBrowserPaneDM::CNode & n) { os << "CQBrowserPaneDM::CNode:" << std::endl; //os << " mChemicalEquation: " << d.getChemicalEquation() << std::endl; //os << " mChemicalEquationConverted: " << d.getChemicalEquationConverted() << std::endl; os << " mId: " << n.mData.mId << std::endl; os << " mKey: " << n.mData.mKey << std::endl; os << " mDisplayRole: " << TO_UTF8(n.mData.mDisplayRole) << std::endl; return os; }
25.561743
138
0.603959
[ "model" ]
fc6d0a699fa8dafc3a5ba64fb704b83c672000ec
1,031
cpp
C++
src/regression/Regression.cpp
jwadia/CPP-MachineLearning
aa7b8dd02fad8f143d0214d4b39c56aa59e7aa18
[ "MIT" ]
null
null
null
src/regression/Regression.cpp
jwadia/CPP-MachineLearning
aa7b8dd02fad8f143d0214d4b39c56aa59e7aa18
[ "MIT" ]
null
null
null
src/regression/Regression.cpp
jwadia/CPP-MachineLearning
aa7b8dd02fad8f143d0214d4b39c56aa59e7aa18
[ "MIT" ]
null
null
null
#include "Regression.h" #include "../util/Matrix.h" #include <math.h> Regression::Regression(std::vector<double> xList, std::vector<double> yList) { x = xList; y = yList; } std::vector<double> Regression::PolynomialRegression(int order) { if(x.size() == y.size()) { int n = x.size(); double sum = 0; std::vector<double> row; std::vector<std::vector<double>> matrix; std::vector<std::vector<double>> ans; for(int i = 0; i <= order; i++) { for(int j = 0; j <= order; j++) { if(i == 0 && j == 0) { row.push_back(n); } else { for(double k : x) { sum+=pow(k,j+i); } row.push_back(sum); sum = 0; } } matrix.push_back(row); row.clear(); } for(int i = 0; i <= order; i++) { for(int j = 0; j <= n; j++) { sum+=(pow(x[j],i)*y[j]); } ans.push_back({sum}); sum = 0; } Matrix m(matrix, ans); return m.solve(); } }
23.431818
78
0.466537
[ "vector" ]
fc6ebb09ba243d5bc7ff34ee68aef9e41b4e7dd2
2,176
cpp
C++
aws-cpp-sdk-application-autoscaling/source/model/StepAdjustment.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-application-autoscaling/source/model/StepAdjustment.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-application-autoscaling/source/model/StepAdjustment.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/application-autoscaling/model/StepAdjustment.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ApplicationAutoScaling { namespace Model { StepAdjustment::StepAdjustment() : m_metricIntervalLowerBound(0.0), m_metricIntervalLowerBoundHasBeenSet(false), m_metricIntervalUpperBound(0.0), m_metricIntervalUpperBoundHasBeenSet(false), m_scalingAdjustment(0), m_scalingAdjustmentHasBeenSet(false) { } StepAdjustment::StepAdjustment(JsonView jsonValue) : m_metricIntervalLowerBound(0.0), m_metricIntervalLowerBoundHasBeenSet(false), m_metricIntervalUpperBound(0.0), m_metricIntervalUpperBoundHasBeenSet(false), m_scalingAdjustment(0), m_scalingAdjustmentHasBeenSet(false) { *this = jsonValue; } StepAdjustment& StepAdjustment::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("MetricIntervalLowerBound")) { m_metricIntervalLowerBound = jsonValue.GetDouble("MetricIntervalLowerBound"); m_metricIntervalLowerBoundHasBeenSet = true; } if(jsonValue.ValueExists("MetricIntervalUpperBound")) { m_metricIntervalUpperBound = jsonValue.GetDouble("MetricIntervalUpperBound"); m_metricIntervalUpperBoundHasBeenSet = true; } if(jsonValue.ValueExists("ScalingAdjustment")) { m_scalingAdjustment = jsonValue.GetInteger("ScalingAdjustment"); m_scalingAdjustmentHasBeenSet = true; } return *this; } JsonValue StepAdjustment::Jsonize() const { JsonValue payload; if(m_metricIntervalLowerBoundHasBeenSet) { payload.WithDouble("MetricIntervalLowerBound", m_metricIntervalLowerBound); } if(m_metricIntervalUpperBoundHasBeenSet) { payload.WithDouble("MetricIntervalUpperBound", m_metricIntervalUpperBound); } if(m_scalingAdjustmentHasBeenSet) { payload.WithInteger("ScalingAdjustment", m_scalingAdjustment); } return payload; } } // namespace Model } // namespace ApplicationAutoScaling } // namespace Aws
22.666667
81
0.769761
[ "model" ]
fc6eccc33b8c75cf9069c40166b85555f4e46ff6
3,391
cpp
C++
core/Blocks.cpp
DiscoveryInstitute/haplo
c2b49bc0920aaf68f4364646a30ef2614329b103
[ "MIT" ]
null
null
null
core/Blocks.cpp
DiscoveryInstitute/haplo
c2b49bc0920aaf68f4364646a30ef2614329b103
[ "MIT" ]
null
null
null
core/Blocks.cpp
DiscoveryInstitute/haplo
c2b49bc0920aaf68f4364646a30ef2614329b103
[ "MIT" ]
null
null
null
#include <algorithm> #include <string> #include "Blocks.h" #include "BlocksRange.h" using namespace std; template<typename V> Blocks<V> Blocks<V>::combine( const Blocks<V>& blocks_A, const Blocks<V>& blocks_B, const BlocksRange& pattern) { auto it0 = blocks_A.m_intervals.cbegin(); // 0 for off/unselected auto it1 = blocks_B.m_intervals.cbegin(); // 1 for on/selected auto end0 = blocks_A.m_intervals.cend(); auto end1 = blocks_B.m_intervals.cend(); auto tog_it = pattern.m_toggles.cbegin(); auto tog_end = pattern.m_toggles.cend(); V current0 = V(); V current1 = V(); Blocks<V> blocks_C; auto& intervals_C = blocks_C.m_intervals; for ( ; tog_it != tog_end; ++tog_it) { for ( ; it1 != end1 && it1->first < *tog_it; ++it1) { intervals_C.push_back(*it1); current1 = it1->second; } swap(it0, it1); swap(end0, end1); swap(current0, current1); for ( ; it1 != end1 && it1->first <= *tog_it; ++it1) { current1 = it1->second; } if (current1 != current0) { intervals_C.emplace_back(*tog_it, current1); } } for ( ; it1 != end1; ++it1) { intervals_C.push_back(*it1); current1 = it1->second; } return blocks_C; } template<typename V> Blocks<V> Blocks<V>::filtered(const BlocksRange& filterPattern) const { return combine(*this, Blocks<V>(), filterPattern); } template<typename V> Blocks<V> Blocks<V>::compressed() { const auto& old_intervals = this->m_intervals; Blocks<V> new_blocks; auto& new_intervals = new_blocks.m_intervals; auto it = old_intervals.begin(); auto end_it = old_intervals.end(); new_intervals.emplace_back(*it); for ( ; it != end_it; ++it) { if (new_intervals.back().second != it->second) { new_intervals.emplace_back(*it); } } return new_blocks; } template<typename V> bool Blocks<V>::operator==(const Blocks<V>& other) const { return (this->m_intervals.size() == other.m_intervals.size()) && equal(this->m_intervals.cbegin(), this->m_intervals.cend(), other.m_intervals.cbegin()); } template<typename V> V Blocks<V>::getValue(long position) const { auto itBegin = m_intervals.cbegin(); auto itEnd = m_intervals.cend(); typedef pair<long,V> P; auto it = upper_bound( itBegin, itEnd, make_pair(position, V()), [](const P& a, const P& b) { return a.first < b.first; }); return it==itBegin ? V() : prev(it)->second; } template<typename V> string Blocks<V>::toString() const { string s = ""; const auto& v = m_intervals; long n = v.size(); if (n==0) return "[0,end): " + to_string(V()) + ", "; long last = n-1; if (v[0].first != 0) { s += "[0," + to_string(v[0].first) + "):" + to_string(V()) + ", "; } for(int i=0; i<last; i++) { s += "[" + to_string(v[i].first) + "," + to_string(v[i+1].first) + "):" + to_string(v[i].second) + ", "; } s += "[" + to_string(v[last].first) + ",end):" + to_string(v[last].second) + ", "; return s; } template<typename V> size_t Blocks<V>::getSizeInMemory() const { return sizeof(vector<pair<long,V>>) + m_intervals.size() * sizeof(pair<long,V>); } // Specify which class(es) we want to pre-compile. template class Blocks<int>; template class Blocks<long>;
28.737288
106
0.598054
[ "vector" ]
fc71bb11b49cc0bee20ad7ced3e28ce44a6e6fec
14,693
cpp
C++
IndieLib/common/src/render/directx/RenderObject2dDirectX.cpp
DarthMike/indielib-crossplatform
473a589ae050b6d1c274cf58adf08731e63ae870
[ "Zlib" ]
29
2015-03-05T08:11:23.000Z
2020-11-11T08:27:22.000Z
IndieLib/common/src/render/directx/RenderObject2dDirectX.cpp
PowerOlive/indielib-crossplatform
473a589ae050b6d1c274cf58adf08731e63ae870
[ "Zlib" ]
1
2019-04-03T18:59:01.000Z
2019-04-14T11:46:45.000Z
IndieLib/common/src/render/directx/RenderObject2dDirectX.cpp
PowerOlive/indielib-crossplatform
473a589ae050b6d1c274cf58adf08731e63ae870
[ "Zlib" ]
9
2015-03-05T08:17:10.000Z
2021-08-09T07:15:37.000Z
/***************************************************************************************** * File: RenderObject2dDirectX.cpp * Desc: Blitting of 2d objects using D3D *****************************************************************************************/ /*********************************** The zlib License ************************************ * * Copyright (c) 2013 Indielib-crossplatform Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. * *****************************************************************************************/ #include "Defines.h" #ifdef INDIERENDER_DIRECTX // ----- Includes ----- /** @cond DOCUMENT_PRIVATEAPI */ #include "Global.h" #include "IND_SurfaceManager.h" #include "IND_Surface.h" #include "TextureDefinitions.h" #include "IND_Animation.h" #include "DirectXRender.h" // -------------------------------------------------------------------------------- // Public methods // -------------------------------------------------------------------------------- void DirectXRender::blitSurface(IND_Surface *pSu) { // ----- Blitting ----- int mCont = 0; for (int i = 0; i < pSu->getNumBlocks(); i++) { // ----- Transform 4 vertices of the quad into world space coordinates ----- D3DXVECTOR4 mP1, mP2, mP3, mP4; Transform4Vertices(static_cast<float>(pSu->_surface->_vertexArray[mCont]._pos._x), static_cast<float>(pSu->_surface->_vertexArray[mCont]._pos._y), static_cast<float>(pSu->_surface->_vertexArray[mCont + 1]._pos._x), static_cast<float>(pSu->_surface->_vertexArray[mCont + 1]._pos._y), static_cast<float>(pSu->_surface->_vertexArray[mCont + 2]._pos._x), static_cast<float>(pSu->_surface->_vertexArray[mCont + 2]._pos._y), static_cast<float>(pSu->_surface->_vertexArray[mCont + 3]._pos._x), static_cast<float>(pSu->_surface->_vertexArray[mCont + 3]._pos._y), &mP1, &mP2, &mP3, &mP4); IND_Vector3 mP1_f3(mP1.x,mP1.y,mP1.z); IND_Vector3 mP2_f3(mP2.x,mP2.y,mP2.z); IND_Vector3 mP3_f3(mP3.x,mP3.y,mP3.z); IND_Vector3 mP4_f3(mP4.x,mP4.y,mP4.z); // Calculate the bounding rectangle that we are going to try to discard _math->calculateBoundingRectangle(&mP1_f3, &mP2_f3, &mP3_f3, &mP4_f3); // ---- Discard bounding rectangle using frustum culling if possible ---- if (_math->cullFrustumBox(mP1_f3, mP2_f3,_frustrumPlanes)) { _info._device->SetFVF(D3DFVF_CUSTOMVERTEX2D); if (!pSu->isHaveGrid()) { //Texture ID - If it doesn't have a grid, every other block must be blit by //a different texture in texture array ID. _info._device->SetTexture(0, pSu->_surface->_texturesArray[i]._texture); } else { //In a case of rendering a grid. Same texture (but different vertex position) //is rendered all the time. In other words, different pieces of same texture are rendered _info._device->SetTexture(0, pSu->_surface->_texturesArray[0]._texture); } _info._device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, pSu->_surface->_vertexArray + mCont, sizeof(CUSTOMVERTEX2D)); _numrenderedObjects++; } else _numDiscardedObjects++; mCont += 4; } } void DirectXRender::blitGrid(IND_Surface *pSu, unsigned char pR, unsigned char pG, unsigned char pB, unsigned char pA) { D3DXMATRIX mMatWorld; _info._device->GetTransform(D3DTS_WORLD, &mMatWorld); for (int i = 0; i < pSu->getNumBlocks() * 4; i += 4) { // ----- Transform 4 vertices of the quad into world space coordinates ----- D3DXVECTOR4 mP1, mP2, mP3, mP4; Transform4Vertices(static_cast<float>( pSu->_surface->_vertexArray[i]._pos._x), static_cast<float>( pSu->_surface->_vertexArray[i]._pos._y), static_cast<float>( pSu->_surface->_vertexArray[i + 1]._pos._x), static_cast<float>( pSu->_surface->_vertexArray[i + 1]._pos._y), static_cast<float>( pSu->_surface->_vertexArray[i + 2]._pos._x), static_cast<float>( pSu->_surface->_vertexArray[i + 2]._pos._y), static_cast<float>( pSu->_surface->_vertexArray[i + 3]._pos._x), static_cast<float>( pSu->_surface->_vertexArray[i + 3]._pos._y), &mP1, &mP2, &mP3, &mP4); IND_Vector3 mP1_f3(mP1.x,mP1.y,mP1.z); IND_Vector3 mP2_f3(mP2.x,mP2.y,mP2.z); IND_Vector3 mP3_f3(mP3.x,mP3.y,mP3.z); IND_Vector3 mP4_f3(mP4.x,mP4.y,mP4.z); // Calculate the bounding rectangle that we are going to try to discard _math->calculateBoundingRectangle(&mP1_f3, &mP2_f3, &mP3_f3, &mP4_f3); // ---- Discard bounding rectangle using frustum culling if possible ---- //FIXME: This discards some grids when they are visible. Run test INDImageTests_nonPOTLoad to see effect on planet image grid. if (_math->cullFrustumBox(mP1_f3, mP2_f3,_frustrumPlanes)) { BlitGridQuad(static_cast<int>(pSu->_surface->_vertexArray[i]._pos._x), static_cast<int>(pSu->_surface->_vertexArray[i]._pos._y), static_cast<int>(pSu->_surface->_vertexArray[i + 1]._pos._x), static_cast<int>(pSu->_surface->_vertexArray[i + 1]._pos._y), static_cast<int>(pSu->_surface->_vertexArray[i + 2]._pos._x), static_cast<int>(pSu->_surface->_vertexArray[i + 2]._pos._y), static_cast<int>(pSu->_surface->_vertexArray[i + 3]._pos._x), static_cast<int>(pSu->_surface->_vertexArray[i + 3]._pos._y), pR, pG, pB, pA, mMatWorld); } } } void DirectXRender::blitRegionSurface(IND_Surface *pSu, int pX, int pY, int pWidth, int pHeight) { // If the region is the same as the image area, we blit normally // If the region is the same as the image area, we blit normally if (!pX && !pY && (pWidth == pSu->getWidth()) && (pHeight == pSu->getHeight())) { blitSurface(pSu); } else { bool correctParams = true; if (pSu->getNumTextures() > 1 || pX < 0 || pX + pWidth > pSu->getWidth() || pY < 0 || pY + pHeight > pSu->getHeight()) { correctParams = false; } if (correctParams) { // ----- Transform 4 vertices of the quad into world space coordinates ----- D3DXVECTOR4 mP1, mP2, mP3, mP4; Transform4Vertices(static_cast<float>(pWidth), 0.0f, static_cast<float>(pWidth), static_cast<float>(pHeight), 0.0f, 0.0f, 0.0f, static_cast<float>(pHeight), &mP1, &mP2, &mP3, &mP4); IND_Vector3 mP1_f3(mP1.x,mP1.y,mP1.z); IND_Vector3 mP2_f3(mP2.x,mP2.y,mP2.z); IND_Vector3 mP3_f3(mP3.x,mP3.y,mP3.z); IND_Vector3 mP4_f3(mP4.x,mP4.y,mP4.z); // Calculate the bounding rectangle that we are going to try to discard _math->calculateBoundingRectangle(&mP1_f3, &mP2_f3, &mP3_f3, &mP4_f3); // ---- Discard bounding rectangle using frustum culling if possible ---- if (!_math->cullFrustumBox(mP1_f3, mP2_f3,_frustrumPlanes)) { _numDiscardedObjects++; return; } _numrenderedObjects++; // Prepare the quad that is going to be blitted // Calculates the position and mapping coords for that block fillVertex2d(&_vertices2d [0], static_cast<float>(pWidth), 0, (static_cast<float>(pX + pWidth) / pSu->getWidthBlock()), (1.0f - (static_cast<float>(pY + pSu->getSpareY()) / pSu->getHeightBlock()))); fillVertex2d(&_vertices2d [1], static_cast<float>(pWidth), static_cast<float>(pHeight), (static_cast<float>(pX + pWidth) / pSu->getWidthBlock()), (1.0f - (static_cast<float>(pY + pHeight + pSu->getSpareY()) / pSu->getHeightBlock()))); fillVertex2d(&_vertices2d [2], 0.0f, 0.0f, static_cast<float>(pX) / static_cast<float>(pSu->getWidthBlock()), (1.0f - (static_cast<float>(pY + pSu->getSpareY()) / pSu->getHeightBlock()))); fillVertex2d(&_vertices2d [3], 0.0f, static_cast<float>(pHeight), (static_cast<float>(pX)/ pSu->getWidthBlock()), (1.0f - (static_cast<float>(pY + pHeight + pSu->getSpareY()) / pSu->getHeightBlock()))); // Quad blitting _info._device->SetFVF(D3DFVF_CUSTOMVERTEX2D); _info._device->SetTexture(0, pSu->_surface->_texturesArray [0]._texture); _info._device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, &_vertices2d, sizeof(CUSTOMVERTEX2D)); } } } bool DirectXRender::blitWrapSurface(IND_Surface *pSu, int pWidth, int pHeight, float pUDisplace, float pVDisplace) { bool correctParams = true; if (pSu->getNumTextures() != 1) { correctParams = false; } if (correctParams) { // ----- Transform 4 vertices of the quad into world space coordinates ----- D3DXVECTOR4 mP1, mP2, mP3, mP4; Transform4Vertices(static_cast<float>(pWidth), 0.0f, static_cast<float>(pWidth), static_cast<float>(pHeight), 0.0f, 0.0f, 0.0f, static_cast<float>(pHeight), &mP1, &mP2, &mP3, &mP4); IND_Vector3 mP1_f3(mP1.x,mP1.y,mP1.z); IND_Vector3 mP2_f3(mP2.x,mP2.y,mP2.z); IND_Vector3 mP3_f3(mP3.x,mP3.y,mP3.z); IND_Vector3 mP4_f3(mP4.x,mP4.y,mP4.z); // Calculate the bounding rectangle that we are going to try to discard _math->calculateBoundingRectangle(&mP1_f3, &mP2_f3, &mP3_f3, &mP4_f3); // ---- Discard bounding rectangle using frustum culling if possible ---- if (!_math->cullFrustumBox(mP1_f3, mP2_f3,_frustrumPlanes)) { _numDiscardedObjects++; return 1; } _numrenderedObjects++; // Prepare the quad that is going to be blitted // Calculates the position and mapping coords for that block float _u = static_cast<float>(pWidth) / static_cast<float>(pSu->getWidthBlock()); float _v = static_cast<float>(pHeight) / static_cast<float>(pSu->getHeightBlock()); //Upper-right fillVertex2d(&_vertices2d [0], static_cast<float>(pWidth), 0, _u - pUDisplace, pVDisplace); //Lower-right fillVertex2d(&_vertices2d [1], static_cast<float>(pWidth), static_cast<float>(pHeight), _u - pUDisplace,-_v + pVDisplace); //Upper-left fillVertex2d(&_vertices2d [2], 0.0f,0.0f,-pUDisplace,pVDisplace); //Lower-left fillVertex2d(&_vertices2d [3], 0.0f,static_cast<float>(pHeight),-pUDisplace,-_v + pVDisplace); // Quad blitting _info._device->SetFVF(D3DFVF_CUSTOMVERTEX2D); _info._device->SetTexture(0, pSu->_surface->_texturesArray [0]._texture); _info._device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP); _info._device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP); _info._device->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, &_vertices2d, sizeof(CUSTOMVERTEX2D)); _info._device->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP); _info._device->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP); } return correctParams; } int DirectXRender::blitAnimation(IND_Animation *pAn, unsigned int pSequence, int pX, int pY, int pWidth, int pHeight, bool pToggleWrap, float pUDisplace, float pVDisplace) { bool correctParams = true; int mFinish = 1; if (pSequence < 0 || pSequence > pAn->getNumSequences() - 1) { correctParams = false; } if (correctParams) { if (!pAn->getIsActive(pSequence)) { pAn->getSequenceTimer(pSequence)->start(); pAn->setIsActive(pSequence, 1); } // Current world matrix D3DXMATRIX mMatWorld, mTrans; _info._device->GetTransform(D3DTS_WORLD, &mMatWorld); // If the time of a frame have passed, go to the next frame if (pAn->getSequenceTimer(pSequence)->getTicks() > (unsigned long) pAn->getActualFrameTime(pSequence)) { // Put timer to zero pAn->getSequenceTimer(pSequence)->start(); // Point to the next frame increasing the counter int i = pAn->getActualFramePos(pSequence); pAn->setActualFramePos(pSequence, i + 1); // If the counter is higher than the number of frames of the sequence, we put it to zero if (pAn->getActualFramePos(pSequence) > pAn->getNumFrames(pSequence) - 1) { pAn->setActualFramePos(pSequence, pAn->getNumFrames(pSequence) - 1); pAn->setIsActive(pSequence, 0); mFinish = -1; } } // ----- OffsetX y OffsetY ----- D3DXMatrixTranslation(&mTrans, static_cast<float>(pAn->getActualOffsetX(pSequence)), static_cast<float>(pAn->getActualOffsetY(pSequence)), 0); D3DXMatrixMultiply(&mMatWorld, &mMatWorld, &mTrans); _info._device->SetTransform(D3DTS_WORLD, &mMatWorld); // ----- Blitting ----- // Blits all the IND_Surface (all the blocks) if (!pX && !pY && !pWidth && !pHeight) { blitSurface(pAn->getActualSurface(pSequence)); } else { if (!pToggleWrap) { // Blits a region of the IND_Surface if (pAn->getActualSurface(pSequence)->getNumTextures() > 1) return 0; blitRegionSurface(pAn->getActualSurface(pSequence), pX, pY, pWidth, pHeight); } else {// Blits a wrapping IND_Surface if (pAn->getActualSurface(pSequence)->getNumTextures() > 1) return 0; blitWrapSurface(pAn->getActualSurface(pSequence), pWidth, pHeight, pUDisplace, pVDisplace); } } } return mFinish; } // -------------------------------------------------------------------------------- // Private methods // -------------------------------------------------------------------------------- /* ================== Fills a CUSTOMVERTEX2D structure ================== */ void DirectXRender::fillVertex2d(CUSTOMVERTEX2D *pVertex2d, float pX, float pY, float pU, float pV) { // Vertex pVertex2d->_pos._x = pX; pVertex2d->_pos._y= pY; pVertex2d->_pos._z = 0.0f; pVertex2d->_texCoord._u = pU; pVertex2d->_texCoord._v = pV; } /** @endcond */ #endif //INDIERENDER_DIRECTX
41.041899
237
0.628326
[ "transform" ]
fc7c6316830ba50cb8637d5049164d5a62374fa1
21,355
cxx
C++
pandatool/src/cvscopy/cvsSourceTree.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
pandatool/src/cvscopy/cvsSourceTree.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
pandatool/src/cvscopy/cvsSourceTree.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: cvsSourceTree.cxx // Created by: drose (31Oct00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include "cvsSourceTree.h" #include "cvsSourceDirectory.h" #include "filename.h" #include "executionEnvironment.h" #include "pnotify.h" #include "string_utils.h" #include <algorithm> #include <ctype.h> #include <stdio.h> // for perror #include <errno.h> #ifdef WIN32_VC #include <direct.h> // for chdir #endif bool CVSSourceTree::_got_start_fullpath = false; Filename CVSSourceTree::_start_fullpath; //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::Constructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// CVSSourceTree:: CVSSourceTree() { _root = (CVSSourceDirectory *)NULL; _got_root_fullpath = false; } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::Destructor // Access: Public // Description: //////////////////////////////////////////////////////////////////// CVSSourceTree:: ~CVSSourceTree() { if (_root != (CVSSourceDirectory *)NULL) { delete _root; } } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::set_root // Access: Public // Description: Sets the root of the source directory. This must be // called before scan(), and should not be called more // than once. //////////////////////////////////////////////////////////////////// void CVSSourceTree:: set_root(const Filename &root_path) { nassertv(_path.empty()); _path = root_path; } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::scan // Access: Public // Description: Scans the complete source directory starting at the // indicated pathname. It is an error to call this more // than once. Returns true on success, false if there // is an error. //////////////////////////////////////////////////////////////////// bool CVSSourceTree:: scan(const Filename &key_filename) { nassertr(_root == (CVSSourceDirectory *)NULL, false); Filename root_fullpath = get_root_fullpath(); _root = new CVSSourceDirectory(this, NULL, root_fullpath.get_basename()); return _root->scan(_path, key_filename); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::get_root // Access: Public // Description: Returns the root directory of the hierarchy. //////////////////////////////////////////////////////////////////// CVSSourceDirectory *CVSSourceTree:: get_root() const { return _root; } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::find_directory // Access: Public // Description: Returns the source directory that corresponds to the // given path, or NULL if there is no such directory in // the source tree. //////////////////////////////////////////////////////////////////// CVSSourceDirectory *CVSSourceTree:: find_directory(const Filename &path) { string root_fullpath = get_root_fullpath(); string fullpath = get_actual_fullpath(path); // path is a subdirectory within the source hierarchy if and only if // root_fullpath is an initial prefix of fullpath. if (root_fullpath.length() > fullpath.length() || cmp_nocase(fullpath.substr(0, root_fullpath.length()), root_fullpath) != 0) { // Nope! return (CVSSourceDirectory *)NULL; } // The relative name is the part of fullpath not in root_fullpath. Filename relpath = fullpath.substr(root_fullpath.length()); return _root->find_relpath(relpath); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::find_relpath // Access: Public // Description: Returns the source directory that corresponds to the // given relative path from the root, or NULL if there // is no match. The relative path may or may not // include the name of the root directory itself. //////////////////////////////////////////////////////////////////// CVSSourceDirectory *CVSSourceTree:: find_relpath(const string &relpath) { CVSSourceDirectory *result = _root->find_relpath(relpath); if (result != (CVSSourceDirectory *)NULL) { return result; } // Check for the root dirname at the front of the path, and remove // it if it's there. size_t slash = relpath.find('/'); Filename first = relpath.substr(0, slash); Filename rest; if (slash != string::npos) { rest = relpath.substr(slash + 1); } if (cmp_nocase(first, _root->get_dirname()) == 0) { return _root->find_relpath(rest); } return (CVSSourceDirectory *)NULL; } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::find_dirname // Access: Public // Description: Returns the source directory that corresponds to the // given local directory name, or NULL if there // is no match. //////////////////////////////////////////////////////////////////// CVSSourceDirectory *CVSSourceTree:: find_dirname(const string &dirname) { return _root->find_dirname(dirname); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::choose_directory // Access: Public // Description: Determines where an externally referenced model file // of the indicated name should go. It does this by // looking for an existing model file of the same name; // if a matching model is not found, or if multiple // matching files are found, prompts the user for the // directory, or uses suggested_dir. //////////////////////////////////////////////////////////////////// CVSSourceTree::FilePath CVSSourceTree:: choose_directory(const string &basename, CVSSourceDirectory *suggested_dir, bool force, bool interactive) { static FilePaths empty_paths; Basenames::const_iterator bi; bi = _basenames.find(downcase(basename)); if (bi != _basenames.end()) { // The filename already exists somewhere. const FilePaths &paths = (*bi).second; return prompt_user(basename, suggested_dir, paths, force, interactive); } // Now we have to prompt the user for a suitable place to put it. return prompt_user(basename, suggested_dir, empty_paths, force, interactive); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::get_root_fullpath // Access: Public // Description: Returns the full path from the root to the top of // the source hierarchy. //////////////////////////////////////////////////////////////////// Filename CVSSourceTree:: get_root_fullpath() { nassertr(!_path.empty(), Filename()); if (!_got_root_fullpath) { _root_fullpath = get_actual_fullpath(_path); _got_root_fullpath = true; } return _root_fullpath; } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::get_root_dirname // Access: Public // Description: Returns the local directory name of the root of the // tree. //////////////////////////////////////////////////////////////////// Filename CVSSourceTree:: get_root_dirname() const { nassertr(_root != (CVSSourceDirectory *)NULL, Filename()); return _root->get_dirname(); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::add_file // Access: Public // Description: Adds a new file to the set of known files. This is // normally called from CVSSourceDirectory::scan() and // should not be called directly by the user. //////////////////////////////////////////////////////////////////// void CVSSourceTree:: add_file(const string &basename, CVSSourceDirectory *dir) { FilePath file_path(dir, basename); _basenames[downcase(basename)].push_back(file_path); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::temp_chdir // Access: Public, Static // Description: Temporarily changes the current directory to the // named path. Returns true on success, false on // failure. Call restore_cwd() to restore to the // original directory later. //////////////////////////////////////////////////////////////////// bool CVSSourceTree:: temp_chdir(const Filename &path) { // We have to call this first to guarantee that we have already // determined our starting directory. get_start_fullpath(); string os_path = path.to_os_specific(); if (chdir(os_path.c_str()) < 0) { return false; } return true; } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::restore_cwd // Access: Public, Static // Description: Restores the current directory after changing it from // temp_chdir(). //////////////////////////////////////////////////////////////////// void CVSSourceTree:: restore_cwd() { Filename start_fullpath = get_start_fullpath(); string os_path = start_fullpath.to_os_specific(); if (chdir(os_path.c_str()) < 0) { // Hey! We can't get back to the directory we started from! perror(os_path.c_str()); nout << "Can't continue, aborting.\n"; exit(1); } } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::prompt_user // Access: Private // Description: Prompts the user, if necessary, to choose a directory // to import the given file into. //////////////////////////////////////////////////////////////////// CVSSourceTree::FilePath CVSSourceTree:: prompt_user(const string &basename, CVSSourceDirectory *suggested_dir, const CVSSourceTree::FilePaths &paths, bool force, bool interactive) { if (paths.size() == 1) { // The file already exists in exactly one place. if (!interactive) { return paths[0]; } FilePath result = ask_existing(basename, paths[0]); if (result.is_valid()) { return result; } } else if (paths.size() > 1) { // The file already exists in multiple places. if (force && !interactive) { return paths[0]; } FilePath result = ask_existing(basename, paths, suggested_dir); if (result.is_valid()) { return result; } } // The file does not already exist, or the user declined to replace // an existing file. if (force && !interactive) { return FilePath(suggested_dir, basename); } // Is the file already in the suggested directory? If not, prompt // the user to put it there. bool found_dir = false; FilePaths::const_iterator pi; for (pi = paths.begin(); pi != paths.end(); ++pi) { if ((*pi)._dir == suggested_dir) { found_dir = true; break; } } if (!found_dir) { FilePath result = ask_new(basename, suggested_dir); if (result.is_valid()) { return result; } } // Ask the user where the damn thing should go. return ask_any(basename, paths); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::ask_existing // Access: Private // Description: Asks the user if he wants to replace an existing // file. //////////////////////////////////////////////////////////////////// CVSSourceTree::FilePath CVSSourceTree:: ask_existing(const string &basename, const CVSSourceTree::FilePath &path) { while (true) { nout << basename << " found in tree at " << path.get_path() << ".\n"; string result = prompt("Overwrite this file (y/n)? "); nassertr(!result.empty(), FilePath()); if (result.size() == 1) { if (tolower(result[0]) == 'y') { return path; } else if (tolower(result[0]) == 'n') { return FilePath(); } } nout << "*** Invalid response: " << result << "\n\n"; } } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::ask_existing // Access: Private // Description: Asks the user which of several existing files he // wants to replace. //////////////////////////////////////////////////////////////////// CVSSourceTree::FilePath CVSSourceTree:: ask_existing(const string &basename, const CVSSourceTree::FilePaths &paths, CVSSourceDirectory *suggested_dir) { while (true) { nout << basename << " found in tree at more than one place:\n"; bool any_suggested = false; for (int i = 0; i < (int)paths.size(); i++) { nout << " " << (i + 1) << ". " << paths[i].get_path() << "\n"; if (paths[i]._dir == suggested_dir) { any_suggested = true; } } int next_option = paths.size() + 1; int suggested_option = -1; if (!any_suggested) { // If it wasn't already in the suggested directory, offer to put // it there. suggested_option = next_option; next_option++; nout << "\n" << suggested_option << ". create " << Filename(suggested_dir->get_path(), basename) << "\n"; } int other_option = next_option; nout << other_option << ". Other\n"; string result = prompt("Choose an option: "); nassertr(!result.empty(), FilePath()); const char *nptr = result.c_str(); char *endptr; int option = strtol(nptr, &endptr, 10); if (*endptr == '\0') { if (option >= 1 && option <= (int)paths.size()) { return paths[option - 1]; } else if (option == suggested_option) { return FilePath(suggested_dir, basename); } else if (option == other_option) { return FilePath(); } } nout << "*** Invalid response: " << result << "\n\n"; } } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::ask_new // Access: Private // Description: Asks the user if he wants to create a new file. //////////////////////////////////////////////////////////////////// CVSSourceTree::FilePath CVSSourceTree:: ask_new(const string &basename, CVSSourceDirectory *dir) { while (true) { nout << basename << " will be created in " << dir->get_path() << ".\n"; string result = prompt("Create this file (y/n)? "); nassertr(!result.empty(), FilePath()); if (result.size() == 1) { if (tolower(result[0]) == 'y') { return FilePath(dir, basename); } else if (tolower(result[0]) == 'n') { return FilePath(); } } nout << "*** Invalid response: " << result << "\n\n"; } } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::ask_any // Access: Private // Description: Asks the user to type in the name of the directory in // which to store the file. //////////////////////////////////////////////////////////////////// CVSSourceTree::FilePath CVSSourceTree:: ask_any(const string &basename, const CVSSourceTree::FilePaths &paths) { while (true) { string result = prompt("Enter the name of the directory to copy " + basename + " to: "); nassertr(!result.empty(), FilePath()); // The user might enter a fully-qualified path to the directory, // or a relative path from the root (with or without the root's // dirname), or the dirname of the particular directory. CVSSourceDirectory *dir = find_directory(result); if (dir == (CVSSourceDirectory *)NULL) { dir = find_relpath(result); } if (dir == (CVSSourceDirectory *)NULL) { dir = find_dirname(result); } if (dir != (CVSSourceDirectory *)NULL) { // If the file is already in this directory, we must preserve // its existing case. FilePaths::const_iterator pi; for (pi = paths.begin(); pi != paths.end(); ++pi) { if ((*pi)._dir == dir) { return (*pi); } } // Otherwise, since we're creating a new file, keep the original // case. return FilePath(dir, basename); } nout << "*** Not a valid directory name: " << result << "\n\n"; } } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::prompt // Access: Private // Description: Issues a prompt to the user and waits for a typed // response. Returns the response (which will not be // empty). //////////////////////////////////////////////////////////////////// string CVSSourceTree:: prompt(const string &message) { nout << flush; while (true) { cerr << message << flush; string response; getline(cin, response); // Remove leading and trailing whitespace. size_t p = 0; while (p < response.length() && isspace(response[p])) { p++; } size_t q = response.length(); while (q > p && isspace(response[q - 1])) { q--; } if (q > p) { return response.substr(p, q - p); } } } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::get_actual_fullpath // Access: Private, Static // Description: Determines the actual full path from the root to the // named directory. //////////////////////////////////////////////////////////////////// Filename CVSSourceTree:: get_actual_fullpath(const Filename &path) { Filename canon = path; canon.make_canonical(); return canon; } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::get_start_fullpath // Access: Private, Static // Description: Returns the full path from the root to the directory // in which the user started the program. //////////////////////////////////////////////////////////////////// Filename CVSSourceTree:: get_start_fullpath() { if (!_got_start_fullpath) { Filename cwd = ExecutionEnvironment::get_cwd(); _start_fullpath = cwd.to_os_specific(); } return _start_fullpath; } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::FilePath::Constructor // Access: Public // Description: Creates an invalid FilePath specification. //////////////////////////////////////////////////////////////////// CVSSourceTree::FilePath:: FilePath() : _dir(NULL) { } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::FilePath::Constructor // Access: Public // Description: Creates a valid FilePath specification with the // indicated directory and basename. //////////////////////////////////////////////////////////////////// CVSSourceTree::FilePath:: FilePath(CVSSourceDirectory *dir, const string &basename) : _dir(dir), _basename(basename) { } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::FilePath::is_valid // Access: Public // Description: Returns true if this FilePath represents a valid // file, or false if it represents an error return. //////////////////////////////////////////////////////////////////// bool CVSSourceTree::FilePath:: is_valid() const { return (_dir != (CVSSourceDirectory *)NULL); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::FilePath::get_path // Access: Public // Description: Returns the relative path to this file from the root // of the source tree. //////////////////////////////////////////////////////////////////// Filename CVSSourceTree::FilePath:: get_path() const { nassertr(_dir != (CVSSourceDirectory *)NULL, Filename()); return Filename(_dir->get_path(), _basename); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::FilePath::get_fullpath // Access: Public // Description: Returns the full path to this file. //////////////////////////////////////////////////////////////////// Filename CVSSourceTree::FilePath:: get_fullpath() const { nassertr(_dir != (CVSSourceDirectory *)NULL, Filename()); return Filename(_dir->get_fullpath(), _basename); } //////////////////////////////////////////////////////////////////// // Function: CVSSourceTree::FilePath::get_rel_from // Access: Public // Description: Returns the relative path to this file as seen from // the indicated source directory. //////////////////////////////////////////////////////////////////// Filename CVSSourceTree::FilePath:: get_rel_from(const CVSSourceDirectory *other) const { nassertr(_dir != (CVSSourceDirectory *)NULL, Filename()); return Filename(other->get_rel_to(_dir), _basename); }
34.388084
83
0.526481
[ "model", "3d" ]