hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
40a38fd9b67fbcb9b21519ae4fa5f0b301d1a0df
12,173
cc
C++
libs/daemon/shell.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
libs/daemon/shell.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
libs/daemon/shell.cc
sandtreader/obtools
2382e2d90bb62c9665433d6d01bbd31b8ad66641
[ "MIT" ]
null
null
null
//========================================================================== // ObTools::Daemon: shell.cc // // Implementation of daemon shell // // Copyright (c) 2009 Paul Clark. All rights reserved // This code comes with NO WARRANTY and is subject to licence agreement //========================================================================== #include "ot-daemon.h" #include "ot-log.h" #include "ot-misc.h" #include "ot-init.h" #include "ot-file.h" #include <errno.h> #include <signal.h> #include <sys/types.h> #include <fstream> #if !defined(PLATFORM_WINDOWS) #include <execinfo.h> #include <sys/wait.h> #include <unistd.h> #else #include <dbghelp.h> typedef __p_sig_fn_t sighandler_t; #endif #define DEFAULT_TIMESTAMP "%a %d %b %H:%M:%*S [%*L]: " #define DEFAULT_HOLD_TIME "1 min" #define FIRST_WATCHDOG_SLEEP_TIME 1 #define MAX_WATCHDOG_SLEEP_TIME 60 namespace ObTools { namespace Daemon { //-------------------------------------------------------------------------- // Signal handlers for both processes static Shell *the_shell = 0; const sighandler_t sig_ign(SIG_IGN); const sighandler_t sig_dfl(SIG_DFL); // Clean shutdown signals void sigshutdown(int) { if (the_shell) the_shell->signal_shutdown(); signal(SIGTERM, sig_ign); signal(SIGINT, sig_ign); #if !defined(PLATFORM_WINDOWS) signal(SIGQUIT, sig_ign); #endif } #if !defined(PLATFORM_WINDOWS) // SIGHUP: Reload config void sighup(int) { if (the_shell) the_shell->signal_reload(); signal(SIGHUP, sighup); } #endif // Various bad things! void sigevil(int sig) { if (the_shell) the_shell->log_evil(sig); signal(sig, sig_dfl); raise(sig); } //-------------------------------------------------------------------------- // Main run function // Delegate entirely to the application int Shell::run() { int result = application.pre_run(); if (result) return result; while (!shut_down) { result = application.tick(); if (result) return result; int wait = application.tick_wait(); if (wait) this_thread::sleep_for(chrono::microseconds{wait}); if (trigger_shutdown) { shutdown(); } else if (trigger_reload) { reload(); trigger_reload = false; } } return 0; } //-------------------------------------------------------------------------- // Start process, with arguments // Returns process exit code int Shell::start(int argc, char **argv) { // Run initialisation sequence (auto-registration of modules etc.) Init::Sequence::run(); // Grab config filename if specified string cf = default_config_file; if (argc > 1) cf = argv[argc-1]; // Last arg, leaves room for options // Read config config.add_file(cf); if (!config.read(config_element)) { cerr << argv[0] << ": Can't read config file " << cf << endl; return 2; } // Process <include> in config config.process_includes(); #if defined(DEBUG) bool go_daemon = config.get_value_bool("background/@daemon", false); #else bool go_daemon = config.get_value_bool("background/@daemon", true); #endif // Create log stream if daemon auto chan_out = static_cast<Log::Channel *>(nullptr); if (go_daemon) { #if !defined(PLATFORM_WINDOWS) if (config.get_value_bool("log/@syslog")) { chan_out = new Log::SyslogChannel; } else { #endif const auto log_conf = File::Path{config.get_value("log/@file", default_log_file)}; const auto log_exp = log_conf.expand(); const auto logfile = File::Path{cf}.resolve(log_exp); const auto log_dir = logfile.dir(); if (!log_dir.ensure(true)) { cerr << argv[0] << ": Logfile directory can not be created: " << log_dir << endl; return 2; } auto sout = new ofstream(logfile.c_str(), ios::app); if (!*sout) { cerr << argv[0] << ": Unable to open logfile " << logfile << endl; return 2; } chan_out = new Log::OwnedStreamChannel{sout}; #if !defined(PLATFORM_WINDOWS) } #endif } else { chan_out = new Log::StreamChannel{&cout}; } auto log_level = config.get_value_int("log/@level", static_cast<int>(Log::Level::summary)); auto level_out = static_cast<Log::Level>(log_level); auto time_format = config.get_value("log/@timestamp", DEFAULT_TIMESTAMP); auto hold_time = config.get_value("log/@hold-time", DEFAULT_HOLD_TIME); Log::logger.connect_full(chan_out, level_out, time_format, hold_time); Log::Streams log; log.summary << name << " version " << version << " starting\n"; // Tell application to read config settings application.read_config(config, cf); // Call preconfigure before we go daemon - e.g. asking for SSL passphrase int rc = application.preconfigure(); if (rc) { log.error << "Preconfigure failed: " << rc << endl; return rc; } #if !defined(PLATFORM_WINDOWS) // Full background daemon if (go_daemon) { if (daemon(0, 0)) log.error << "Can't become daemon: " << strerror(errno) << endl; // Create pid file string pid_file = config.get_value("daemon/pid/@file", default_pid_file); ofstream pidfile(pid_file.c_str()); pidfile << getpid() << endl; pidfile.close(); } #endif // Register signal handlers - same for both master and slave the_shell = this; signal(SIGTERM, sigshutdown); signal(SIGINT, sigshutdown); // quit from Ctrl-C #if !defined(PLATFORM_WINDOWS) signal(SIGQUIT, sigshutdown); // quit from Ctrl-backslash signal(SIGHUP, sighup); // Ignore SIGPIPE from closed sockets etc. signal(SIGPIPE, sig_ign); #endif signal(SIGSEGV, sigevil); signal(SIGILL, sigevil); signal(SIGFPE, sigevil); signal(SIGABRT, sigevil); #if !defined(PLATFORM_WINDOWS) // Watchdog? Master/slave processes... bool enable_watchdog = config.get_value_bool("watchdog/@restart", true); int sleep_time = FIRST_WATCHDOG_SLEEP_TIME; if (go_daemon && enable_watchdog) { // Now loop forever restarting a child process, in case it fails bool first = true; while (!shut_down) { if (!first) { log.detail << "Waiting for " << sleep_time << "s\n"; this_thread::sleep_for(chrono::seconds(sleep_time)); // Exponential backoff, up to a max sleep_time *= 2; if (sleep_time > MAX_WATCHDOG_SLEEP_TIME) sleep_time = MAX_WATCHDOG_SLEEP_TIME; log.error << "*** RESTARTING SLAVE ***\n"; } first = false; log.summary << "Forking slave process\n"; slave_pid = fork(); if (slave_pid < 0) { log.error << "Can't fork slave process: " << strerror(errno) << endl; continue; } if (slave_pid) { // PARENT PROCESS log.detail << "Slave process pid " << slave_pid << " forked\n"; // Wait for it to exit int status; int died = waitpid(slave_pid, &status, 0); // Check for fatal failure if (died && !WIFEXITED(status)) { log.error << "*** Slave process " << slave_pid << " died ***\n"; } else { int rc = WEXITSTATUS(status); if (rc) { log.error << "*** Slave process " << slave_pid << " exited with code " << rc << " ***\n"; } else { log.summary << "Slave process exited OK\n"; // Expected shut_down = true; } } // However it exited, if shutdown is requested, stop if (trigger_shutdown) shut_down = true; } else { // SLAVE PROCESS // Run subclass prerun before dropping privileges int rc = application.run_priv(); if (rc) return rc; rc = drop_privileges(); if (rc) return rc; // Run subclass full startup rc = run(); application.cleanup(); return rc; } } log.summary << "Master process exiting\n"; return 0; } else { #endif // Just run directly rc = application.run_priv(); if (rc) return rc; #if !defined(PLATFORM_WINDOWS) rc = drop_privileges(); if (rc) return rc; #endif rc = run(); application.cleanup(); return rc; #if !defined(PLATFORM_WINDOWS) } #endif } //-------------------------------------------------------------------------- // Drop privileges if required // Returns 0 on success, rc if not int Shell::drop_privileges() { #if defined(PLATFORM_WINDOWS) return -99; #else // Drop privileges if root if (!getuid()) { Log::Streams log; string username = config["security/@user"]; string groupname = config["security/@group"]; // Set group first - needs to still be root if (!groupname.empty()) { int gid = File::Path::group_name_to_id(groupname); if (gid >= 0) { log.summary << "Changing to group " << groupname << " (" << gid << ")\n"; if (setgid(static_cast<gid_t>(gid))) { log.error << "Can't change group: " << strerror(errno) << endl; return 2; } } else { log.error << "Can't find group " << groupname << "\n"; return 2; } } if (!username.empty()) { int uid = File::Path::user_name_to_id(username); if (uid >= 0) { log.summary << "Changing to user " << username << " (" << uid << ")\n"; if (setuid(static_cast<uid_t>(uid))) { log.error << "Can't change user: " << strerror(errno) << endl; return 2; } } else { log.error << "Can't find user " << username << "\n"; return 2; } } } return 0; #endif } //-------------------------------------------------------------------------- // Shut down - indirectly called from SIGTERM handler void Shell::shutdown() { // Stop our restart loop (master) and any loop in the slave shut_down=true; } //-------------------------------------------------------------------------- // Reload config - indirectly called from SIGHUP handler void Shell::reload() { Log::Streams log; log.summary << "SIGHUP received\n"; if (config.read(config_element)) application.read_config(config); else log.error << "Failed to re-read config, using existing" << endl; application.reconfigure(); } //-------------------------------------------------------------------------- // Handle a failure signal void Shell::log_evil(int sig) { string what; switch (sig) { case SIGSEGV: what = "segment violation"; break; case SIGILL: what = "illegal instruction"; break; case SIGFPE: what = "floating point exception"; break; case SIGABRT: what = "aborted"; break; default: what = "unknown"; } Log::Streams log; log.error << "*** Signal received in " << (slave_pid?"master":"slave") << ": " << what << " (" << sig << ") ***\n"; // Do a backtrace #define MAXTRACE 100 #define MAXNAMELEN 1024 void *buffer[MAXTRACE]; #if defined(PLATFORM_WINDOWS) const auto frames = CaptureStackBackTrace(1, MAXTRACE, buffer, nullptr); if (frames) { log.error << "--- backtrace:\n"; for (auto i = 0; i < frames; ++i) { auto sumbuff = vector<uint64_t>(sizeof(SYMBOL_INFO) + MAXNAMELEN + sizeof(uint64_t) - 1); auto *info = reinterpret_cast<SYMBOL_INFO *>(&sumbuff[0]); info->SizeOfStruct = sizeof(SYMBOL_INFO); info->MaxNameLen = 1024; auto displacement = uint64_t{}; if (SymFromAddr(GetCurrentProcess(), (DWORD64)buffer[i], &displacement, info)) { log.error << "- " << string(info->Name, info->NameLen) << endl; } } log.error << "---\n"; } #else int n = backtrace(buffer, MAXTRACE); char **strings = backtrace_symbols(buffer, n); if (strings) { log.error << "--- backtrace:\n"; for(int i=0; i<n; i++) log.error << "- " << strings[i] << endl; log.error << "---\n"; free(strings); } #endif } }} // namespaces
25.955224
79
0.563707
sandtreader
40a721506ac9c6339abc64023a3026b1dd0e4d18
24,194
cpp
C++
trunk/src/app/srs_app_forward_rtsp.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
trunk/src/app/srs_app_forward_rtsp.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
trunk/src/app/srs_app_forward_rtsp.cpp
breezeewu/media-server
b7f6e7c24a1c849180ba31088250c0174b1112e0
[ "MIT" ]
null
null
null
/**************************************************************************************************************** * filename srs_app_forward_rtsp.cpp * describe Sunvalley forward rtsp classs define * author Created by dawson on 2019/04/25 * Copyright ©2007 - 2029 Sunvally. All Rights Reserved. ***************************************************************************************************************/ #include <srs_app_forward_rtsp.hpp> #include <srs_app_source.hpp> #include <srs_rtmp_stack.hpp> #include <srs_rtmp_msg_array.hpp> #include <srs_kernel_flv.hpp> #include <srs_kernel_ts.hpp> #include <sys/stat.h> ForwardRtspQueue::ForwardRtspQueue() { //srs_trace("ForwardRtspQueue begin"); m_nmax_queue_size = 1000; m_pavccodec = new SrsAvcAacCodec(); LB_ADD_MEM(m_pavccodec, sizeof(SrsAvcAacCodec)); m_pavcsample = new SrsCodecSample(); LB_ADD_MEM(m_pavcsample, sizeof(SrsCodecSample)); m_paaccodec = new SrsAvcAacCodec(); LB_ADD_MEM(m_paaccodec, sizeof(SrsAvcAacCodec)); m_paacsample = new SrsCodecSample(); LB_ADD_MEM(m_paacsample, sizeof(SrsCodecSample)); m_bwait_keyframe = true; m_bsend_avc_seq_hdr = false; m_bsend_aac_seq_hdr = false; //srs_trace("ForwardRtspQueue end"); } ForwardRtspQueue::~ForwardRtspQueue() { //srs_trace("~ForwardRtspQueue begin"); srs_freep(m_pavccodec); srs_freep(m_pavcsample); srs_freep(m_paaccodec); srs_freep(m_paacsample); /*if(m_pavccodec) { delete m_pavccodec; m_pavccodec = NULL; } if(m_pavcsample) { delete m_pavcsample; m_pavcsample = NULL; } if(m_paaccodec) { delete m_paaccodec; m_paaccodec = NULL; } if(m_paacsample) { delete m_paacsample; m_paacsample = NULL; }*/ //srs_trace("~ForwardRtspQueue end"); } int ForwardRtspQueue::enqueue(SrsSharedPtrMessage* pmsg) { int ret; if(NULL == pmsg) { srs_trace("Invalid pmsg ptr %p", pmsg); m_bwait_keyframe = true; return -1; } if((int)m_vFwdMsgList.size() >= m_nmax_queue_size) { srs_trace("Forward rtsp queue is full, list size %d < max queue size %d", (int)m_vFwdMsgList.size(), m_nmax_queue_size); return -1; } if(pmsg->is_video()) { ret = m_pavccodec->video_avc_demux(pmsg->payload, pmsg->size, m_pavcsample); //srs_trace("avc enqueue(payload:%p, size:%d, pmsg->pts:%"PRId64"), m_pavcsample->frame_type:%d, m_bwait_keyframe:%d\n", pmsg->payload, pmsg->size, pmsg->timestamp, m_pavcsample->frame_type, (int)m_bwait_keyframe); if(ERROR_SUCCESS != ret) { srs_error("ret:%d = m_pavccodec->video_avc_demux(pmsg->payload:%p, pmsg->size:%d, m_pavcsample:%p) failed", ret, pmsg->payload, pmsg->size, m_pavcsample); srs_err_memory(pmsg->payload, 32); return ret; } /*if(m_pavcsample->nb_sample_units <= 0) { return 0; }*/ if(SrsCodecVideoAVCTypeSequenceHeader == m_pavcsample->avc_packet_type) { /*srs_rtsp_debug("avc sequence header, m_pavcsample->nb_sample_units:%d:\n", m_pavcsample->nb_sample_units); for(int i = 0; i < m_pavcsample->nb_sample_units; i++) { srs_trace_memory(m_pavcsample->sample_units[i].bytes, m_pavcsample->sample_units[i].size); }*/ } else if(m_bwait_keyframe && m_pavcsample->frame_type != SrsCodecVideoAVCFrameKeyFrame) { //srs_trace("wait for keyframe, not keyframe, drop video\n"); m_pavcsample->clear(); return 0; } else { if(m_bwait_keyframe) { srs_trace("key frame come, pts:%"PRId64", m_pavcsample.nb_sample_units:%d", pmsg->timestamp, m_pavcsample->nb_sample_units); m_bwait_keyframe = false; } /*if(SrsCodecVideoAVCFrameKeyFrame == m_pavcsample->frame_type) { m_pavcsample->add_prefix_sample_uint(m_pavccodec->pictureParameterSetNALUnit, m_pavccodec->pictureParameterSetLength); m_pavcsample->add_prefix_sample_uint(m_pavccodec->sequenceParameterSetNALUnit, m_pavccodec->sequenceParameterSetLength); }*/ ret = enqueue_avc(m_pavccodec, m_pavcsample, pmsg->timestamp); } m_pavcsample->clear(); } else { ret = m_paaccodec->audio_aac_demux(pmsg->payload, pmsg->size, m_paacsample); if(ERROR_SUCCESS != ret) { srs_error("ret:%d = m_paaccodec->audio_aac_demux(pmsg->payload:%p, pmsg->size:%d, m_paacsample:%p) failed", ret, pmsg->payload, pmsg->size, m_paacsample); srs_err_memory(pmsg->payload, 32); return ret; } if(m_bwait_keyframe) { //srs_trace("wait for keyframe, not keyframe, drop audio\n"); m_paacsample->clear(); return 0; } /*if(m_pavcsample->nb_sample_units <= 0) { return 0; } if(!m_bsend_aac_seq_hdr) { m_bsend_aac_seq_hdr = true; m_pavcsample->add_prefix_sample_uint(m_paaccodec->aac_extra_data, m_pavccodec->aac_extra_size); }*/ if(SrsCodecAudioTypeSequenceHeader == m_paacsample->aac_packet_type) { //srs_rtsp_debug("aac sequence header, m_pavcsample->nb_sample_units:%d\n", m_paacsample->nb_sample_units); for(int i = 0; i < m_paacsample->nb_sample_units; i++) { srs_trace_memory(m_paacsample->sample_units[i].bytes, m_paacsample->sample_units[i].size); } } else { //srs_trace("aac enqueue(payload:%p, size:%d, pmsg->pts:%"PRId64")\n", pmsg->payload, pmsg->size, pmsg->timestamp); ret = enqueue_aac(m_paaccodec, m_paacsample, pmsg->timestamp); } m_paacsample->clear(); } //srs_trace("enqueue end, ret:%d", ret); return ret; } int ForwardRtspQueue::enqueue_avc(SrsAvcAacCodec* codec, SrsCodecSample* sample, int64_t pts) { int ret = ERROR_SUCCESS; int pt = SRS_RTSP_AVC_PAYLOAD_TYPE; // Whether aud inserted. //bool aud_inserted = false; static u_int8_t fresh_nalu_header[] = { 0x00, 0x00, 0x00, 0x01 }; //srs_trace("codec:%p, sample:%p, pts:"PRId64"", codec, sample, pts); if(SrsCodecVideoHEVC == codec->video_codec_id) { pt = SRS_RTSP_HEVC_PAYLOAD_TYPE; } // Insert a default AUD NALU when no AUD in samples. if (!sample->has_aud) { // the aud(access unit delimiter) before each frame. // 7.3.2.4 Access unit delimiter RBSP syntax // H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 66. // // primary_pic_type u(3), the first 3bits, primary_pic_type indicates that the slice_type values // for all slices of the primary coded picture are members of the set listed in Table 7-5 for // the given value of primary_pic_type. // 0, slice_type 2, 7 // 1, slice_type 0, 2, 5, 7 // 2, slice_type 0, 1, 2, 5, 6, 7 // 3, slice_type 4, 9 // 4, slice_type 3, 4, 8, 9 // 5, slice_type 2, 4, 7, 9 // 6, slice_type 0, 2, 3, 4, 5, 7, 8, 9 // 7, slice_type 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 // 7.4.2.4 Access unit delimiter RBSP semantics // H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 102. // // slice_type specifies the coding type of the slice according to Table 7-6. // 0, P (P slice) // 1, B (B slice) // 2, I (I slice) // 3, SP (SP slice) // 4, SI (SI slice) // 5, P (P slice) // 6, B (B slice) // 7, I (I slice) // 8, SP (SP slice) // 9, SI (SI slice) // H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 105. /*static u_int8_t default_aud_nalu[] = { 0x09, 0xf0}; pfwdmsg->payload->append((const char*)fresh_nalu_header, sizeof(fresh_nalu_header)); pfwdmsg->payload->append((const char*)default_aud_nalu, 2);*/ } bool is_sps_pps_appended = false; // all sample use cont nalu header, except the sps-pps before IDR frame. for (int i = 0; i < sample->nb_sample_units; i++) { SrsCodecSampleUnit* sample_unit = &sample->sample_units[i]; int32_t size = sample_unit->size; //srs_trace("sample_unit:%p, size:%d", sample_unit, size); if (!sample_unit->bytes || size <= 0) { ret = ERROR_HLS_AVC_SAMPLE_SIZE; srs_error("invalid avc sample length=%d, ret=%d", size, ret); //delete pfwdmsg; return ret; } ForwardRtspSample* pfwdmsg = new ForwardRtspSample(); LB_ADD_MEM(pfwdmsg, sizeof(ForwardRtspSample)); pfwdmsg->payloadtype = pt; // 5bits, 7.3.1 NAL unit syntax, // H.264-AVC-ISO_IEC_14496-10-2012.pdf, page 83. SrsAvcNaluType nal_unit_type = (SrsAvcNaluType)(sample_unit->bytes[0] & 0x1f); //srs_rtsp_debug("nal_unit_type:%d, sample_unit->size:%d", nal_unit_type, sample_unit->size); if(9 == nal_unit_type || 10 == nal_unit_type) { srs_freep(pfwdmsg); continue; } // Insert sps/pps before IDR when there is no sps/pps in samples. // The sps/pps is parsed from sequence header(generally the first flv packet). if (nal_unit_type == SrsAvcNaluTypeIDR && !sample->has_sps_pps && !is_sps_pps_appended) { if (codec->sequenceParameterSetLength > 0) { //srs_avc_insert_aud(pfwdmsg->payload, aud_inserted); /*pfwdmsg->payload->append((const char*)fresh_nalu_header, sizeof(fresh_nalu_header)); pfwdmsg->payload->append(codec->sequenceParameterSetNALUnit, codec->sequenceParameterSetLength); srs_trace("codec->sequenceParameterSetNALUnit:%p, codec->sequenceParameterSetLength:%d\n", codec->sequenceParameterSetNALUnit, codec->sequenceParameterSetLength); srs_trace_memory(codec->sequenceParameterSetNALUnit, codec->sequenceParameterSetLength > 48 ? 48 : codec->sequenceParameterSetLength);*/ } if (codec->pictureParameterSetLength > 0) { //srs_avc_insert_aud(pfwdmsg->payload, aud_inserted); /*pfwdmsg->payload->append((const char*)fresh_nalu_header, sizeof(fresh_nalu_header)); pfwdmsg->payload->append(codec->pictureParameterSetNALUnit, codec->pictureParameterSetLength); srs_trace("codec->pictureParameterSetNALUnit:%p, codec->sequenceParameterSetLength:%d\n", codec->pictureParameterSetNALUnit, codec->sequenceParameterSetLength); srs_trace_memory(codec->pictureParameterSetNALUnit, codec->pictureParameterSetLength > 48 ? 48 : codec->pictureParameterSetLength);*/ } is_sps_pps_appended = true; // Insert the NALU to video in annexb. } pfwdmsg->payload->append((const char*)fresh_nalu_header, sizeof(fresh_nalu_header)); //srs_avc_insert_aud(pfwdmsg->payload, aud_inserted); pfwdmsg->payload->append(sample_unit->bytes, sample_unit->size); pfwdmsg->pts = pts; pfwdmsg->dts = pts; pfwdmsg->mediatype = 0; m_vFwdMsgList.push(pfwdmsg); //srs_rtsp_debug("pfwdmsg:%p, length:%d, pt:%d, list size:%ld, pts:%"PRId64"\n", pfwdmsg, pfwdmsg->payload->length(), pfwdmsg->payloadtype, m_vFwdMsgList.size(), pfwdmsg->pts); } //srs_trace("pfwdmsg:%p, length:%d, pt:%d, list size:%ld, pts:%"PRId64"\n", pfwdmsg, pfwdmsg->payload->length(), pfwdmsg->payloadtype, m_vFwdMsgList.size(), pfwdmsg->pts); return ret; } int ForwardRtspQueue::enqueue_aac(SrsAvcAacCodec* codec, SrsCodecSample* sample, int64_t pts) { int ret = ERROR_SUCCESS; ForwardRtspSample* pfwdmsg = new ForwardRtspSample(); LB_ADD_MEM(pfwdmsg, sizeof(ForwardRtspSample)); pfwdmsg->payloadtype = SRS_RTSP_AAC_PAYLOAD_TYPE; //srs_trace("(codec:%p, sample:%p) begin", codec, sample); for (int i = 0; i < sample->nb_sample_units; i++) { SrsCodecSampleUnit* sample_unit = &sample->sample_units[i]; int32_t size = sample_unit->size; if (!sample_unit->bytes || size <= 0 || size > 0x1fff) { ret = ERROR_HLS_AAC_FRAME_LENGTH; srs_error("invalid aac frame length=%d, ret=%d, pt:%d, audio_codec_id:%d", size, ret, pfwdmsg->payloadtype, codec->audio_codec_id); //delete pfwdmsg; srs_freep(pfwdmsg); return ret; } // the frame length is the AAC raw data plus the adts header size. int32_t frame_length = size + 7; // AAC-ADTS // 6.2 Audio Data Transport Stream, ADTS // in aac-iso-13818-7.pdf, page 26. // fixed 7bytes header u_int8_t adts_header[7] = {0xff, 0xf9, 0x00, 0x00, 0x00, 0x0f, 0xfc}; /* // adts_fixed_header // 2B, 16bits int16_t syncword; //12bits, '1111 1111 1111' int8_t protection_absent; //1bit, can be '1' // 12bits int8_t profile; //2bit, 7.1 Profiles, page 40 TSAacSampleFrequency sampling_frequency_index; //4bits, Table 35, page 46 int8_t private_bit; //1bit, can be '0' int8_t channel_configuration; //3bits, Table 8 int8_t original_or_copy; //1bit, can be '0' int8_t home; //1bit, can be '0' // adts_variable_header // 28bits int8_t copyright_identification_bit; //1bit, can be '0' int8_t copyright_identification_start; //1bit, can be '0' int16_t frame_length; //13bits int16_t adts_buffer_fullness; //11bits, 7FF signals that the bitstream is a variable rate bitstream. int8_t number_of_raw_data_blocks_in_frame; //2bits, 0 indicating 1 raw_data_block() */ // profile, 2bits SrsAacProfile aac_profile = srs_codec_aac_rtmp2ts(codec->aac_object); adts_header[2] = (aac_profile << 6) & 0xc0; // sampling_frequency_index 4bits adts_header[2] |= (codec->aac_sample_rate << 2) & 0x3c; // channel_configuration 3bits adts_header[2] |= (codec->aac_channels >> 2) & 0x01; adts_header[3] = (codec->aac_channels << 6) & 0xc0; // frame_length 13bits adts_header[3] |= (frame_length >> 11) & 0x03; adts_header[4] = (frame_length >> 3) & 0xff; adts_header[5] = ((frame_length << 5) & 0xe0); // adts_buffer_fullness; //11bits adts_header[5] |= 0x1f; //srs_verbose("codec->aac_sample_rate:%d, codec->aac_channels:%d, codec->aac_object:%d", codec->aac_sample_rate, codec->aac_channels, codec->aac_object); // copy to audio buffer pfwdmsg->payload->append((const char*)adts_header, sizeof(adts_header)); pfwdmsg->payload->append(sample_unit->bytes, sample_unit->size); } pfwdmsg->pts = pts; pfwdmsg->dts = pts; pfwdmsg->mediatype = 1; m_vFwdMsgList.push(pfwdmsg); //srs_trace("pfwdmsg:%p, length:%d, pfwdmsg->payloadtype:%d, list_size:%ld, pts:%"PRId64"\n", pfwdmsg, pfwdmsg->payload->length(), pfwdmsg->payloadtype, m_vFwdMsgList.size(), pfwdmsg->pts); return ret; } int ForwardRtspQueue::push_back(ForwardRtspSample* psample) { if(NULL == psample) { lberror("Invalid parameter, psample:%p\n", psample); return -1; } if(m_bwait_keyframe && 0 == psample->mediatype && psample->keyflag) { m_bwait_keyframe = false; } else if(m_bwait_keyframe) { srs_trace("wait for key frame, drop frame, mt:%d, pts:%" PRId64 " keyflag:%d, size:%d\n", psample->mediatype, psample->pts, psample->keyflag, psample->payload->length()); return -1; } m_vFwdMsgList.push(psample); return 0; } int ForwardRtspQueue::get_queue_size() { return (int)m_vFwdMsgList.size(); } ForwardRtspSample* ForwardRtspQueue::dump_packet() { ForwardRtspSample* pfwdmsg = NULL; if(m_vFwdMsgList.size() > 0) { pfwdmsg = m_vFwdMsgList.front(); m_vFwdMsgList.pop(); } return pfwdmsg; } int ForwardRtspQueue::get_sps_pps(std::string& sps, std::string& pps) { if(m_pavccodec && m_pavccodec->sequenceParameterSetLength > 0 && m_pavccodec->pictureParameterSetLength > 0) { sps.clear(); pps.clear(); sps.append(m_pavccodec->sequenceParameterSetNALUnit, m_pavccodec->sequenceParameterSetLength); pps.append(m_pavccodec->pictureParameterSetNALUnit, m_pavccodec->pictureParameterSetLength); return 0; } return -1; } int ForwardRtspQueue::get_aac_sequence_hdr(std::string& audio_cfg) { if(m_paaccodec && m_paaccodec->aac_extra_size > 0) { audio_cfg.clear(); audio_cfg.append(m_paaccodec->aac_extra_data, m_paaccodec->aac_extra_size); return 0; } return -1; } bool ForwardRtspQueue::is_codec_ok() { if(m_pavccodec) return m_pavccodec->is_avc_codec_ok(); return false; } bool SrsForwardRtsp::m_bInit(false); SrsForwardRtsp::SrsForwardRtsp(SrsRequest* req):rtsp_forward_thread("fwdrtsp", this, SRS_RTSP_FORWARD_SLEEP_US) { m_lConnectID = -1; m_pReq = req->copy(); srs_debug(" m_pReq:%p = req->copy()\n", m_pReq); m_pvideofile = NULL; m_paudiofile = NULL; } SrsForwardRtsp::~SrsForwardRtsp() { srs_trace("~SrsForwardRtsp begin"); stop(); srs_trace("~SrsForwardRtsp after stop"); srs_freep(m_pReq); /*if(m_pReq) { delete m_pReq; m_pReq = NULL; }*/ srs_trace("~SrsForwardRtsp after m_pSrsMsgArry"); if(m_pvideofile) { fclose(m_pvideofile); m_pvideofile =NULL; } if(m_paudiofile) { fclose(m_paudiofile); m_paudiofile =NULL; } srs_trace("~SrsForwardRtsp end"); } int SrsForwardRtsp::initialize(const char* prtsp_url, const char* prtsp_log_url) { srs_trace("initialize(prtsp_url:%s, prtsp_log_url:%s)", prtsp_url, prtsp_log_url); if(!prtsp_url) { srs_error("initialize failed, invalid url prtsp_url:%s", prtsp_url); return ERROR_FORWARD_RTSP_INVALID_URL; } m_sRtspUrl = prtsp_url; if(!m_bInit) { if(prtsp_log_url) { m_sFwdRtspLogUrl = prtsp_log_url; } int ret = SVRtspPush_API_Initialize(); if(ret < 0) { srs_error("ret:%d = SVRtspPush_API_Initialize() faield", ret); return ret; } ret = SVRtspPush_API_Init_log(m_sFwdRtspLogUrl.c_str(), 3, 2); srs_trace("initialize end, ret:%d", ret); m_bInit = true; } return ERROR_SUCCESS; } int SrsForwardRtsp::set_raw_data_path(const char* prawpath) { srs_trace("prawpath:%s", prawpath); if(prawpath) { if(access(prawpath, F_OK) != 0) { mkdir(prawpath, 0777); } m_sFwdRtspRawDataDir = prawpath; return ERROR_SUCCESS; } return -1; } int SrsForwardRtsp::publish() { int ret = start(); srs_trace("Forward rtsp publish ret:%d", ret); return ret; } int SrsForwardRtsp::unpublish() { stop(); srs_trace("Forward rtsp unpublish end"); return ERROR_SUCCESS; } int SrsForwardRtsp::start() { srs_trace("start begin, m_bInit:%d", (int)m_bInit); int ret = ERROR_FORWARD_RTSP_NOT_INIT; if(m_bInit) { stop(); ret = rtsp_forward_thread.start(); srs_trace("start end ret:%d, m_bInit:%d", ret, (int)m_bInit); return ret; } return ret; } void SrsForwardRtsp::on_thread_start() { srs_trace(" begin, m_bInit:%d", (int)m_bInit); if(m_bInit) { m_lConnectID = SVRtspPush_API_Connect(m_sRtspUrl.c_str(), SrsForwardRtsp::RtspCallback); srs_trace("m_lConnectID:%ld = SVRtspPush_API_Connect(m_sRtspUrl.c_str():%s, SrsForwardRtsp::RtspCallback:%p)", m_lConnectID, m_sRtspUrl.c_str(), SrsForwardRtsp::RtspCallback); //m_pvideofile = fopen("avc.data", "wb"); //m_paudiofile = fopen("aac.data", "wb"); if(!m_sFwdRtspRawDataDir.empty()) { char path[256] = {0}; sprintf(path, "%s/rtspfwd.h264", m_sFwdRtspRawDataDir.c_str()); m_pvideofile = fopen(path, "wb"); sprintf(path, "%s/rtspfwd.aac", m_sFwdRtspRawDataDir.c_str()); m_paudiofile = fopen(path, "wb"); } srs_trace("m_pvideofile:%p, m_paudiofile:%p", m_pvideofile, m_paudiofile); m_bRuning = true; } srs_trace(" end"); } int SrsForwardRtsp::cycle() { int ret = -1; //srs_trace("Forward rtsp cycle begin, m_vFwdMsgList.size():%d", (int)m_vFwdMsgList.size()); while(m_vFwdMsgList.size() > 0 && m_bRuning) { int writed = 0; ForwardRtspSample* pfrs = dump_packet(); if(pfrs) { //srs_trace("Forward rtsp cycle, send packetg, m_lConnectID:%ld, pfrs->mediatype:%d, size:%d, pts:%"PRId64"", m_lConnectID, pfrs->mediatype, pfrs->payload->length()); if(pfrs->mediatype == 0) { ret = SVRtspPush_API_Send_VideoPacket(m_lConnectID, pfrs->payload->bytes(), pfrs->payload->length(), pfrs->pts); if(m_pvideofile && 0 == ret) { writed = fwrite(pfrs->payload->bytes(), 1, pfrs->payload->length(), m_pvideofile); //srs_trace("writed:%d = fwrite(pfrs->payload->bytes():%p, 1, pfrs->payload->length():%d, m_pvideofile:%p)", writed, pfrs->payload->bytes(), pfrs->payload->length(), m_pvideofile); } srs_trace("ret:%d = SVRtspPush_API_Send_VideoPacket, writed:%d", ret, writed); //srs_trace("ret:%d = SVRtspPush_API_Send_VideoPacket(m_lConnectID:%ld, pfrs->payload->bytes():%p, pfrs->payload->length():%d, pfrs->pts:%"PRId64")", ret, m_lConnectID, pfrs->payload->bytes(), pfrs->payload->length(), pfrs->pts); } else { ret = SVRtspPush_API_Send_AudioPacket(m_lConnectID, pfrs->payload->bytes(), pfrs->payload->length(), pfrs->pts); if(m_paudiofile && 0 == ret) { writed = fwrite(pfrs->payload->bytes(), 1, pfrs->payload->length(), m_paudiofile); //srs_trace("writed:%d = fwrite(pfrs->payload->bytes():%p, 1, pfrs->payload->length():%d, m_paudiofile:%p)", writed, pfrs->payload->bytes(), pfrs->payload->length(), m_paudiofile); } srs_trace("ret:%d = SVRtspPush_API_Send_AudioPacket, writed:%d", ret, writed); //srs_trace("ret:%d = SVRtspPush_API_Send_AudioPacket(m_lConnectID:%ld, pfrs->payload->bytes():%p, pfrs->payload->length():%d, pfrs->pts:%"PRId64")", ret, m_lConnectID, pfrs->payload->bytes(), pfrs->payload->length(), pfrs->pts); } srs_freep(pfrs); //delete pfrs; //pfrs = NULL; srs_trace("after delete pfrs"); } } return ret; } void SrsForwardRtsp::on_thread_stop() { } void SrsForwardRtsp::stop() { srs_trace(" begin"); m_bRuning = false; rtsp_forward_thread.stop(); if(m_bInit && m_lConnectID >= 0) { int ret = SVRtspPush_API_Close(m_lConnectID); srs_trace("ret:%d = SVRtspPush_API_Close(m_lConnectID:%ld)", ret, m_lConnectID); } if(m_pvideofile) { fclose(m_pvideofile); m_pvideofile = NULL; } if(m_paudiofile) { fclose(m_paudiofile); m_paudiofile = NULL; } } bool SrsForwardRtsp::is_forward_rtsp_enable() { return !m_sForwardRtspUrl.empty(); } int SrsForwardRtsp::RtspCallback(int nUserID, E_Event_Code eHeaderEventCode) { srs_trace("nUserID:%ld, eHeaderEventCode:%d\n", nUserID, eHeaderEventCode); return ERROR_SUCCESS; }
36.381955
245
0.607175
breezeewu
40a7a7c216a19ecf469391fdd26677c687cda6e5
5,457
cpp
C++
Bomberman/GUI.cpp
PratikMandlecha/Bomberman
e62d99880f9856aab2aea393099e3386cedcb3ee
[ "MIT" ]
26
2016-05-18T09:39:22.000Z
2022-03-25T10:21:26.000Z
Bomberman/GUI.cpp
PratikMandlecha/Bomberman
e62d99880f9856aab2aea393099e3386cedcb3ee
[ "MIT" ]
4
2016-05-22T11:55:22.000Z
2016-06-09T08:22:36.000Z
Bomberman/GUI.cpp
PratikMandlecha/Bomberman
e62d99880f9856aab2aea393099e3386cedcb3ee
[ "MIT" ]
21
2016-07-20T16:13:01.000Z
2021-11-28T11:08:24.000Z
#include "GUI.h" void GUI::draw(sf::RenderTarget & target, sf::RenderStates states) const { rect->setFillColor(sf::Color(255, 255, 255, 155)); rect->setSize(sf::Vector2f(m_screenWidth, m_screenHeight)); if (m_endOfGameMenuView) { target.draw(*m_frame, states); target.draw(*rect, states); target.draw(*m_returnToMenuButton->GetSpritePointer(), states); target.draw(*m_returnToMenuButton->GetTextPointer(), states); target.draw(*m_playAgainButton->GetSpritePointer(), states); target.draw(*m_playAgainButton->GetTextPointer(), states); target.draw(*m_exitButton->GetSpritePointer(), states); target.draw(*m_exitButton->GetTextPointer(), states); target.draw(*m_winnerText); } if (m_gameGUIView) { target.draw(*m_playerOneLives); target.draw(*m_playerSecondLives); } } GUI::GUI() { } GUI::~GUI() { delete rect; delete m_returnToMenuButton; delete m_playAgainButton; delete m_exitButton; delete m_frameTexture; delete m_frame; delete m_winnerText; delete m_playerOneLives; delete m_playerSecondLives; } void GUI::Init(sf::Font * font, short textSize, int screenWidth, int screenHeight, bool* playAgain, bool* exit, bool* enterMenu) { rect = new sf::RectangleShape(); m_screenWidth = screenWidth; m_screenHeight = screenHeight;; m_playerOneLives = new sf::Text(); m_playerOneLives->setFont(*font); m_playerOneLives->setString("Player 1 Lives: 3"); m_playerOneLives->setPosition(sf::Vector2f(20, 10)); m_playerOneLives->setColor(sf::Color(255, 255, 255)); m_playerOneLives->setScale(1.2f, 1.2f); m_playerSecondLives = new sf::Text(); m_playerSecondLives->setFont(*font); m_playerSecondLives->setString("Player 2 Lives: 3"); m_playerSecondLives->setPosition(sf::Vector2f(screenWidth-300, screenHeight-50)); m_playerSecondLives->setColor(sf::Color(255, 255, 255)); m_playerSecondLives->setScale(1.2f, 1.2f); m_whoWin = -1; m_enterMenu = enterMenu; m_exit = exit; m_playAgain = playAgain; m_endOfGameMenuView = false; m_gameGUIView = true; m_frameTexture = new sf::Texture(); m_frameTexture->loadFromFile("data/frame.png"); m_frame = new sf::Sprite(); m_frame->setTexture(*m_frameTexture); m_frame->setScale((float)m_frameTexture->getSize().x / (float)(screenWidth * 5), (float)m_frameTexture->getSize().y / (float)(screenHeight * 7)); m_frame->setPosition(screenWidth / 2.f - (m_frameTexture->getSize().x * m_frame->getScale().x)/2.f, screenHeight / 3.3f - 50); m_returnToMenuButton = new Button(sf::Vector2f(screenWidth / 2 - 150, screenHeight / 2.3f - 50), sf::Vector2i(300, 75.f), "data/pressButton.png", "data/unpressButton.png", "Return to Menu"); m_playAgainButton = new Button(sf::Vector2f(screenWidth / 2 - 150, screenHeight / 1.7f -50), sf::Vector2i(300, 75.f), "data/pressButton.png", "data/unpressButton.png", "Play Again"); m_exitButton = new Button(sf::Vector2f(screenWidth / 2 - 150, screenHeight / 1.7f + screenHeight / 1.7f - screenHeight / 2.3f - 50), sf::Vector2i(300, 75.f), "data/pressButton.png", "data/unpressButton.png", "Exit Game"); m_winnerText = new sf::Text(); m_winnerText->setFont(*font); m_winnerText->setString("Player 1 Wins!"); sf::FloatRect textRect = m_winnerText->getLocalBounds(); m_winnerText->setOrigin(textRect.left + textRect.width / 2.0f, 0); m_winnerText->setPosition(sf::Vector2f(screenWidth / 2.f,m_frame->getPosition().y+20)); m_winnerText->setColor(sf::Color(0.f, 107, 139)); m_winnerText->setScale(1.2f, 1.2f); } void GUI::UpdateStats(std::vector<Player*>* players, short mouseX, short mouseY) { m_endOfGameMenuView = false; m_gameGUIView = true; for (short i = 0; i < players->size(); ++i) { switch (i) { case 0: m_playerOneLives->setString("Player 1 Lives: " + std::to_string((*players)[i]->GetRespawnsCount())); case 1: m_playerSecondLives->setString("Player 2 Lives: " + std::to_string((*players)[i]->GetRespawnsCount())); } if ((*players)[i]->GetWin()) { m_whoWin = i; m_winnerText->setString("Player "+ std::to_string(m_whoWin+1)+" Wins!"); break; } else { } } } void GUI::UpdateStats(std::vector<Player*>* players, short mouseX, short mouseY, bool & playAgain, bool & exit, bool & enterMenu) { UpdateStats(players, mouseX, mouseY); m_endOfGameMenuView = true; m_gameGUIView = false; } void GUI::processEvents(sf::Vector2i mousePos, sf::Event* eventPointer) { if (m_endOfGameMenuView) { if (eventPointer->type == sf::Event::MouseButtonReleased && eventPointer->mouseButton.button == sf::Mouse::Left) { m_returnToMenuButton->Update(mousePos, false); m_playAgainButton->Update(mousePos, false); m_exitButton->Update(mousePos, false); if (m_returnToMenuButton->GetSpritePointer()->getGlobalBounds().contains((sf::Vector2f)mousePos)) { *m_playAgain = false; *m_enterMenu = true; *m_exit = true; } if (m_playAgainButton->GetSpritePointer()->getGlobalBounds().contains((sf::Vector2f)mousePos)) { *m_playAgain = true; *m_enterMenu = false; *m_exit = false; } if (m_exitButton->GetSpritePointer()->getGlobalBounds().contains((sf::Vector2f)mousePos)) { *m_playAgain = false; *m_enterMenu = false; *m_exit = true; } } if (eventPointer->type == sf::Event::MouseButtonPressed && eventPointer->mouseButton.button == sf::Mouse::Left) { m_returnToMenuButton->Update(mousePos, true); m_playAgainButton->Update(mousePos, true); m_exitButton->Update(mousePos, true); } } }
29.983516
222
0.708814
PratikMandlecha
40aa23d314b53734894c6c1d441a15e4f1712af5
1,290
hpp
C++
libs/core/include/fcppt/container/find_opt_iterator.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/container/find_opt_iterator.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/container/find_opt_iterator.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_CONTAINER_FIND_OPT_ITERATOR_HPP_INCLUDED #define FCPPT_CONTAINER_FIND_OPT_ITERATOR_HPP_INCLUDED #include <fcppt/container/to_iterator_type.hpp> #include <fcppt/optional/object_impl.hpp> namespace fcppt { namespace container { /** \brief Returns an iterator from a find operation or an empty optional. Searches for \a _key in the associative container \a _container. If \a _key is found, its iterator is returned. Otherwise, the empty optional is returned. \ingroup fcpptcontainer \tparam Container Must be an associative container. \tparam Key Must be a key that can be searched for. */ template< typename Container, typename Key > fcppt::optional::object< fcppt::container::to_iterator_type< Container > > find_opt_iterator( Container &_container, Key const &_key ) { auto const it( _container.find( _key ) ); typedef fcppt::optional::object< fcppt::container::to_iterator_type< Container > > result_type; return it != _container.end() ? result_type( it ) : result_type() ; } } } #endif
16.973684
78
0.727132
pmiddend
40ac7c0d929478f10e0c34c5f3f4ae75897ec363
2,894
cpp
C++
platformio/ethernet_client/src/main.cpp
amdxyz/aiolib
90d6541b0945680d61d070109f8bcc468902af38
[ "MIT" ]
1
2020-05-24T10:33:14.000Z
2020-05-24T10:33:14.000Z
platformio/ethernet_client/src/main.cpp
amdxyz/aiolib
90d6541b0945680d61d070109f8bcc468902af38
[ "MIT" ]
1
2019-02-20T19:33:08.000Z
2019-02-20T19:36:19.000Z
platformio/ethernet_client/src/main.cpp
amdx/aiolib
90d6541b0945680d61d070109f8bcc468902af38
[ "MIT" ]
null
null
null
/** * AMDX AIO arduino library * * Copyright (C) 2019-2020 Archimedes Exhibitions GmbH * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ // Tests the onboard W5500 ethernet controller on the AIO XL #include <Arduino.h> #include <Ethernet.h> #include <AIO.h> using namespace AIO; const uint8_t MAX_CHUNK_SIZE = 128; uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; EthernetClient client; void fetch_page(const char* host) { uint8_t chunk[MAX_CHUNK_SIZE]; Serial.print(F(">>> Connecting to: ")); Serial.println(host); if (client.connect(host, 80)) { client.write("HEAD / HTTP/1.1\nHost:"); client.write(host); client.write("\nConnection: close\n\n"); Serial.println(F(">>> Retrieving data:")); while (1) { int length = client.read(chunk, MAX_CHUNK_SIZE); if (length > 0) { Serial.write(chunk, length); } else if (!client.connected()) { Serial.println(); Serial.println(F(">>> Head fetched")); break; } } } else { Serial.println(F("*** Cannot connect to the remote end")); } } void setup() { // Open serial communications and wait for port to open: Serial.begin(115200); Serial.print(F("Initializing..")); Ethernet.init(ETH_CS_PIN); Ethernet.begin(mac, IPAddress(0, 0, 0, 0)); Serial.println("done."); Serial.print(F("Waiting for link..")); while (Ethernet.linkStatus() != LinkON) { delay(500); Serial.print("."); } Serial.println(F("link is up.")); Serial.print(F("Requesting IP via DHCP..")); // Initialize the ethernet library Ethernet.begin(mac); Serial.println(F("done.")); fetch_page("www.google.com"); } void loop() { }
28.94
93
0.651348
amdxyz
40b2611eae038d213c5ccfa342d44e5e7b9e2868
593
cpp
C++
MoravaEngine/src/H2M/Core/HashH2M.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
null
null
null
MoravaEngine/src/H2M/Core/HashH2M.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
null
null
null
MoravaEngine/src/H2M/Core/HashH2M.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
1
2022-01-05T03:51:02.000Z
2022-01-05T03:51:02.000Z
/** * @package H2M (Hazel to Morava) * @author Yan Chernikov (TheCherno) * @licence Apache License 2.0 */ #include "HashH2M.h" namespace H2M { uint32_t HashH2M::GenerateFNVHash(const char* str) { constexpr uint32_t FNV_PRIME = 16777619u; constexpr uint32_t OFFSET_BASIS = 2166136261u; const size_t length = strlen(str) + 1; uint32_t hash = OFFSET_BASIS; for (size_t i = 0; i < length; ++i) { hash ^= *str++; hash *= FNV_PRIME; } return hash; } uint32_t HashH2M::GenerateFNVHash(const std::string& string) { return GenerateFNVHash(string.c_str()); } }
17.441176
61
0.671164
imgui-works
40b523f52870cab0904b80949e7e892cc5c49cde
395
cpp
C++
test/chapter_09_data_serialization/problem_077_printing_a_list_of_movies_to_a_pdf.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
test/chapter_09_data_serialization/problem_077_printing_a_list_of_movies_to_a_pdf.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
test/chapter_09_data_serialization/problem_077_printing_a_list_of_movies_to_a_pdf.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
#include "chapter_09_data_serialization/problem_077_printing_a_list_of_movies_to_a_pdf.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <sstream> // ostringstream TEST(problem_77_main, DISABLED_output) { std::ostringstream oss{}; problem_77_main(oss); EXPECT_THAT(oss.str(), ::testing::ContainsRegex( "Writing PDF out to: .*/list_of_movies.pdf\n" )); }
24.6875
89
0.726582
rturrado
40b5ce5cc77231d5ef5716675374b11c6290e415
5,517
hpp
C++
renderboi/core/shader/shader_program.hpp
deqyra/GLSandbox
40d641ebbf6af694e8640a584d283876d128748c
[ "MIT" ]
null
null
null
renderboi/core/shader/shader_program.hpp
deqyra/GLSandbox
40d641ebbf6af694e8640a584d283876d128748c
[ "MIT" ]
null
null
null
renderboi/core/shader/shader_program.hpp
deqyra/GLSandbox
40d641ebbf6af694e8640a584d283876d128748c
[ "MIT" ]
null
null
null
#ifndef RENDERBOI__CORE__SHADER__SHADER_PROGRAM_HPP #define RENDERBOI__CORE__SHADER__SHADER_PROGRAM_HPP #include <glad/gl.h> #include <glm/glm.hpp> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <unordered_map> #include "shader_feature.hpp" #include "../material.hpp" namespace Renderboi { class ShaderBuilder; /// @brief Handler for a shader program resource on the GPU. class ShaderProgram { friend ShaderBuilder; private: /// @param location Location of the shader program resource on the GPU. /// @param supportedFeatures Array of literals describing features which /// the shader program supports. ShaderProgram(const unsigned int location, const std::vector<ShaderFeature> supportedFeatures); /// @brief The location of the shader resource on the GPU. unsigned int _location; /// @brief Array of literals describing features which the shader /// program supports. std::vector<ShaderFeature> _supportedFeatures; /// @brief Structure mapping uniform locations against their name, and /// then against the location of the program they belong to. static std::unordered_map<unsigned int, std::unordered_map<std::string, unsigned int>> _uniformLocations; /// @brief Structure mapping how many shader instances are referencing a /// shader resource on the GPU. static std::unordered_map<unsigned int, unsigned int> _locationRefCounts; /// @brief Free resources upon destroying an instance. void _cleanup(); public: ShaderProgram(const ShaderProgram& other); ~ShaderProgram(); ShaderProgram& operator=(const ShaderProgram& other); /// @brief Get location of the shader program on the GPU. /// /// @return The location of the shader program on the GPU. unsigned int location() const; /// @brief Enable the shader on the GPU. void use() const; /// @brief Get the GPU location of a named uniform in the program. /// /// @param name The name of the uniform to locate in the program. /// /// @return The GPU location of a named uniform in the shader program. unsigned int getUniformLocation(const std::string& name) const; /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type bool. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setBool(const std::string& name, const bool value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type int. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setInt(const std::string& name, const int value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type unsigned int. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setUint(const std::string& name, const unsigned int value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type float. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setFloat(const std::string& name, const float value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type 3-by-3 float matrix. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. /// @param transpose Whether or not to transpose the matrix before /// sending. void setMat3f(const std::string& name, const glm::mat3& value, const bool transpose = false); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type 4-by-4 float matrix. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. /// @param transpose Whether or not to transpose the matrix before /// sending. void setMat4f(const std::string& name, const glm::mat4& value, const bool transpose = false); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type 3-dimensional float vector. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setVec3f(const std::string& name, const glm::vec3& value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type material. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setMaterial(const std::string& name, const Material& value); /// @brief Get the features which this shader program supports. /// /// @return A const reference to an array of literals describing which /// features the shader program supports. const std::vector<ShaderFeature>& getSupportedFeatures() const; /// @brief Tells whether this shader supports a certain feature. /// /// @param feature Literal describing the feature to check on. /// /// @return Whether or not the feature is supported. bool supports(const ShaderFeature feature) const; }; }//namespace Renderboi #endif//RENDERBOI__CORE__SHADER__SHADER_PROGRAM_HPP
37.277027
109
0.684249
deqyra
8ad653610f9deded27ac62e1d95fcf2b6797912c
2,290
cpp
C++
src/Group.cpp
gicmo/nix
17a5b90e6c12a22e921c181b79eb2a3db1bf61af
[ "BSD-3-Clause" ]
53
2015-02-10T01:04:34.000Z
2021-04-24T14:26:04.000Z
src/Group.cpp
tapaswenipathak/nix
4565c2d7b363f27cac88932b35c085ee8fe975a1
[ "BSD-3-Clause" ]
262
2015-01-09T13:24:21.000Z
2021-07-02T13:45:31.000Z
src/Group.cpp
gicmo/nix
17a5b90e6c12a22e921c181b79eb2a3db1bf61af
[ "BSD-3-Clause" ]
34
2015-03-27T16:41:14.000Z
2020-03-27T06:47:59.000Z
// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/Group.hpp> #include <nix/util/util.hpp> using namespace nix; template<typename T> void Group::replaceEntities(const std::vector<T> &entities) { base::IGroup *ig = backend(); ObjectType ot = objectToType<T>::value; while (ig->entityCount(ot) > 0) { ig->removeEntity(ig->getEntity<typename objectToType<T>::backendType>(0)); } for (const auto &e : entities) { ig->addEntity(e); } } void Group::dataArrays(const std::vector<DataArray> &data_arrays) { replaceEntities(data_arrays); } std::vector<DataArray> Group::dataArrays(const util::Filter<DataArray>::type &filter) const { auto f = [this] (size_t i) { return getDataArray(i); }; return getEntities<DataArray>(f, dataArrayCount(), filter); } void Group::dataFrames(const std::vector<DataFrame> &data_frames) { replaceEntities(data_frames); } std::vector<DataFrame> Group::dataFrames(const util::Filter<DataFrame>::type &filter) const { auto f = [this] (size_t i) { return getDataFrame(i); }; return getEntities<DataFrame>(f, dataFrameCount(), filter); } void Group::tags(const std::vector<Tag> &tags) { replaceEntities(tags); } std::vector<Tag> Group::tags(const util::Filter<Tag>::type &filter) const { auto f = [this] (size_t i) { return getTag(i); }; return getEntities<Tag>(f, tagCount(), filter); } std::vector<MultiTag> Group::multiTags(const util::Filter<MultiTag>::type &filter) const { auto f = [this] (size_t i) { return getMultiTag(i); }; return getEntities<MultiTag>(f, multiTagCount(), filter); } void Group::multiTags(const std::vector<MultiTag> &tags) { replaceEntities(tags); } std::ostream& nix::operator<<(std::ostream &out, const Group &ent) { out << "Group: {name = " << ent.name(); out << ", type = " << ent.type(); out << ", id = " << ent.id() << "}"; return out; }
27.590361
93
0.625328
gicmo
8ad874790cc7b81859edcf2349de3491b20944b5
1,749
hpp
C++
test/unit/search/helper.hpp
remyschwab/seqan3
f10e557b61428ff7faac8b10f18b9087d1ff2663
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/search/helper.hpp
remyschwab/seqan3
f10e557b61428ff7faac8b10f18b9087d1ff2663
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/search/helper.hpp
remyschwab/seqan3
f10e557b61428ff7faac8b10f18b9087d1ff2663
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #pragma once #include <algorithm> #include <iterator> #include <vector> #include <seqan3/core/debug_stream/debug_stream_type.hpp> #include <seqan3/search/fm_index/bi_fm_index_cursor.hpp> #include <seqan3/search/fm_index/fm_index_cursor.hpp> #include <seqan3/utility/views/to.hpp> namespace seqan3 { template <typename char_t, typename index_t> inline debug_stream_type<char_t> & operator<<(debug_stream_type<char_t> & s, seqan3::fm_index_cursor<index_t> const &) { return s << ("fm_index_cursor"); } template <typename char_t, typename index_t> inline debug_stream_type<char_t> & operator<<(debug_stream_type<char_t> & s, seqan3::bi_fm_index_cursor<index_t> const &) { return s << ("bi_fm_index_cursor"); } template <typename result_range_t> std::vector<std::ranges::range_value_t<result_range_t>> uniquify(result_range_t && result_range) { auto unique_res = result_range | views::to<std::vector>; std::sort(unique_res.begin(), unique_res.end()); unique_res.erase(std::unique(unique_res.begin(), unique_res.end()), unique_res.end()); return unique_res; } } // namespace std
38.866667
104
0.6255
remyschwab
8ae376ff7484994fb0d118556b27921a69aad370
535
cpp
C++
demo/main.cpp
SSBMTonberry/emusound
3f07b3af1158277cacaf63d78c47f47aeb18723d
[ "BSD-2-Clause" ]
4
2020-07-22T07:26:18.000Z
2020-09-01T22:10:21.000Z
demo/main.cpp
SSBMTonberry/emusound
3f07b3af1158277cacaf63d78c47f47aeb18723d
[ "BSD-2-Clause" ]
1
2020-08-21T06:43:04.000Z
2020-08-30T12:28:08.000Z
demo/main.cpp
SSBMTonberry/emusound
3f07b3af1158277cacaf63d78c47f47aeb18723d
[ "BSD-2-Clause" ]
null
null
null
// // Created by robin on 19.01.2020. // #include "ProgramManager.h" int emuprogramExample(int argc, char** argv) { std::string title = "emusound demo"; sf::ContextSettings settings; settings.antialiasingLevel = 0; esnddemo::ProgramManager program(title, sf::Vector2i(400 * 4, 240 * 4), sf::Vector2i(400, 240), sf::Style::Titlebar, settings); //program.setZoomValue(1.f); program.initialize(); program.run(); return 0; } int main(int argc, char** argv) { return emuprogramExample(argc, argv); }
22.291667
131
0.66729
SSBMTonberry
8ae52f3cde59794915f589b495859af442b3ea62
9,126
cpp
C++
Managment/src/slam_client.cpp
cxdcxd/sepanta3
a65a3415f046631ac4d6b91f9342966b0c030226
[ "MIT" ]
1
2018-09-11T18:40:25.000Z
2018-09-11T18:40:25.000Z
ROS/Managment/src/slam_client.cpp
cxdcxd/NAVbot
8068e7ca596708f1fbfc63b1f6f944b85dee0953
[ "MIT" ]
null
null
null
ROS/Managment/src/slam_client.cpp
cxdcxd/NAVbot
8068e7ca596708f1fbfc63b1f6f944b85dee0953
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <move_base_msgs/MoveBaseAction.h> #include <actionlib/client/simple_action_client.h> #include <tf/transform_broadcaster.h> #include <stdio.h> #include <boost/thread.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <actionlib/client/simple_action_client.h> #include <actionlib/client/terminal_state.h> #include <sepanta_msgs/command.h> #include <sepanta_msgs/omnidata.h> #include <sepanta_msgs/sepantaAction.h> //movex movey turngl turngllocal actions #include <sepanta_msgs/slamactionAction.h> //slam action #include <std_msgs/Int32.h> #include <std_msgs/Bool.h> //#include <std_msgs/Bool.h> #include "sepanta_msgs/stop.h" typedef actionlib::SimpleActionClient<sepanta_msgs::slamactionAction> SLAMClient; typedef actionlib::SimpleActionClient<sepanta_msgs::sepantaAction> SepantaClient; ros::ServiceClient serviceclient_odometryslam; ros::ServiceClient serviceclient_facestop; ros::ServiceClient serviceclient_manualauto; ros::ServiceClient serviceclient_map; SLAMClient *globalSLAM; SepantaClient *globalSepanta; bool App_exit = false; ros::Publisher chatter_pub[20]; using namespace std; bool flag1 = false; bool flag2 = false; int old = 0; std::string service_command = ""; std::string service_id = ""; int service_value = 0 ; void goWithOdometry(string mode,int value) { ROS_INFO("Going %s with odometry...", mode.c_str()); sepanta_msgs::sepantaGoal interfacegoal; interfacegoal.type = mode; interfacegoal.value = value; actionlib::SimpleClientGoalState state = globalSepanta->sendGoalAndWait(interfacegoal, ros::Duration(1000), ros::Duration(1000)); if (state == actionlib::SimpleClientGoalState::PREEMPTED) { ROS_INFO("ODOMETRY PREEMPTED"); } if (state == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("ODOMETRY SUCCEEDED"); } if (state == actionlib::SimpleClientGoalState::ABORTED) { ROS_INFO("ODOMETRY ABORTED"); } } void goWithSlam(string where) { ROS_INFO("Going %s with slam...", where.c_str()); sepanta_msgs::slamactionGoal interfacegoal; interfacegoal.x = 0; interfacegoal.y = 0; interfacegoal.yaw = 0; interfacegoal.ID = where; ROS_INFO("goal sent to slam... waiting for reach there."); cout << where << endl; actionlib::SimpleClientGoalState state = globalSLAM->sendGoalAndWait(interfacegoal, ros::Duration(1000), ros::Duration(1000)); if (state == actionlib::SimpleClientGoalState::PREEMPTED) { ROS_INFO("SLAM PREEMPTED"); } if (state == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("SLAM SUCCEEDED"); } if (state == actionlib::SimpleClientGoalState::ABORTED) { ROS_INFO("SLAM ABORTED"); } } void service_thread2() { while ( App_exit == false && ros::ok()) { if (service_command == "gotocancle") { ROS_INFO("GOTOCANCLE"); globalSLAM->cancelGoal(); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "odometrycancle") { ROS_INFO("ODOMETRYCANCLE"); globalSepanta->cancelGoal(); service_command = ""; service_id = ""; service_value = 0; } boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } } void service_thread() { while ( App_exit == false && ros::ok()) { if (service_command == "goto") { ROS_INFO("GET GOTO"); goWithSlam(service_id); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "movex") { ROS_INFO("MOVEX"); goWithOdometry(service_command,service_value); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "movey") { ROS_INFO("MOVEY"); goWithOdometry(service_command,service_value); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "turngl") { ROS_INFO("TURNGL"); goWithOdometry(service_command,service_value); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "turngllocal") { ROS_INFO("TURNGLLOCAL"); goWithOdometry(service_command,service_value); service_command = ""; service_id = ""; service_value = 0; } boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } } bool checkcommand(sepanta_msgs::command::Request &req,sepanta_msgs::command::Response &res) { std::string str = req.command; std::string id = req.id; int value = req.value; ROS_INFO("Service Request...."); service_command = str; service_id = id; service_value = value; res.result = "done"; return true; } void omnidrive(int x,int y,int w) { sepanta_msgs::omnidata msg_data; msg_data.d0 = x; msg_data.d1 = y; msg_data.d2 = w; chatter_pub[0].publish(msg_data); } void calibration_test() { return; cout << "calib start start" << endl; boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); //reset_position(); omnidrive(0, 0, 30); boost::this_thread::sleep(boost::posix_time::milliseconds(10000)); omnidrive(0, 0, 0); boost::this_thread::sleep(boost::posix_time::milliseconds(5000)); cout << "back" << endl; omnidrive(0, 0, -30); boost::this_thread::sleep(boost::posix_time::milliseconds(10000)); omnidrive(0, 0, 0); boost::this_thread::sleep(boost::posix_time::milliseconds(5000)); cout << "finish" << endl; // cout << position[0] << " , " << position[1] << " , " << position[2] << " , " << delta<< endl; } void checkkeypad(const std_msgs::Int32::ConstPtr &topicMsg) { int value = topicMsg->data ; //ROS_INFO("%d",value); if ( value != old) { ROS_INFO("%d",value); old = value; if(value==3) { omnidrive(0,0,0); // std_msgs::Bool msg; // msg.data = true; // chatter_pub[2].publish(msg); } if(value== 7) { omnidrive(200,0,0); } if(value==8) { omnidrive(-200,0,0); } if(value==9) { omnidrive(0,200,0); } if(value==10) { omnidrive(0,-200,0); } if(value==5) { omnidrive(0,0,220); } if(value==6) { omnidrive(0,0,-220); } //================ if ( value == 1) { //manual mode start // sepanta_msgs::stop srv_stop; // srv_stop.request.command = "Manual"; // serviceclient_manualauto.call(srv_stop); } if ( value == 4) { //slam mode start //sepanta_msgs::stop srv_stop; //srv_stop.request.command = "Slam"; //serviceclient_manualauto.call(srv_stop); } if ( value == 2) { //manual reached //sepanta_msgs::stop srv_stop; //srv_stop.request.command = "ManualReached"; //serviceclient_manualauto.call(srv_stop); // std_msgs::Bool msg; // msg.data = false; // chatter_pub[2].publish(msg); } } } int main(int argc, char** argv) { ros::init(argc, argv, "navigation_client"); ros::Time::init(); cout << "SEPANTA SLAM CLIENTS SERVICES STARTED DONE (93/04/05)" << endl; ros::NodeHandle n_service; ros::ServiceServer service_command = n_service.advertiseService("AUTROBOTINSRV_command", checkcommand); ros::NodeHandle node_handles[15]; chatter_pub[0] = node_handles[0].advertise<sepanta_msgs::omnidata>("AUTROBOTIN_omnidrive", 10); chatter_pub[1] = node_handles[1].advertise<std_msgs::Bool>("AUTROBOTIN_greenlight", 10); chatter_pub[2] = node_handles[2].advertise<std_msgs::Bool>("AUTROBOTIN_redlight", 10); ros::Subscriber sub_handles[1]; sub_handles[0] = node_handles[1].subscribe("AUTROBOTOUT_keypad", 10, checkkeypad); ros::NodeHandle n_client1; serviceclient_facestop = n_client1.serviceClient<sepanta_msgs::stop>("speechOrFace_Stop"); ros::NodeHandle n_client2; serviceclient_manualauto = n_client2.serviceClient<sepanta_msgs::stop>("manualOrAuto"); SLAMClient slamAction("slam_action", true); globalSLAM = &slamAction ; slamAction.waitForServer(); ROS_INFO("connected to slam server"); //=========================================== SepantaClient sepantaAction("sepanta_action", true); globalSepanta = &sepantaAction ; sepantaAction.waitForServer(); ROS_INFO("connected to sepanta server"); ros::Rate ros_rate(20); boost::thread _thread_logic(&calibration_test); boost::thread _thread_serevice(&service_thread); boost::thread _thread_serevice2(&service_thread2); while(ros::ok()) { ros::spinOnce(); ros_rate.sleep(); } App_exit = true; _thread_logic.interrupt(); _thread_logic.join(); _thread_serevice.interrupt(); _thread_serevice.join(); _thread_serevice2.interrupt(); _thread_serevice2.join(); return 0; }
23.952756
133
0.636862
cxdcxd
8ae63d490cda9c5c36b938df14957f23e053c408
99,673
cpp
C++
compiler/src/cpp_synth.cpp
mdegirolami/stay
b47676e5340c2bbd93fe97d52a12a895a3492b22
[ "BSD-3-Clause" ]
null
null
null
compiler/src/cpp_synth.cpp
mdegirolami/stay
b47676e5340c2bbd93fe97d52a12a895a3492b22
[ "BSD-3-Clause" ]
null
null
null
compiler/src/cpp_synth.cpp
mdegirolami/stay
b47676e5340c2bbd93fe97d52a12a895a3492b22
[ "BSD-3-Clause" ]
null
null
null
#include <assert.h> #include <string.h> #include <stdio.h> #include <vector> #include <cinttypes> #include "cpp_synth.h" #include "FileName.h" #include "helpers.h" #include "builtin_functions.h" namespace SingNames { static const int KForcedPriority = 100; // i.e. requires no protection and never overrides order. (uses brackets) //static const int KLiteralPriority = 0; // a single literal numeral, can be converted changing the suffix static const int KLeafPriority = 1; // a single item, not a literal numeral static const int KCastPriority = 3; bool IsFloatFormat(const char *num); void CppSynth::Synthetize(string *cppfile, string *hppfile, PackageManager *packages, Options *options, int pkg_index, bool *empty_cpp) { string text; int num_levels, num_items; *cppfile = ""; *hppfile = ""; const Package *pkg = packages->getPkg(pkg_index); pkmgr_ = packages; root_ = (AstFile*)pkg->GetRoot(); indent_ = 0; split_level_ = 0xff; exp_level = 0; synth_options_ = options->GetSynthOptions(); debug_ = options->IsDebugBuild(); // HPP file ///////////////// formatter_.Reset(); formatter_.SetMaxLineLen(synth_options_->max_linelen_); formatter_.SetRemarks(&root_->remarks_[0], root_->remarks_.size()); file_str_ = hppfile; text = "#pragma once"; Write(&text, false); EmptyLine(); // headers text = "#include <sing.h>"; Write(&text, false); WriteHeaders(DependencyUsage::PUBLIC); EmptyLine(); // open the namespace num_levels = WriteNamespaceOpening(); // all public declarations by cathegory WriteClassForwardDeclarations(true); WriteTypeDefinitions(true); WritePrototypes(true); WriteExternalDeclarations(); WriteNamespaceClosing(num_levels); if (options->GenerateHOnly()) { *empty_cpp = true; return; } // CPP file ///////////////// formatter_.Reset(); formatter_.SetRemarks(&root_->remarks_[0], root_->remarks_.size()); file_str_ = cppfile; string fullname = pkg->getFullPath(); FileName::SplitFullName(nullptr, &text, nullptr, &fullname); text.insert(0, "#include \""); text += ".h\""; Write(&text, false); num_items = WriteHeaders(DependencyUsage::PRIVATE); EmptyLine(); // open the namespace num_levels = WriteNamespaceOpening(); // all public declarations by cathegory WriteClassForwardDeclarations(false); num_items += WriteTypeDefinitions(false); WritePrototypes(false); num_items += WriteVariablesDefinitions(); num_items += WriteClassIdsDefinitions(); num_items += WriteConstructors(); num_items += WriteFunctions(); WriteNamespaceClosing(num_levels); *empty_cpp = num_items == 0; } void CppSynth::SynthVar(VarDeclaration *declaration) { string text, typedecl, initer; if (!declaration->HasOneOfFlags(VF_ISLOCAL) && (!declaration->IsPublic() || declaration->HasOneOfFlags(VF_IMPLEMENTED_AS_CONSTINT)) ) { text = "static "; } if (declaration->initer_ != nullptr) { SynthIniterCore(&initer, declaration->GetTypeSpec(), declaration->initer_); } else if (declaration->HasOneOfFlags(VF_ISLOCAL)) { SynthZeroIniter(&initer, declaration->GetTypeSpec()); } if (declaration->HasOneOfFlags(VF_ISPOINTED)) { bool init_on_second_row = declaration->initer_ != nullptr && declaration->initer_->GetType() == ANT_INITER; init_on_second_row = init_on_second_row || initer[0] == '{'; text += "std::shared_ptr<"; if (declaration->HasOneOfFlags(VF_READONLY)) { text += "const "; } SynthTypeSpecification(&typedecl, declaration->GetTypeSpec()); text += typedecl; text += "> "; text += declaration->name_; text += " = std::make_shared<"; text += typedecl; if (initer.length() > 0 && !init_on_second_row) { text += ">("; text += initer; text += ")"; } else { text += ">()"; } Write(&text); if (initer.length() > 0 && init_on_second_row) { text = "*"; text += declaration->name_; text += " = "; text += initer; Write(&text); } } else { if (declaration->HasOneOfFlags(VF_READONLY)) { text += "const "; } typedecl = declaration->name_; IAstTypeNode *tnode = declaration->GetTypeSpec(); SynthTypeSpecification(&typedecl, tnode); text += typedecl; if (initer.length() > 0) { text += " = "; text += initer; } Write(&text); } } void CppSynth::SynthType(TypeDeclaration *declaration) { switch (declaration->type_spec_->GetType()) { case ANT_CLASS_TYPE: SynthClassDeclaration(declaration->name_.c_str(), (AstClassType*)declaration->type_spec_); break; case ANT_INTERFACE_TYPE: SynthInterfaceDeclaration(declaration->name_.c_str(), (AstInterfaceType*)declaration->type_spec_); break; case ANT_ENUM_TYPE: SynthEnumDeclaration(declaration->name_.c_str(), (AstEnumType*)declaration->type_spec_); break; default: { string text(declaration->name_); SynthTypeSpecification(&text, declaration->type_spec_); text.insert(0, "typedef "); Write(&text); break; } } } void CppSynth::SynthFunc(FuncDeclaration *declaration) { string text, typedecl; EmptyLine(); if (declaration->is_class_member_) { AstClassType *ctype = GetLocalClassTypeDeclaration(declaration->classname_.c_str()); if (ctype != nullptr && ctype->has_constructor && !ctype->constructor_written) { ctype->SetConstructorDone(); SynthConstructor(&declaration->classname_, ctype); } EmptyLine(); if (declaration->name_ == "finalize") { text = declaration->classname_ + "::~" + declaration->classname_ + "()"; } else { text = declaration->classname_ + "::" + declaration->name_; SynthFuncTypeSpecification(&text, declaration->function_type_, false); if (!declaration->is_muting_) { text += " const"; } } } else { text = declaration->name_; SynthFuncTypeSpecification(&text, declaration->function_type_, false); if (!declaration->IsPublic()) { text.insert(0, "static "); } } SynthFunOpenBrace(text); return_type_ = declaration->function_type_->return_type_; function_name_ = declaration->name_; if (debug_) { WriteArgumentsGuards(declaration->function_type_); } SynthBlock(declaration->block_); } void CppSynth::SynthFunOpenBrace(string &text) { if (!synth_options_->newline_before_function_bracket_) { text += " {"; } Write(&text, false); if (synth_options_->newline_before_function_bracket_) { text = "{"; Write(&text, false); } } void CppSynth::SynthConstructor(string *classname, AstClassType *ctype) { string initer, text; EmptyLine(); text = *classname + "::" + *classname + "()"; SynthFunOpenBrace(text); ++indent_; for (int ii = 0; ii < ctype->member_vars_.size(); ++ii) { VarDeclaration *vdecl = ctype->member_vars_[ii]; initer = ""; if (vdecl->initer_ != nullptr) { SynthIniterCore(&initer, vdecl->GetTypeSpec(), vdecl->initer_); } else { SynthZeroIniter(&initer, vdecl->GetTypeSpec()); } if (initer.length() > 0) { text = ""; AppendMemberName(&text, vdecl); text += " = "; text += initer; Write(&text); } } --indent_; text = "}"; Write(&text, false); } void CppSynth::SynthTypeSpecification(string *dst, IAstTypeNode *type_spec) { switch (type_spec->GetType()) { case ANT_BASE_TYPE: { const char *name = GetBaseTypeName(((AstBaseType*)type_spec)->base_type_); PrependWithSeparator(dst, name); } break; case ANT_NAMED_TYPE: { AstNamedType *node = (AstNamedType*)type_spec; if (node->next_component != nullptr) { string full; GetFullExternName(&full, node->pkg_index_, node->next_component->name_.c_str()); PrependWithSeparator(dst, full.c_str()); } else if (node->pkg_index_ > 0) { string full; GetFullExternName(&full, node->pkg_index_, node->name_.c_str()); PrependWithSeparator(dst, full.c_str()); } else { PrependWithSeparator(dst, node->name_.c_str()); } } break; case ANT_ARRAY_TYPE: SynthArrayTypeSpecification(dst, (AstArrayType*)type_spec); break; case ANT_MAP_TYPE: { AstMapType *node = (AstMapType*)type_spec; string fulldecl, the_type; fulldecl = "sing::map<"; SynthTypeSpecification(&the_type, node->key_type_); fulldecl += the_type; fulldecl += ", "; the_type = ""; SynthTypeSpecification(&the_type, node->returned_type_); fulldecl += the_type; fulldecl += ">"; PrependWithSeparator(dst, fulldecl.c_str()); } break; case ANT_POINTER_TYPE: { AstPointerType *node = (AstPointerType*)type_spec; string fulldecl, the_type; fulldecl = "std::"; if (node->isweak_) { fulldecl += "weak_ptr<"; } else { fulldecl += "shared_ptr<"; } if (node->isconst_) fulldecl += "const "; SynthTypeSpecification(&the_type, node->pointed_type_); fulldecl += the_type; fulldecl += ">"; PrependWithSeparator(dst, fulldecl.c_str()); } break; case ANT_FUNC_TYPE: dst->insert(0, "(*"); *dst += ")"; SynthFuncTypeSpecification(dst, (AstFuncType*)type_spec, false); break; case ANT_ENUM_TYPE: { AstEnumType *node = (AstEnumType*)type_spec; int pkg_idx = node->GetPositionRecord()->package_idx; if (pkg_idx > 0) { string full; GetFullExternName(&full, pkg_idx, node->name_.c_str()); PrependWithSeparator(dst, full.c_str()); } else { PrependWithSeparator(dst, node->name_.c_str()); } } break; case ANT_CLASS_TYPE: { // this is possible only locally, else the class is referred as a named type. AstClassType *node = (AstClassType*)type_spec; PrependWithSeparator(dst, node->name_.c_str()); } } } void CppSynth::SynthFuncTypeSpecification(string *dst, AstFuncType *type_spec, bool prototype) { int ii; --split_level_; *dst += "("; AddSplitMarker(dst); if (type_spec->arguments_.size() > 0) { string the_type; int last_uninited; for (last_uninited = type_spec->arguments_.size() - 1; last_uninited >= 0; --last_uninited) { if (type_spec->arguments_[last_uninited]->initer_ == NULL) break; } for (ii = 0; ii < (int)type_spec->arguments_.size(); ++ii) { // collect info VarDeclaration *arg = type_spec->arguments_[ii]; ParmPassingMethod mode = GetParameterPassingMethod(arg->GetTypeSpec(), arg->HasOneOfFlags(VF_READONLY)); // sinth the parm if (mode == PPM_INPUT_STRING) { the_type = "char *"; the_type += arg->name_; } else { if (mode == PPM_POINTER) { the_type = "*"; the_type += arg->name_; } else if (mode == PPM_CONSTREF) { the_type = "&"; the_type += arg->name_; } else { // PPM_VALUE the_type = arg->name_; } SynthTypeSpecification(&the_type, arg->GetTypeSpec()); } // add to dst if (ii != 0) { *dst += ", "; AddSplitMarker(dst); } if (arg->HasOneOfFlags(VF_READONLY) && mode != PPM_VALUE) { *dst += "const "; } if (ii > last_uninited && prototype) { SynthIniter(&the_type, arg->GetTypeSpec(), arg->initer_); } *dst += the_type; } if (type_spec->varargs_) { *dst += ", "; } } if (type_spec->varargs_) { *dst += "..."; } *dst += ')'; SynthTypeSpecification(dst, type_spec->return_type_); ++split_level_; } void CppSynth::SynthArrayTypeSpecification(string *dst, AstArrayType *type_spec) { string the_type, decl; if (type_spec->is_dynamic_) { decl = "std::vector<"; } else { decl = "sing::array<"; } SynthTypeSpecification(&the_type, type_spec->element_type_); decl += the_type; if (!type_spec->is_dynamic_) { // i.e.: is sing::array if (type_spec->expression_ != nullptr) { string exp; decl += ", "; int priority = SynthExpression(&exp, type_spec->expression_); if (type_spec->expression_->GetAttr()->IsEnum()) { priority = AddCast(&exp, priority, "size_t"); } Protect(&exp, priority, GetBinopCppPriority(TOKEN_SHR)); // because SHR gets confused with the end of the template parameters list '>' decl += exp; } else { // length determined based on the initializer char buffer[32]; sprintf(buffer, ", %" PRIu64, (uint64_t)type_spec->dimension_); decl += buffer; } } decl += ">"; PrependWithSeparator(dst, decl.c_str()); } void CppSynth::SynthClassDeclaration(const char *name, AstClassType *type_spec) { bool has_base = type_spec->member_interfaces_.size() > 0; SynthClassHeader(name, &type_spec->member_interfaces_, false); // collect some info bool supports_typeswitch = type_spec->member_interfaces_.size() > 0; bool has_private = false; bool has_public_var = false; bool needs_constructor = false; for (int ii = 0; ii < type_spec->member_vars_.size(); ++ii) { VarDeclaration *vdecl = type_spec->member_vars_[ii]; if (!vdecl->IsPublic()) { has_private = true; } else { has_public_var = true; } if (vdecl->initer_ != nullptr || vdecl->GetTypeSpec()->NeedsZeroIniter()) { needs_constructor = true; } } for (int ii = 0; ii < type_spec->member_functions_.size() && !has_private; ++ii) { if (!type_spec->member_functions_[ii]->IsPublic()) { has_private = true; } } // for later use !! if (needs_constructor) { type_spec->SetNeedsConstructor(); } string text = "public:"; Write(&text, false); // the functions ++indent_; // constructor if (needs_constructor) { text = name; text += "()"; Write(&text); } // destructor if (type_spec->has_destructor) { text = name; if (has_base) { text.insert(0, "virtual ~"); text += "()"; } else { text.insert(0, "~"); text += "()"; } Write(&text); // if has a destructor, copying is unsafe !! /* text = name; text += "(const "; text += name; text += " &) = delete"; Write(&text); text = name; text += " &operator=(const "; text += name; text += " &) = delete"; Write(&text); */ } // get__id (if inherits from an interface) if (supports_typeswitch) { if (synth_options_->use_override_) { text = "virtual void *get__id() const override { return(&id__); }"; } else { text = "virtual void *get__id() const { return(&id__); }"; } Write(&text); } // user defined int num_functions = SynthClassMemberFunctions(&type_spec->member_functions_, &type_spec->fn_implementors_, type_spec->first_hinherited_member_, true, false); if (num_functions > 0 && (supports_typeswitch || has_public_var)) { EmptyLine(); } // the variables if (supports_typeswitch) { text = "static char id__"; Write(&text); } SynthClassMemberVariables(&type_spec->member_vars_, true); --indent_; if (has_private) { EmptyLine(); string text = "private:"; Write(&text, false); ++indent_; num_functions = SynthClassMemberFunctions(&type_spec->member_functions_, &type_spec->fn_implementors_, type_spec->first_hinherited_member_, false, false); if (num_functions > 0) { EmptyLine(); } SynthClassMemberVariables(&type_spec->member_vars_, false); --indent_; } // close the declaration text = "}"; Write(&text); } void CppSynth::SynthClassHeader(const char *name, vector<AstNamedType*> *bases, bool is_interface) { string text = "class "; text += name; if (!is_interface && synth_options_->use_final_) { text += " final"; } int num_bases = bases->size(); if (num_bases > 0) { string basename; text += " :"; for (int ii = 0; ii < num_bases; ++ii) { basename = ""; SynthTypeSpecification(&basename, (*bases)[ii]); text += " public "; text += basename; if (ii < num_bases - 1) { text += ","; } } } text += " {"; Write(&text, false); } int CppSynth::SynthClassMemberFunctions(vector<FuncDeclaration*> *declarations, vector<string> *implementors, int first_hinerited, bool public_members, bool is_interface) { string text; int num_functions = 0; int top = declarations->size(); // on interfaces there is no need to declare inherited functions if (is_interface) { top = first_hinerited; } for (int ii = 0; ii < top; ++ii) { // filter out FuncDeclaration *func = (*declarations)[ii]; if (func->IsPublic() != public_members) continue; if (func->name_ == "finalize") continue; // declared elsewhere // setup for comments formatter_.SetNodePos(func); // synth ! AstFuncType *ftype = func->function_type_; assert(ftype != nullptr); text = func->name_; SynthFuncTypeSpecification(&text, ftype, true); if (is_interface || ii >= first_hinerited) { text.insert(0, "virtual "); } if (!func->is_muting_) { text += " const"; } if (!is_interface && ii >= first_hinerited && synth_options_->use_override_) { text += " override"; } if (is_interface) { text += " = 0"; } else if ((*implementors)[ii] != "") { SynthFunOpenBrace(text); ++indent_; bool voidfun = ftype->ReturnsVoid(); if (!voidfun) { text = "return("; } else { text = ""; } text +=synth_options_->member_prefix_ + (*implementors)[ii] + synth_options_->member_suffix_ + "." + func->name_ + "("; --split_level_; for (int ii = 0; ii < ftype->arguments_.size(); ++ii) { text += ftype->arguments_[ii]->name_; if (ii < ftype->arguments_.size() - 1) { text += ", "; AddSplitMarker(&text); } } ++split_level_; text += ")"; if (!voidfun) { text += ")"; } Write(&text); --indent_; text = "}"; } Write(&text); ++num_functions; } return(num_functions); } void CppSynth::SynthClassMemberVariables(vector<VarDeclaration*> *d_vector, bool public_members) { string text; int top = d_vector->size(); for (int ii = 0; ii < top; ++ii) { VarDeclaration *declaration = (*d_vector)[ii]; if (declaration->IsPublic() != public_members) continue; formatter_.SetNodePos(declaration); text = ""; AppendMemberName(&text, declaration); SynthTypeSpecification(&text, declaration->GetTypeSpec()); Write(&text); } } void CppSynth::SynthInterfaceDeclaration(const char *name, AstInterfaceType *type_spec) { SynthClassHeader(name, &type_spec->ancestors_, true); string text = "public:"; Write(&text, false); // the functions ++indent_; // virtual destructor and typeswitch support (if not inherited) if (type_spec->ancestors_.size() == 0) { text = "virtual ~"; text += name; text += "() {}"; Write(&text, false); text = "virtual void *get__id() const = 0"; Write(&text); } SynthClassMemberFunctions(&type_spec->members_, nullptr, type_spec->first_hinherited_member_, true, true); --indent_; // close the declaration text = "}"; Write(&text); } void CppSynth::SynthEnumDeclaration(const char *name, AstEnumType *type_spec) { --split_level_; string text = "enum class "; text += name; text += " {"; AddSplitMarker(&text); for (int ii = 0; ii < type_spec->items_.size(); ++ii) { text += type_spec->items_[ii]; if (type_spec->initers_[ii] != nullptr) { string exp; SynthExpression(&exp, type_spec->initers_[ii]); text += " = "; text += exp; } if (ii < type_spec->items_.size() - 1) { text += ", "; AddSplitMarker(&text); } } text += "}"; Write(&text); ++split_level_; } void CppSynth::SynthIniter(string *dst, IAstTypeNode *type_spec, IAstNode *initer) { *dst += " = "; SynthIniterCore(dst, type_spec, initer); } void CppSynth::SynthIniterCore(string *dst, IAstTypeNode *type_spec, IAstNode *initer) { while (type_spec != nullptr && type_spec->GetType() == ANT_NAMED_TYPE) { type_spec = ((AstNamedType*)type_spec)->wp_decl_->type_spec_; } if (initer->GetType() == ANT_INITER) { AstIniter *ast_initer = (AstIniter*)initer; int ii; int oldrow = initer->GetPositionRecord()->start_row; *dst += '{'; if (type_spec->GetType() == ANT_ARRAY_TYPE) { AstArrayType *arraytype = (AstArrayType*)type_spec; for (ii = 0; ii < (int)ast_initer->elements_.size(); ++ii) { IAstNode *element = ast_initer->elements_[ii]; oldrow = AddForcedSplit(dst, element, oldrow); SynthIniterCore(dst, arraytype->element_type_, element); if (ii != (int)ast_initer->elements_.size() - 1) { *dst += ", "; } } } else if (type_spec->GetType() == ANT_MAP_TYPE) { AstMapType *maptype = (AstMapType*)type_spec; IAstNode **element = &ast_initer->elements_[0]; for (ii = (int)ast_initer->elements_.size() >> 1; ii > 0; --ii) { oldrow = AddForcedSplit(dst, element[0], oldrow); *dst += "{"; SynthIniterCore(dst, maptype->key_type_, element[0]); *dst += ", "; SynthIniterCore(dst, maptype->returned_type_, element[1]); *dst += "}"; if (ii != 1) { *dst += ", "; } element += 2; } } if (initer->GetPositionRecord()->last_row > oldrow) { *dst += 0xff; } *dst += '}'; } else { string exp; SynthFullExpression(type_spec, &exp, (IAstExpNode*)initer); *dst += exp; } } void CppSynth::SynthZeroIniter(string *dst, IAstTypeNode *type_spec) { *dst = ""; switch (type_spec->GetType()) { case ANT_BASE_TYPE: switch (((AstBaseType*)type_spec)->base_type_) { default: *dst = "0"; break; case TOKEN_COMPLEX64: case TOKEN_COMPLEX128: case TOKEN_STRING: break; case TOKEN_BOOL: *dst = "false"; break; } break; case ANT_NAMED_TYPE: SynthZeroIniter(dst, ((AstNamedType*)type_spec)->wp_decl_->type_spec_); break; case ANT_FUNC_TYPE: *dst = "nullptr"; break; case ANT_ENUM_TYPE: { AstEnumType *etype = (AstEnumType*)type_spec; *dst = etype->name_ + "::" + etype->items_[0]; int pkg_idx = etype->GetPositionRecord()->package_idx; if (pkg_idx > 0) { string partial = *dst; GetFullExternName(dst, pkg_idx, partial.c_str()); } } break; case ANT_ARRAY_TYPE: if (!((AstArrayType*)type_spec)->is_dynamic_) { SynthZeroIniter(dst, ((AstArrayType*)type_spec)->element_type_); if ((*dst)[0] != 0) { dst->insert(0, "{"); *dst += "}"; } } break; default: break; } } void CppSynth::SynthBlock(AstBlock *block, bool write_closing_bracket) { int ii; AstNodeType oldtype = ANT_BLOCK; // init so that SynthStatementOrAutoVar doesn't place an empty line. ++indent_; for (ii = 0; ii < (int)block->block_items_.size(); ++ii) { SynthStatementOrAutoVar(block->block_items_[ii], &oldtype); } --indent_; if (write_closing_bracket) { string text = "}"; Write(&text, false); } } void CppSynth::SynthStatementOrAutoVar(IAstNode *node, AstNodeType *oldtype) { string text; AstNodeType type; type = node->GetType(); formatter_.SetNodePos(node, type != ANT_VAR && type != ANT_BLOCK); // place an empty line before the first non-var statement following one or more var declarations // if (oldtype != nullptr) { // if (type != ANT_VAR && *oldtype == ANT_VAR) { // EmptyLine(); // } // *oldtype = type; // } switch (type) { case ANT_VAR: SynthVar((VarDeclaration*)node); break; case ANT_UPDATE: SynthUpdateStatement((AstUpdate*)node); break; case ANT_INCDEC: SynthIncDec((AstIncDec*)node); break; case ANT_SWAP: SynthSwap((AstSwap*)node); break; case ANT_WHILE: SynthWhile((AstWhile*)node); break; case ANT_IF: SynthIf((AstIf*)node); break; case ANT_FOR: SynthFor((AstFor*)node); break; case ANT_SIMPLE: SynthSimpleStatement((AstSimpleStatement*)node); break; case ANT_RETURN: SynthReturn((AstReturn*)node); break; case ANT_TRY: SynthTry((AstTry*)node); break; case ANT_FUNCALL: text = ""; SynthFunCall(&text, (AstFunCall*)node); Write(&text, true); break; case ANT_SWITCH: SynthSwitch((AstSwitch*)node); break; case ANT_TYPESWITCH: SynthTypeSwitch((AstTypeSwitch*)node); break; case ANT_BLOCK: text = "{"; Write(&text, false); SynthBlock((AstBlock*)node); break; } } void CppSynth::SynthUpdateStatement(AstUpdate *node) { string full; string expression; const ExpressionAttributes *left_attr = node->left_term_->GetAttr(); const ExpressionAttributes *right_attr = node->right_term_->GetAttr(); // copying a static vector to a dynamic one ? if (left_attr->IsArray() && ((AstArrayType*)left_attr->GetTypeTree())->is_dynamic_ && !((AstArrayType*)right_attr->GetTypeTree())->is_dynamic_) { --split_level_; SynthExpression(&expression, node->left_term_); full = "sing::copy_array_to_vec("; AddSplitMarker(&full); full += expression; expression = ""; SynthExpression(&expression, node->right_term_); full += ", "; AddSplitMarker(&full); full += expression; full += ")"; ++split_level_; } else if (left_attr->IsWeakPointer() && right_attr->IsLiteralNull()) { int priority = SynthExpression(&full, node->left_term_); Protect(&full, priority, GetBinopCppPriority(TOKEN_DOT)); full += ".reset()"; } else { SynthExpression(&full, node->left_term_); full += ' '; full += Lexer::GetTokenString(node->operation_); full += ' '; SynthFullExpression(left_attr, &expression, node->right_term_); full += expression; } Write(&full); } void CppSynth::SynthIncDec(AstIncDec *node) { int priority; string text; priority = SynthExpression(&text, node->left_term_); Protect(&text, priority, GetUnopCppPriority(node->operation_)); text.insert(0, Lexer::GetTokenString(node->operation_)); Write(&text); } void CppSynth::SynthSwap(AstSwap *node) { string text, expression; --split_level_; text = "std::swap("; AddSplitMarker(&text); SynthExpression(&expression, node->left_term_); text += expression; text += ", "; AddSplitMarker(&text); expression = ""; SynthExpression(&expression, node->right_term_); text += expression; text += ")"; Write(&text); ++split_level_; } void CppSynth::SynthWhile(AstWhile *node) { string text; SynthExpression(&text, node->expression_); text.insert(0, "while ("); text += ") {"; Write(&text, false); SynthBlock(node->block_); } void CppSynth::SynthIf(AstIf *node) { string text; int ii; // check: types compatibility (annotate the node). SynthExpression(&text, node->expressions_[0]); text.insert(0, "if ("); text += ") {"; Write(&text, false); SynthBlock(node->blocks_[0], false); for (ii = 1; ii < (int)node->expressions_.size(); ++ii) { text = ""; SynthExpression(&text, node->expressions_[ii]); text.insert(0, "} else if ("); text += ") {"; Write(&text, false); SynthBlock(node->blocks_[ii], false); } if (node->default_block_ != NULL) { text = "} else {"; Write(&text, false); SynthBlock(node->default_block_, false); } text = "}"; Write(&text, false); } void CppSynth::SynthSwitch(AstSwitch *node) { string text; --split_level_; SynthExpression(&text, node->switch_value_); text.insert(0, "switch ("); text += ") {"; Write(&text, false); int cases = 0; for (int ii = 0; ii < (int)node->statements_.size(); ++ii) { int top_case = node->statement_top_case_[ii]; if (top_case == cases) { text = "default:"; Write(&text, false); } else { while (cases < top_case) { IAstExpNode *clause = node->case_values_[cases]; if (clause != nullptr) { SynthExpression(&text, clause); text.insert(0, "case "); text += ": "; Write(&text, false); } ++cases; } } IAstNode *statement = node->statements_[ii]; ++indent_; if (statement != nullptr) { SynthStatementOrAutoVar(statement, nullptr); } text = "break"; Write(&text); --indent_; } text = "}"; ++split_level_; Write(&text, false); } void CppSynth::SynthTypeSwitch(AstTypeSwitch *node) { string text, switch_exp, tocompare, tempbuf; int exppri = SynthExpression(&switch_exp, node->expression_); tocompare = switch_exp; if (node->on_interface_ptr_) { Protect(&tocompare, exppri, GetUnopCppPriority(TOKEN_MPY)); tocompare.insert(0, "(*"); tocompare += ").get__id() == &"; } else { Protect(&tocompare, exppri, GetBinopCppPriority(TOKEN_DOT)); tocompare += ".get__id() == &"; } if (node->on_interface_ptr_) { text = "if (!"; text += switch_exp; // no need to protect: a leftvalue doesn't include binops. text += ") {"; Write(&text, false); } for (int ii = 0; ii < node->case_types_.size(); ++ii) { IAstTypeNode *clause = node->case_types_[ii]; IAstNode *statement = node->case_statements_[ii]; bool needs_reference = node->uses_reference_[ii]; string clause_typename; if (clause == nullptr) { if (statement != nullptr) { assert(ii != 0); text = "} else {"; Write(&text, false); } } else { if (ii == 0 && !node->on_interface_ptr_) { text = "if ("; } else { text = "} else if ("; } text += tocompare; if (node->on_interface_ptr_) { IAstTypeNode *solved = SolveTypedefs(clause); if (solved->GetType() == ANT_POINTER_TYPE) { SynthTypeSpecification(&clause_typename, ((AstPointerType*)solved)->pointed_type_); } } else { SynthTypeSpecification(&clause_typename, clause); } text += clause_typename; text += "::id__) {"; Write(&text, false); } if (statement != nullptr) { ++indent_; // init the reference if (needs_reference) { if (node->on_interface_ptr_) { // es: std::shared_ptr<Derived> localname(p04, (Derived*)p04.get()); text = "std::shared_ptr<"; text += clause_typename; text += "> "; text += node->reference_->name_; text += "("; text += switch_exp; text += ", ("; text += clause_typename; text += "*)"; tempbuf = switch_exp; Protect(&tempbuf, exppri, GetBinopCppPriority(TOKEN_DOT)); text += tempbuf; text += ".get())"; } else { // es: Derived &localname = *(Derived *)&inparm; text = clause_typename; text += " &"; text += node->reference_->name_; text += " = *("; text += clause_typename; text += " *)&"; text += switch_exp; } Write(&text); } // this is all about avoiding double {} if (statement->GetType() == ANT_BLOCK) { --indent_; SynthBlock((AstBlock*)statement, false); ++indent_; } else { SynthStatementOrAutoVar(statement, nullptr); } --indent_; } } text = "}"; Write(&text, false); } void CppSynth::SynthFor(AstFor *node) { string text; // declare or init the index // (can't do in the init clause of the for because it is a declaration, not a statement !! if (node->index_ != nullptr) { if (!node->index_referenced_) { text = "int64_t "; text += node->index_->name_; } else { text = node->index_->name_; } if (node->set_ != nullptr) { text += " = -1"; } else { text += " = 0"; } Write(&text); } if (node->set_ != nullptr) { SynthForEachOnDyna(node); } else { SynthForIntRange(node); } } void CppSynth::SynthForEachOnDyna(AstFor *node) { string expression, text; text = "for(auto &"; text += node->iterator_->name_; text += " : "; SynthExpression(&expression, node->set_); text += expression; text += ") {"; Write(&text, false); if (debug_) { ++indent_; WriteReferenceGuard(node->iterator_->name_.c_str(), true); --indent_; } if (node->index_ != nullptr) { ++indent_; text = "++"; text += node->index_->name_; Write(&text); --indent_; } SynthBlock(node->block_); } void CppSynth::SynthForIntRange(AstFor *node) { string text, aux, top_exp; const ExpressionAttributes *attr_low = node->low_->GetAttr(); const ExpressionAttributes *attr_high = node->high_->GetAttr(); bool use_top_var = !attr_high->HasKnownValue(); bool use_step_var = (node->step_value_ == 0); // is 0 when unknown at compile time (not literal) assert(node->iterator_->GetTypeSpec()->GetType() == ANT_BASE_TYPE); bool using_64_bits = ((AstBaseType*)node->iterator_->GetTypeSpec())->base_type_ == TOKEN_INT64; --split_level_; text = "for("; AddSplitMarker(&text); // declaration of iterator aux = node->iterator_->name_; SynthTypeSpecification(&aux, node->iterator_->GetTypeSpec()); text += aux; text += " = "; SynthExpressionAndCastToInt(&aux, node->low_, using_64_bits); text += aux; // init clause includes declaration of high/step backing variables, index and interator if (use_top_var) { text += ", "; text += node->iterator_->name_; text += "__top = "; SynthExpressionAndCastToInt(&aux, node->high_, using_64_bits); text += aux; } if (use_step_var) { text += ", "; text += node->iterator_->name_; text += "__step = "; SynthExpressionAndCastToInt(&aux, node->step_, using_64_bits); text += aux; } text += "; "; AddSplitMarker(&text); // end of loop clause. if (use_top_var) { top_exp = node->iterator_->name_; top_exp += "__top"; } else { SynthExpressionAndCastToInt(&top_exp, node->high_, using_64_bits); } if (use_step_var) { text += node->iterator_->name_; text += "__step > 0 ? ("; text += node->iterator_->name_; text += " < "; text += top_exp; text += ") : ("; text += node->iterator_->name_; text += " > "; text += top_exp; text += "); "; } else { text += node->iterator_->name_; text += node->step_value_ > 0 ? " < " : " > "; text += top_exp; text += "; "; } AddSplitMarker(&text); // increment clause if (node->step_value_ == 1) { text += "++"; text += node->iterator_->name_; } else if (node->step_value_ == -1) { text += "--"; text += node->iterator_->name_; } else { text += node->iterator_->name_; text += " += "; if (use_step_var) { text += node->iterator_->name_; text += "__step"; } else { SynthExpressionAndCastToInt(&aux, node->step_, using_64_bits); text += aux; } } if (node->index_ != NULL) { text += ", ++"; text += node->index_->name_; } // close and write down text += ") {"; Write(&text, false); ++split_level_; SynthBlock(node->block_); } void CppSynth::SynthExpressionAndCastToInt(string *dst, IAstExpNode *node, bool use_int64) { int priority; *dst = ""; priority = SynthExpression(dst, node); Token target = use_int64 ? TOKEN_INT64 : TOKEN_INT32; CastIfNeededTo(target, node->GetAttr()->GetAutoBaseType(), dst, priority, false); } void CppSynth::SynthSimpleStatement(AstSimpleStatement *node) { // check: is in an inner block who is continuable/breakable ? string text = Lexer::GetTokenString(node->subtype_); Write(&text); } void CppSynth::SynthReturn(AstReturn *node) { string text; if (node->retvalue_ != nullptr) { SynthFullExpression(return_type_, &text, node->retvalue_); text.insert(0, "return ("); text += ")"; } else { text = "return"; } Write(&text); } void CppSynth::SynthTry(AstTry *node) { string text; bool not_optimization = false; if (node->tried_->GetType() == ANT_UNOP) { AstUnop *op = (AstUnop*)node->tried_; if (op->subtype_ == TOKEN_LOGICAL_NOT) { SynthExpression(&text, op->operand_); not_optimization = true; } } if (!not_optimization) { int priority = SynthExpression(&text, node->tried_); Protect(&text, priority, GetUnopCppPriority(TOKEN_LOGICAL_NOT)); text.insert(0, "!"); } text.insert(0, "if ("); text += ") return(false)"; Write(&text); } // // Adds a final conversion in view of the assignment. Sing allows some numeric conversions c++ doesn't: // - If the value is a compile time constant and fits the target value. // - if the conversion is not narrowing but the target is a complex and the source is not a value of same precision. // // You DONT' need SynthFullExpression() if: // - the espression is strictly constant (recognized as such by legacy C compilers), currently: // - enum case initers // - array size // - left terms (or in general if the value is not the source for a write) // - values that are known not being numerics (es. typeswitch expression) // - values that are required to be integers (not automatically downcasted, even if constant: indices) // - consider SynthExpressionAndCastToInt() for values that are known to be signed ints; // int CppSynth::SynthFullExpression(const IAstTypeNode *type_spec, string *dst, IAstExpNode *node) { int priority; priority = SynthExpression(dst, node); if (type_spec != nullptr) { type_spec = SolveTypedefs(type_spec); if (type_spec->GetType() == ANT_POINTER_TYPE && !((AstPointerType*)type_spec)->isweak_ && node->GetAttr()->IsWeakPointer()) { int newpriority = GetBinopCppPriority(TOKEN_DOT); Protect(dst, priority, newpriority); priority = newpriority; *dst += ".lock()"; } else { Token base = GetBaseType(type_spec); if (base != TOKENS_COUNT) { priority = CastIfNeededTo(base, node->GetAttr()->GetAutoBaseType(), dst, priority, false); } } } return(priority); } int CppSynth::SynthFullExpression(const ExpressionAttributes *attr, string *dst, IAstExpNode *node) { int priority; priority = SynthExpression(dst, node); if (attr != nullptr) { if (attr->IsStrongPointer() && node->GetAttr()->IsWeakPointer()) { int newpriority = GetBinopCppPriority(TOKEN_DOT); Protect(dst, priority, newpriority); priority = newpriority; *dst += ".lock()"; } else { Token target_type = attr->GetAutoBaseType(); if (target_type != TOKENS_COUNT) { priority = CastIfNeededTo(target_type, node->GetAttr()->GetAutoBaseType(), dst, priority, false); } } } return(priority); } // TODO: split on more lines int CppSynth::SynthExpression(string *dst, IAstExpNode *node) { int priority = 0; switch (node->GetType()) { case ANT_INDEXING: priority = SynthIndices(dst, (AstIndexing*)node); break; case ANT_FUNCALL: priority = SynthFunCall(dst, (AstFunCall*) node); break; case ANT_BINOP: priority = SynthBinop(dst, (AstBinop*)node); break; case ANT_UNOP: priority = SynthUnop(dst, (AstUnop*)node); break; case ANT_EXP_LEAF: priority = SynthLeaf(dst, (AstExpressionLeaf*)node); break; } return(priority); } int CppSynth::SynthIndices(string *dst, AstIndexing *node) { string expression; int priority; int exp_pri = SynthExpression(dst, node->indexed_term_); int index_pri = SynthExpression(&expression, node->lower_value_); if (node->lower_value_->GetAttr()->IsEnum()) { AddCast(&expression, index_pri, "size_t"); } if (debug_) { priority = GetUnopCppPriority(TOKEN_DOT); Protect(dst, exp_pri, priority); *dst += ".at("; *dst += expression; *dst += ')'; } else { priority = GetUnopCppPriority(TOKEN_SQUARE_OPEN); Protect(dst, exp_pri, priority); *dst += '['; *dst += expression; *dst += ']'; } return(priority); } int CppSynth::SynthFunCall(string *dst, AstFunCall *node) { int ii, priority; int numargs = (int)node->arguments_.size(); string expression; bool builtin = false; if (node->left_term_->GetType() == ANT_BINOP) { AstBinop *bnode = (AstBinop*)node->left_term_; builtin = bnode->builtin_ != nullptr; } --split_level_; priority = SynthExpression(dst, node->left_term_); if (builtin) { // fun call alredy synthesized in SynthDotOp() but is missing the arguments dst->erase(dst->length() - 1); // just delete ')' - reopen the arg list bool has_already_args = (*dst)[dst->length() - 1] != '('; if (has_already_args && numargs > 0) { // separate the two groups *dst += ", "; } if (has_already_args || numargs > 0) { AddSplitMarker(dst); // has at least an arg. } } else { Protect(dst, priority, GetUnopCppPriority(TOKEN_ROUND_OPEN)); *dst += '('; if (numargs > 0) { AddSplitMarker(dst); // has at least an arg. } } for (ii = 0; ii < numargs; ++ii) { VarDeclaration *var = node->func_type_->arguments_[ii]; IAstExpNode *expression_node = node->arguments_[ii]->expression_; expression = ""; int priority = SynthFullExpression(var->GetTypeSpec(), &expression, expression_node); ParmPassingMethod ppm = GetParameterPassingMethod(var->GetTypeSpec(), var->HasOneOfFlags(VF_READONLY)); if (ppm == PPM_POINTER) { // passed by pointer: get the address (or simplify *this) //if (expression[0] == '*') { // note: can't do this if * is to access an item pointed by a shared pointer. if (expression == "*this") { expression.erase(0, 1); } else if (expression != "nullptr") { // note: optouts can be set to nullptr. expression.insert(0, "&"); } } else if (ppm == PPM_INPUT_STRING && !IsInputArg(expression_node) && !IsLiteralString(expression_node)) { Protect(&expression, priority, GetBinopCppPriority(TOKEN_DOT)); expression += ".c_str()"; } if (ii != 0) { *dst += ", "; AddSplitMarker(dst); } *dst += expression; } *dst += ')'; ++split_level_; return(GetUnopCppPriority(TOKEN_ROUND_OPEN)); } int CppSynth::SynthBinop(string *dst, AstBinop *node) { int priority = 0; switch (node->subtype_) { case TOKEN_DOT: priority = SynthDotOperator(dst, node); break; case TOKEN_POWER: priority = SynthPowerOperator(dst, node); break; case TOKEN_MPY: case TOKEN_DIVIDE: case TOKEN_PLUS: case TOKEN_MINUS: case TOKEN_MOD: case TOKEN_SHR: case TOKEN_AND: case TOKEN_SHL: case TOKEN_OR: case TOKEN_XOR: case TOKEN_MIN: case TOKEN_MAX: --split_level_; priority = SynthMathOperator(dst, node); ++split_level_; break; case TOKEN_ANGLE_OPEN_LT: case TOKEN_ANGLE_CLOSE_GT: case TOKEN_GTE: case TOKEN_LTE: case TOKEN_DIFFERENT: case TOKEN_EQUAL: --split_level_; priority = SynthRelationalOperator(dst, node); ++split_level_; break; case TOKEN_LOGICAL_AND: case TOKEN_LOGICAL_OR: --split_level_; priority = SynthLogicalOperator(dst, node); ++split_level_; break; default: // ops !! assert(false); break; } return(priority); } int CppSynth::SynthDotOperator(string *dst, AstBinop *node) { int priority = GetBinopCppPriority(TOKEN_DOT); assert(node->operand_right_->GetType() == ANT_EXP_LEAF); AstExpressionLeaf* right_leaf = (AstExpressionLeaf*)node->operand_right_; // is a package resolution operator or 'this' ? int pkg_index = -1; if (node->operand_left_->GetType() == ANT_EXP_LEAF) { AstExpressionLeaf* left_leaf = (AstExpressionLeaf*)node->operand_left_; pkg_index = left_leaf->pkg_index_; if (pkg_index >= 0) { GetFullExternName(dst, pkg_index, right_leaf->value_.c_str()); return(KLeafPriority); } else if (left_leaf->subtype_ == TOKEN_THIS) { if (!right_leaf->unambiguous_member_access) { *dst = "this->"; } AppendMemberName(dst, right_leaf->wp_decl_); return(priority); } } priority = SynthExpression(dst, node->operand_left_); const ExpressionAttributes *left_attr = node->operand_left_->GetAttr(); if (left_attr->IsEnum()) { *dst += "::"; *dst += right_leaf->value_; priority = KLeafPriority; } else if (node->builtin_ != nullptr) { if (left_attr->IsPointer()) { Protect(dst, priority, GetUnopCppPriority(TOKEN_MPY)); dst->insert(0, "*"); priority = GetUnopCppPriority(TOKEN_MPY); } BInSynthMode builtin_mode = GetBuiltinSynthMode(node->builtin_signature_); switch (builtin_mode) { case BInSynthMode::sing: dst->insert(0, "("); dst->insert(0, right_leaf->value_); dst->insert(0, "sing::"); (*dst) += ")"; priority = GetUnopCppPriority(TOKEN_ROUND_OPEN); break; case BInSynthMode::std: dst->insert(0, "("); dst->insert(0, right_leaf->value_); dst->insert(0, "std::"); (*dst) += ")"; priority = GetUnopCppPriority(TOKEN_ROUND_OPEN); break; case BInSynthMode::cast: case BInSynthMode::plain: { dst->insert(0, "("); dst->insert(0, right_leaf->value_); if (root_->namespace_.length() > 0) { dst->insert(0, "::"); } (*dst) += ")"; priority = GetUnopCppPriority(TOKEN_ROUND_OPEN); Token base_type = node->operand_left_->GetAttr()->GetAutoBaseType(); if (base_type != TOKEN_FLOAT64 && builtin_mode != BInSynthMode::plain) { priority = AddCast(dst, priority, GetBaseTypeName(base_type)); } } break; case BInSynthMode::member: default: Protect(dst, priority, GetBinopCppPriority(TOKEN_DOT)); (*dst) += "."; (*dst) += right_leaf->value_; (*dst) += "()"; priority = GetUnopCppPriority(TOKEN_ROUND_OPEN); break; } } else { if (left_attr->IsPointer()) { Protect(dst, priority, GetUnopCppPriority(TOKEN_MPY)); dst->insert(0, "(*"); *dst += ")."; } else { // ANT_CLASS_TYPE Protect(dst, priority, GetBinopCppPriority(TOKEN_DOT)); *dst += "."; } AppendMemberName(dst, right_leaf->wp_decl_); priority = GetBinopCppPriority(TOKEN_DOT); } return(priority); } int CppSynth::SynthPowerOperator(string *dst, AstBinop *node) { string right; int priority = GetBinopCppPriority(node->subtype_); int left_priority = SynthExpression(dst, node->operand_left_); int right_priority = SynthExpression(&right, node->operand_right_); const ExpressionAttributes *left_attr = node->operand_left_->GetAttr(); const ExpressionAttributes *right_attr = node->operand_right_->GetAttr(); const ExpressionAttributes *result_attr = node->GetAttr(); const NumericValue *right_value = right_attr->GetValue(); Token left_type = left_attr->GetAutoBaseType(); Token right_type = right_attr->GetAutoBaseType(); Token result_type = result_attr->GetAutoBaseType(); // pow2 ? if (right_attr->HasKnownValue() && !right_value->IsComplex() && right_value->GetDouble() == 2) { if (left_type != result_type) { left_priority = AddCast(dst, left_priority, GetBaseTypeName(result_type)); } dst->insert(0, "sing::pow2("); *dst += ")"; return(priority); } else { if (ExpressionAttributes::BinopRequiresNumericConversion(left_attr, right_attr, TOKEN_POWER)) { assert(false); // since we do no authomatic conversion if (left_type != result_type) { left_priority = AddCast(dst, left_priority, GetBaseTypeName(result_type)); } if (right_type != result_type) { right_priority = AddCast(&right, right_priority, GetBaseTypeName(result_type)); } } else { left_priority = PromoteToInt32(left_type, dst, left_priority); } if (result_attr->IsInteger()) { dst->insert(0, "sing::pow("); } else { dst->insert(0, "std::pow("); } *dst += ", "; *dst += right; *dst += ")"; } return(priority); } int CppSynth::SynthMathOperator(string *dst, AstBinop *node) { string right; const ExpressionAttributes *left_attr = node->operand_left_->GetAttr(); const ExpressionAttributes *right_attr = node->operand_right_->GetAttr(); const ExpressionAttributes *result_attr = node->GetAttr(); Token left_type = left_attr->GetAutoBaseType(); Token right_type = right_attr->GetAutoBaseType(); Token result_type = result_attr->GetAutoBaseType(); if (node->subtype_ == TOKEN_PLUS && left_type == TOKEN_STRING && right_type == TOKEN_STRING) { string format, parms; ProcessStringSumOperand(&format, &parms, node->operand_left_); ProcessStringSumOperand(&format, &parms, node->operand_right_); bool left_is_literal = IsLiteralString(node->operand_left_); bool right_is_literal = IsLiteralString(node->operand_right_); bool left_is_const_char = left_is_literal || IsInputArg(node->operand_left_); bool right_is_const_char = right_is_literal || IsInputArg(node->operand_right_); if (format != "%s%s" || left_is_const_char && right_is_const_char) { if (left_is_literal && right_is_literal) { *dst += ((AstExpressionLeaf*)node->operand_left_)->value_; *dst += ' '; *dst += ((AstExpressionLeaf*)node->operand_right_)->value_; return(KForcedPriority); } else { *dst = "sing::s_format(\""; *dst += format; *dst += "\""; *dst += parms; *dst += ")"; return(KForcedPriority); } } // else can simply use the + operator. } int priority = GetBinopCppPriority(node->subtype_); int left_priority = SynthExpression(dst, node->operand_left_); int right_priority = SynthExpression(&right, node->operand_right_); if (ExpressionAttributes::BinopRequiresNumericConversion(left_attr, right_attr, node->subtype_)) { assert(false); // since we do no authomatic conversion if (left_type != result_type) { left_priority = CastIfNeededTo(result_type, left_type, dst, left_priority, false); } if (right_type != result_type) { right_priority = CastIfNeededTo(result_type, right_type, &right, right_priority, false); } } // add brackets if needed Protect(dst, left_priority, priority); Protect(&right, right_priority, priority, true); // sinthesize the operation if (node->subtype_ == TOKEN_MIN || node->subtype_ == TOKEN_MAX) { if (node->subtype_ == TOKEN_MIN) { dst->insert(0, "std::min("); } else { dst->insert(0, "std::max("); } *dst += ", "; AddSplitMarker(dst); *dst += right; *dst += ')'; } else { if (node->subtype_ == TOKEN_XOR) { *dst += " ^ "; } else { *dst += ' '; *dst += Lexer::GetTokenString(node->subtype_); *dst += ' '; } AddSplitMarker(dst); *dst += right; } return(priority); } int CppSynth::SynthRelationalOperator(string *dst, AstBinop *node) { return(SynthRelationalOperator3(dst, node->subtype_, node->operand_left_, node->operand_right_)); } int CppSynth::SynthRelationalOperator3(string *dst, Token subtype, IAstExpNode *operand_left, IAstExpNode *operand_right) { string right; int priority = GetBinopCppPriority(subtype); int left_priority = SynthExpression(dst, operand_left); int right_priority = SynthExpression(&right, operand_right); const ExpressionAttributes *left_attr = operand_left->GetAttr(); const ExpressionAttributes *right_attr = operand_right->GetAttr(); Token left_type = left_attr->GetAutoBaseType(); Token right_type = right_attr->GetAutoBaseType(); if (left_attr->IsInteger() && right_attr->IsInteger()) { // use special function in case of signed-unsigned comparison bool left_is_uint64 = left_type == TOKEN_UINT64; bool right_is_uint64 = right_type == TOKEN_UINT64; bool left_is_int64 = left_type == TOKEN_INT64; bool right_is_int64 = right_type == TOKEN_INT64; bool left_is_uint32 = left_type == TOKEN_UINT32; bool right_is_uint32 = right_type == TOKEN_UINT32; bool left_is_int32 = left_type == TOKEN_INT32 || left_attr->RequiresPromotion(); bool right_is_int32 = right_type == TOKEN_INT32 || right_attr->RequiresPromotion(); bool use_function = left_is_uint64 && right_is_int64 || left_is_uint64 && right_is_int32 || left_is_uint32 && right_is_int32; bool use_function_swap = right_is_uint64 && left_is_int64 || right_is_uint64 && left_is_int32 || right_is_uint32 && left_is_int32; if (use_function) { switch (subtype) { case TOKEN_ANGLE_OPEN_LT: dst->insert(0, "sing::isless("); break; case TOKEN_ANGLE_CLOSE_GT: dst->insert(0, "sing::ismore("); break; case TOKEN_GTE: dst->insert(0, "sing::ismore_eq("); break; case TOKEN_LTE: dst->insert(0, "sing::isless_eq("); break; case TOKEN_DIFFERENT: dst->insert(0, "!sing::iseq("); break; case TOKEN_EQUAL: dst->insert(0, "sing::iseq("); break; } *dst += ", "; AddSplitMarker(dst); *dst += right; *dst += ")"; return(subtype == TOKEN_DIFFERENT ? GetUnopCppPriority(TOKEN_LOGICAL_NOT) : KForcedPriority); } if (use_function_swap) { switch (subtype) { case TOKEN_ANGLE_OPEN_LT: right.insert(0, "sing::ismore("); break; case TOKEN_ANGLE_CLOSE_GT: right.insert(0, "sing::isless("); break; case TOKEN_GTE: right.insert(0, "sing::isless_eq("); break; case TOKEN_LTE: right.insert(0, "sing::ismore_eq("); break; case TOKEN_DIFFERENT: right.insert(0, "!sing::iseq("); break; case TOKEN_EQUAL: right.insert(0, "sing::iseq("); break; } right += ", "; AddSplitMarker(&right); dst->insert(0, right); *dst += ")"; return(subtype == TOKEN_DIFFERENT ? GetUnopCppPriority(TOKEN_LOGICAL_NOT) : KForcedPriority); } } else if (left_attr->IsNumber()) { CastForRelational(left_type, right_type, dst, &right, &left_priority, &right_priority); } else if (left_attr->IsString() && right_attr->IsString()) { if (IsLiteralString(operand_left) || IsInputArg(operand_left)) { if (IsLiteralString(operand_right) || IsInputArg(operand_right)) { dst->insert(0, "::strcmp("); *dst += ", "; *dst += right; *dst += ") "; *dst += Lexer::GetTokenString(subtype); *dst += " 0"; return(priority); } } } // add brackets if needed Protect(dst, left_priority, priority); Protect(&right, right_priority, priority, true); // sinthesize the operation *dst += ' '; *dst += Lexer::GetTokenString(subtype); *dst += ' '; AddSplitMarker(dst); *dst += right; return(priority); } int CppSynth::SynthLogicalOperator(string *dst, AstBinop *node) { string right; int priority = GetBinopCppPriority(node->subtype_); int left_priority = SynthExpression(dst, node->operand_left_); int right_priority = SynthExpression(&right, node->operand_right_); // add brackets if needed Protect(dst, left_priority, priority); Protect(&right, right_priority, priority, true); // sinthesize the operation *dst += ' '; *dst += Lexer::GetTokenString(node->subtype_); *dst += ' '; AddSplitMarker(dst); *dst += right; return(priority); } int CppSynth::SynthUnop(string *dst, AstUnop *node) { int exp_priority, priority; if (node->subtype_ == TOKEN_SIZEOF) { priority = KForcedPriority; } else { priority = 3; } if (node->operand_ != nullptr) { exp_priority = SynthExpression(dst, node->operand_); } switch (node->subtype_) { case TOKEN_SIZEOF: if (node->type_ != NULL) { SynthTypeSpecification(dst, node->type_); } dst->insert(0, "sizeof("); *dst += ')'; break; case TOKEN_MINUS: Protect(dst, exp_priority, priority); dst->insert(0, "-"); break; case TOKEN_NOT: Protect(dst, exp_priority, priority); dst->insert(0, "~"); break; case TOKEN_AND: Protect(dst, exp_priority, priority); if ((*dst)[0] == '*') { dst->erase(0, 1); } else { dst->insert(0, "&"); } break; case TOKEN_MPY: Protect(dst, exp_priority, priority); if ((*dst)[0] == '&') { dst->erase(0, 1); } else { dst->insert(0, "*"); } break; case TOKEN_PLUS: case TOKEN_LOGICAL_NOT: Protect(dst, exp_priority, priority); dst->insert(0, Lexer::GetTokenString(node->subtype_)); break; case TOKEN_INT8: case TOKEN_INT16: case TOKEN_INT32: case TOKEN_INT64: case TOKEN_UINT8: case TOKEN_UINT16: case TOKEN_UINT32: case TOKEN_UINT64: case TOKEN_FLOAT32: case TOKEN_FLOAT64: priority = SynthCastToScalar(dst, node, exp_priority); break; case TOKEN_COMPLEX64: case TOKEN_COMPLEX128: priority = SynthCastToComplex(dst, node, exp_priority); break; case TOKEN_STRING: priority = SynthCastToString(dst, node); break; case TOKEN_DEF: priority = GetBinopCppPriority(TOKEN_EQUAL); dst->erase(0, 1); // legal args of def are variables requiring indirection: delete '*' // Protect(dst, exp_priority, priority); // no need - exp can only be a single name *dst += " != nullptr"; break; } return(priority); } int CppSynth::SynthCastToScalar(string *dst, AstUnop *node, int priority) { const ExpressionAttributes *src_attr; bool explicit_cast = true; src_attr = node->operand_->GetAttr(); if (src_attr->HasComplexType()) { Protect(dst, priority, GetBinopCppPriority(TOKEN_DOT)); *dst += ".real()"; priority = GetBinopCppPriority(TOKEN_DOT); if (src_attr->GetAutoBaseType() == TOKEN_COMPLEX64) { explicit_cast = node->subtype_ != TOKEN_FLOAT32; } else { explicit_cast = node->subtype_ != TOKEN_FLOAT64; } } else if (src_attr->IsString()) { switch (node->subtype_) { case TOKEN_INT8: case TOKEN_INT16: case TOKEN_INT32: case TOKEN_INT64: dst->insert(0, "sing::string2int("); *dst += ")"; priority = KForcedPriority; explicit_cast = node->subtype_ != TOKEN_INT64; break; case TOKEN_UINT8: case TOKEN_UINT16: case TOKEN_UINT32: case TOKEN_UINT64: dst->insert(0, "sing::string2uint("); *dst += ")"; priority = KForcedPriority; explicit_cast = node->subtype_ != TOKEN_UINT64; break; case TOKEN_FLOAT32: case TOKEN_FLOAT64: dst->insert(0, "sing::string2double("); *dst += ")"; priority = KForcedPriority; explicit_cast = node->subtype_ != TOKEN_FLOAT64; break; } } if (explicit_cast) { priority = AddCast(dst, priority, GetBaseTypeName(node->subtype_)); } return(priority); } int CppSynth::SynthCastToComplex(string *dst, AstUnop *node, int priority) { const ExpressionAttributes *src_attr; src_attr = node->operand_->GetAttr(); if (src_attr->HasComplexType()) { Token src_type = src_attr->GetAutoBaseType(); if (src_attr->GetAutoBaseType() == TOKEN_COMPLEX64 && node->subtype_ == TOKEN_COMPLEX128) { dst->insert(0, "sing::c_f2d("); } else if (src_attr->GetAutoBaseType() == TOKEN_COMPLEX128 && node->subtype_ == TOKEN_COMPLEX64) { dst->insert(0, "sing::c_d2f("); } *dst += ")"; } else if (src_attr->IsString()) { if (node->subtype_ == TOKEN_COMPLEX128) { dst->insert(0, "sing::string2complex128("); } else { dst->insert(0, "sing::string2complex64("); } *dst += ")"; priority = KForcedPriority; } else { Token src_type = src_attr->GetAutoBaseType(); if (node->subtype_ == TOKEN_COMPLEX128) { if (src_type == TOKEN_INT64 || src_type == TOKEN_UINT64) { priority = AddCast(dst, priority, "double"); } priority = AddCast(dst, priority, "std::complex<double>"); } else { if (src_type == TOKEN_INT64 || src_type == TOKEN_UINT64 || src_type == TOKEN_INT32 || src_type == TOKEN_UINT32) { priority = AddCast(dst, priority, "float"); } priority = AddCast(dst, priority, "std::complex<float>"); } } return(priority); } int CppSynth::SynthCastToString(string *dst, AstUnop *node) { bool use_sing_fun = false; if (node->operand_ != nullptr) { const ExpressionAttributes *attr = node->operand_->GetAttr(); use_sing_fun = attr->IsComplex() || attr->IsBool(); } if (use_sing_fun) { dst->insert(0, "sing::to_string("); } else { dst->insert(0, "std::to_string("); } *dst += ")"; return(KForcedPriority); } void CppSynth::ProcessStringSumOperand(string *format, string *parms, IAstExpNode *node) { string operand; if (node->GetType() == ANT_UNOP && ((AstUnop*)node)->subtype_ == TOKEN_STRING) { // CASE 1: a conversion. generate a type specifier based on the underlying type IAstExpNode *child = ((AstUnop*)node)->operand_; Token basetype = child->GetAttr()->GetAutoBaseType(); switch (basetype) { case TOKEN_INT8: case TOKEN_INT16: case TOKEN_INT32: *format += "%d"; break; case TOKEN_INT64: *format += "%lld"; break; case TOKEN_UINT8: case TOKEN_UINT16: case TOKEN_UINT32: *format += "%u"; break; case TOKEN_UINT64: *format += "%llu"; break; case TOKEN_FLOAT32: case TOKEN_FLOAT64: *format += "%f"; break; case TOKEN_COMPLEX64: case TOKEN_COMPLEX128: *format += "%s"; break; case TOKEN_BOOL: *format += "%s"; break; case TOKEN_STRING: *format += "%s"; break; default: assert(false); } int priority = SynthExpression(&operand, child); if (basetype == TOKEN_COMPLEX64 || basetype == TOKEN_COMPLEX128) { operand.insert(0, "sing::to_string("); operand += ").c_str()"; } else if (basetype == TOKEN_BOOL) { if (operand == "true" || operand == "false") { operand.insert(0, "\""); operand += "\""; } else { operand += " ? \"true\" : \"false\""; } } } else { if (node->GetType() == ANT_BINOP) { IAstExpNode *node_left = ((AstBinop*)node)->operand_left_; IAstExpNode *node_right = ((AstBinop*)node)->operand_right_; Token left_type = node_left->GetAttr()->GetAutoBaseType(); Token right_type = node_right->GetAttr()->GetAutoBaseType(); if (((AstBinop*)node)->subtype_ == TOKEN_PLUS && (left_type == TOKEN_STRING || right_type == TOKEN_STRING)) { // CASE 2: a sum of strings. recur ProcessStringSumOperand(format, parms, node_left); ProcessStringSumOperand(format, parms, node_right); return; } assert(false); } // CASE 3: leaf string const ExpressionAttributes *attr = node->GetAttr(); *format += "%s"; int priority = SynthExpression(&operand, node); if (!IsLiteralString(node) && !IsInputArg(node)) { Protect(&operand, priority, GetBinopCppPriority(TOKEN_DOT)); operand += ".c_str()"; } } *parms += ", "; AddSplitMarker(parms); *parms += operand; } int CppSynth::SynthLeaf(string *dst, AstExpressionLeaf *node) { int priority = KLeafPriority; switch (node->subtype_) { case TOKEN_NULL: *dst = "nullptr"; break; case TOKEN_FALSE: case TOKEN_TRUE: *dst = Lexer::GetTokenString(node->subtype_); break; case TOKEN_LITERAL_STRING: *dst = node->value_; break; case TOKEN_INT32: priority = GetRealPartOfIntegerLiteral(dst, node, 32); break; case TOKEN_INT64: priority = GetRealPartOfIntegerLiteral(dst, node, 64); *dst += "LL"; break; case TOKEN_UINT32: GetRealPartOfUnsignedLiteral(dst, node); *dst += "U"; break; case TOKEN_UINT64: GetRealPartOfUnsignedLiteral(dst, node); *dst += "LLU"; break; case TOKEN_FLOAT32: priority = GetRealPartOfFloatLiteral(dst, node); *dst += "f"; break; case TOKEN_FLOAT64: priority = GetRealPartOfFloatLiteral(dst, node); break; case TOKEN_COMPLEX64: SynthComplex64(dst, node); break; case TOKEN_COMPLEX128: SynthComplex128(dst, node); break; case TOKEN_LITERAL_UINT: *dst = node->value_; dst->erase_occurrencies_of('_'); break; case TOKEN_LITERAL_FLOAT: *dst = node->value_; *dst += "f"; dst->erase_occurrencies_of('_'); break; case TOKEN_LITERAL_IMG: GetImgPartOfLiteral(dst, node->value_.c_str(), false, false); dst->insert(0, "std::complex<float>(0.0f, "); *dst += ')'; break; case TOKEN_THIS: *dst = "*this"; priority = GetUnopCppPriority(TOKEN_MPY); break; case TOKEN_NAME: { IAstDeclarationNode *decl = node->wp_decl_; bool needs_dereferencing = false; if (decl->GetType() == ANT_VAR) { needs_dereferencing = VarNeedsDereference((VarDeclaration*)decl); } if (needs_dereferencing) { *dst = "*"; *dst += node->value_; priority = GetUnopCppPriority(TOKEN_MPY); } else { *dst = node->value_; } } break; } return(priority); } void CppSynth::SynthComplex64(string *dst, AstExpressionLeaf *node) { GetRealPartOfFloatLiteral(dst, node); dst->insert(0, "std::complex<float>("); if (node->img_value_ == "") { *dst += "f, 0.0f)"; } else { string img; GetImgPartOfLiteral(&img, node->img_value_.c_str(), false, node->img_is_negated_); *dst += "f, "; *dst += img; *dst += ')'; } } void CppSynth::SynthComplex128(string *dst, AstExpressionLeaf *node) { GetRealPartOfFloatLiteral(dst, node); dst->insert(0, "std::complex<double>("); if (node->img_value_ == "") { *dst += ", 0.0)"; } else { string img; GetImgPartOfLiteral(&img, node->img_value_.c_str(), node->subtype_ == TOKEN_COMPLEX128, node->img_is_negated_); *dst += ", "; *dst += img; *dst += ')'; } } int CppSynth::GetRealPartOfIntegerLiteral(string *dst, AstExpressionLeaf *node, int nbits) { int64_t value; int priority = KLeafPriority; node->GetAttr()->GetSignedIntegerValue(&value); if (node->real_is_int_) { // keep the original format (es. hex..) *dst = node->value_; dst->erase_occurrencies_of('_'); if (node->real_is_negated_) { dst->insert(0, "-"); } } else { char buffer[100]; // must have an integer value. Use it and discard the original floating point representation. sprintf(buffer, "%" PRId64, value); *dst = buffer; } if (nbits == 32 && value == -(int64_t)0x80000000) { dst->insert(0, "(int32_t)"); *dst += "LL"; priority = KCastPriority; } else if ((*dst)[0] == '-') { priority = GetUnopCppPriority(TOKEN_MINUS); } return(priority); } void CppSynth::GetRealPartOfUnsignedLiteral(string *dst, AstExpressionLeaf *node) { if (node->real_is_int_) { // keep the original format (es. hex..) *dst = node->value_; dst->erase_occurrencies_of('_'); } else { uint64_t value; char buffer[100]; // must have an integer value. Use it and discard the original floating point representation. value = node->GetAttr()->GetUnsignedValue(); sprintf(buffer, "%" PRIu64, value); *dst = buffer; } } int CppSynth::GetRealPartOfFloatLiteral(string *dst, AstExpressionLeaf *node) { if (IsFloatFormat(node->value_.c_str())) { *dst = node->value_; dst->erase_occurrencies_of('_'); if (node->real_is_negated_) { dst->insert(0, "-"); } } else { int64_t value; char buffer[100]; // must have an integer value. Use it and convert to a floating point representation. value = (int64_t)node->GetAttr()->GetDoubleValue(); sprintf(buffer, "%" PRId64 ".0", value); *dst = buffer; } if ((*dst)[0] == '-') { return(GetUnopCppPriority(TOKEN_MINUS)); } return(KLeafPriority); } void CppSynth::GetImgPartOfLiteral(string *dst, const char *src, bool is_double, bool is_negated) { *dst = src; dst->erase_occurrencies_of('_'); dst->erase(dst->length() - 1); // erase 'i' if (!IsFloatFormat(src)) { *dst += ".0"; } if (!is_double) { *dst += "f"; } if (is_negated) { dst->insert(0, "-"); } } bool IsFloatFormat(const char *num) { return (strchr(num, 'e') != nullptr || strchr(num, 'E') != nullptr || strchr(num, '.') != nullptr); } void CppSynth::Write(string *text, bool add_semicolon) { if (add_semicolon) { *text += ';'; } // adds indentation and line feed, // if appropriate splits the line at the split markers, // adds comments formatter_.Format(text, indent_); const char *bufout = formatter_.GetString(); int length = formatter_.GetLength(); *file_str_ += bufout; } void CppSynth::AddSplitMarker(string *dst) { *dst += MAX(split_level_, 0xf8); } int CppSynth::AddForcedSplit(string *dst, IAstNode *node1, int row) { int newrow = node1->GetPositionRecord()->start_row; if (newrow != row) { *dst += 0xff; } return(newrow); } void CppSynth::EmptyLine(void) { formatter_.AddLineBreak(); } const char *CppSynth::GetBaseTypeName(Token token) { switch (token) { case TOKEN_INT8: return("int8_t"); case TOKEN_INT16: return("int16_t"); case TOKEN_INT32: return("int32_t"); case TOKEN_INT64: return("int64_t"); case TOKEN_UINT8: return("uint8_t"); case TOKEN_UINT16: return("uint16_t"); case TOKEN_UINT32: return("uint32_t"); case TOKEN_UINT64: return("uint64_t"); case TOKEN_FLOAT32: return("float"); case TOKEN_FLOAT64: return("double"); case TOKEN_COMPLEX64: return("std::complex<float>"); case TOKEN_COMPLEX128: return("std::complex<double>"); case TOKEN_STRING: return("std::string"); case TOKEN_BOOL: return("bool"); case TOKEN_VOID: return("void"); } return(""); } int CppSynth::GetBinopCppPriority(Token token) { switch (token) { case TOKEN_POWER: case TOKEN_MIN: case TOKEN_MAX: return(KForcedPriority); // means "doesn't require parenthesys/doesn't take precedence over childrens." case TOKEN_DOT: return(2); case TOKEN_MPY: case TOKEN_DIVIDE: case TOKEN_MOD: return(5); case TOKEN_SHR: case TOKEN_SHL: return(7); case TOKEN_AND: return(11); case TOKEN_PLUS: case TOKEN_MINUS: return(6); case TOKEN_OR: return(13); case TOKEN_XOR: return(12); case TOKEN_ANGLE_OPEN_LT: case TOKEN_ANGLE_CLOSE_GT: case TOKEN_GTE: case TOKEN_LTE: return(9); case TOKEN_DIFFERENT: case TOKEN_EQUAL: return(10); case TOKEN_LOGICAL_AND: return(14); case TOKEN_LOGICAL_OR: return(15); default: assert(false); break; } return(KForcedPriority); } int CppSynth::GetUnopCppPriority(Token token) { switch (token) { case TOKEN_SQUARE_OPEN: // subscript case TOKEN_ROUND_OPEN: // function call case TOKEN_INC: case TOKEN_DEC: case TOKEN_DOT: return(2); case TOKEN_SIZEOF: return(KForcedPriority); case TOKEN_MINUS: case TOKEN_PLUS: case TOKEN_NOT: // bitwise not case TOKEN_AND: // address case TOKEN_LOGICAL_NOT: case TOKEN_MPY: // dereference default: // casts break; } return(3); } bool CppSynth::VarNeedsDereference(VarDeclaration *var) { if (var->HasOneOfFlags(VF_ISPOINTED)) return(true); if (var->HasOneOfFlags(VF_ISARG)) { // output and not a vector return(GetParameterPassingMethod(var->GetTypeSpec(), var->HasOneOfFlags(VF_READONLY)) == PPM_POINTER); } return(false); } void CppSynth::PrependWithSeparator(string *dst, const char *src) { if (dst->length() == 0) { *dst = src; } else { dst->insert(0, src); dst->insert(strlen(src), " "); } } int CppSynth::AddCast(string *dst, int priority, const char *cast_type) { char prefix[100]; if (cast_type == nullptr || cast_type[0] == 0) { return(priority); } if (priority > KCastPriority) { sprintf(prefix, "(%s)(", cast_type); dst->insert(0, prefix); *dst += ")"; } else { sprintf(prefix, "(%s)", cast_type); dst->insert(0, prefix); } return(KCastPriority); } void CppSynth::CutDecimalPortionAndSuffix(string *dst) { int cut_point = dst->find('.'); if (cut_point != string::npos) { dst->erase(cut_point); return; } // if '.' was not found this could be an integer with an 'll' suffix CutSuffix(dst); } void CppSynth::CutSuffix(string *dst) { int ii; for (ii = dst->length() - 1; ii > 0 && dst->c_str()[ii] == 'l'; --ii); dst->erase(ii + 1); } // // casts numerics if c++ doesn't automatically cast to target // int CppSynth::CastIfNeededTo(Token target, Token src_type, string *dst, int priority, bool for_power_op) { if (target == src_type || target == TOKEN_BOOL || target == TOKEN_STRING || target == TOKENS_COUNT) { return(priority); } if (target == TOKEN_COMPLEX128) { if (src_type == TOKEN_COMPLEX64) { dst->insert(0, "sing::c_f2d("); *dst += ")"; return(KForcedPriority); } else if (src_type != TOKEN_COMPLEX128 && src_type != TOKEN_FLOAT64) { priority = AddCast(dst, priority, "double"); } return(priority); } if (target == TOKEN_COMPLEX64) { if (src_type == TOKEN_COMPLEX128) { dst->insert(0, "sing::c_d2f("); *dst += ")"; return(KForcedPriority); } else if (src_type != TOKEN_COMPLEX64 && src_type != TOKEN_FLOAT32) { priority = AddCast(dst, priority, "float"); } return(priority); } // the target is scalar if (src_type == TOKEN_COMPLEX128 || src_type == TOKEN_COMPLEX64) { Protect(dst, priority, GetBinopCppPriority(TOKEN_DOT)); *dst += ".real()"; priority = GetBinopCppPriority(TOKEN_DOT); src_type = (src_type == TOKEN_COMPLEX128) ? TOKEN_FLOAT64 : TOKEN_FLOAT32; } if (ExpressionAttributes::CanAssignWithoutLoss(target, src_type)) { return(priority); } priority = AddCast(dst, priority, GetBaseTypeName(target)); return(priority); } void CppSynth::CastForRelational(Token left_type, Token right_type, string *left, string *right, int *priority_left, int *priority_right) { // complex comparison if (left_type == TOKEN_COMPLEX128 || right_type == TOKEN_COMPLEX128 || left_type == TOKEN_COMPLEX64 && right_type == TOKEN_FLOAT64 || right_type == TOKEN_COMPLEX64 && left_type == TOKEN_FLOAT64) { *priority_left = CastIfNeededTo(TOKEN_COMPLEX128, left_type, left, *priority_left, false); *priority_right = CastIfNeededTo(TOKEN_COMPLEX128, right_type, right, *priority_right, false); } else if (left_type == TOKEN_COMPLEX64 || right_type == TOKEN_COMPLEX64) { *priority_left = CastIfNeededTo(TOKEN_COMPLEX64, left_type, left, *priority_left, false); *priority_right = CastIfNeededTo(TOKEN_COMPLEX64, right_type, right, *priority_right, false); } else if (left_type == TOKEN_FLOAT64 || right_type == TOKEN_FLOAT64) { *priority_left = CastIfNeededTo(TOKEN_FLOAT64, left_type, left, *priority_left, false); *priority_right = CastIfNeededTo(TOKEN_FLOAT64, right_type, right, *priority_right, false); } else { // we are sure than not both the values are integers, so we know that at least one is float *priority_left = CastIfNeededTo(TOKEN_FLOAT32, left_type, left, *priority_left, false); *priority_right = CastIfNeededTo(TOKEN_FLOAT32, right_type, right, *priority_right, false); } } int CppSynth::PromoteToInt32(Token target, string *dst, int priority) { switch (target) { case TOKEN_INT16: case TOKEN_INT8: case TOKEN_UINT16: case TOKEN_UINT8: return(AddCast(dst, priority, "int32_t")); default: break; } return(priority); } // adds brackets if adding the next operator would invert the priority // to be done to operands after casts and before operation void CppSynth::Protect(string *dst, int priority, int next_priority, bool is_right_term) { // a function-like operator: needs no protection and causes no inversion if (priority == KForcedPriority || next_priority == KForcedPriority) return; // protect the priority of this branch from adjacent operators // note: if two binary operators have same priority, use brackets if right-associativity is required if (next_priority < priority || is_right_term && priority > 3 && next_priority == priority) { dst->insert(0, "("); *dst += ')'; } } bool CppSynth::IsPOD(IAstTypeNode *node) { bool ispod = true; switch (node->GetType()) { case ANT_BASE_TYPE: switch (((AstBaseType*)node)->base_type_) { case TOKEN_COMPLEX64: case TOKEN_COMPLEX128: case TOKEN_STRING: ispod = false; default: break; } break; case ANT_NAMED_TYPE: ispod = IsPOD(((AstNamedType*)node)->wp_decl_->type_spec_); break; case ANT_ARRAY_TYPE: case ANT_MAP_TYPE: case ANT_POINTER_TYPE: ispod = false; break; case ANT_FUNC_TYPE: case ANT_ENUM_TYPE: default: break; } return(ispod); } Token CppSynth::GetBaseType(const IAstTypeNode *node) { switch (node->GetType()) { case ANT_BASE_TYPE: return(((AstBaseType*)node)->base_type_); case ANT_NAMED_TYPE: return(GetBaseType(((AstNamedType*)node)->wp_decl_->type_spec_)); default: break; } return(TOKENS_COUNT); } void CppSynth::GetFullExternName(string *full, int pkg_index, const char *local_name) { const Package *pkg = pkmgr_->getPkg(pkg_index); assert(pkg != nullptr); if (pkg != nullptr) { const string *nspace = &pkg->GetRoot()->namespace_; if (root_->namespace_ != *nspace) { const char *src = nspace->c_str(); (*full) = ""; for (int ii = 0; ii < (int)nspace->length(); ++ii) { if (src[ii] != '.') { (*full) += src[ii]; } else { (*full) += "::"; } } (*full) += "::"; (*full) += local_name; } else { (*full) = local_name; } } else { (*full) = local_name; } } bool CppSynth::IsLiteralString(IAstExpNode *node) { if (node->GetType() == ANT_EXP_LEAF) { AstExpressionLeaf *leaf = (AstExpressionLeaf*)node; return (leaf->subtype_ == TOKEN_LITERAL_STRING); } else if (node->GetType() == ANT_BINOP) { AstBinop *op = (AstBinop*)node; return(IsLiteralString(op->operand_left_) && IsLiteralString(op->operand_right_)); } return(false); } bool CppSynth::IsInputArg(IAstExpNode *node) { if (node->GetType() == ANT_EXP_LEAF) { AstExpressionLeaf *leaf = (AstExpressionLeaf*)node; if (leaf->subtype_ == TOKEN_NAME) { IAstDeclarationNode *decl = leaf->wp_decl_; if (decl != nullptr && decl->GetType() == ANT_VAR) { VarDeclaration *var = (VarDeclaration*)decl; return(var->HasAllFlags(VF_ISARG | VF_READONLY)); } } } return(false); } int CppSynth::WriteHeaders(DependencyUsage usage) { string text; int num_items = 0; for (int ii = 0; ii < (int)root_->dependencies_.size(); ++ii) { AstDependency *dependency = root_->dependencies_[ii]; if (dependency->GetUsage() == usage) { text = dependency->package_dir_.c_str(); FileName::ExtensionSet(&text, "h"); text.insert(0, "#include \""); text += "\""; formatter_.SetNodePos(dependency); Write(&text, false); ++num_items; } } return(num_items); } int CppSynth::WriteNamespaceOpening(void) { int num_levels = 0; const char *scan = root_->namespace_.c_str(); if (*scan != 0) { string text; while (*scan != 0) { text = "namespace "; while (*scan != '.' && *scan != 0) { text += *scan++; } text += " {"; Write(&text, false); while (*scan == '.') ++scan; ++num_levels; } } if (num_levels > 0) { EmptyLine(); } return(num_levels); } void CppSynth::WriteNamespaceClosing(int num_levels) { if (num_levels > 0) { EmptyLine(); string closing; for (int ii = 0; ii < num_levels; ++ii) { closing = "} // namespace"; Write(&closing, false); } } } void CppSynth::WriteClassForwardDeclarations(bool public_defs) { bool empty_section = true; string text; ForwardReferenceType reftype = public_defs ? FRT_PUBLIC : FRT_PRIVATE; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_TYPE) { TypeDeclaration *tdecl = (TypeDeclaration*)declaration; if (tdecl->forward_referral_ != reftype) continue; text = "class "; text += tdecl->name_; Write(&text); empty_section = false; } } if (!empty_section) { EmptyLine(); } } int CppSynth::WriteTypeDefinitions(bool public_defs) { int num_items = 0; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->IsPublic() != public_defs) continue; switch (declaration->GetType()) { case ANT_VAR: { VarDeclaration *var = (VarDeclaration*)declaration; if (var->HasOneOfFlags(VF_IMPLEMENTED_AS_CONSTINT)) { formatter_.SetNodePos(var); SynthVar(var); ++num_items; } } break; case ANT_TYPE: formatter_.SetNodePos(declaration); SynthType((TypeDeclaration*)declaration); ++num_items; break; default: break; } } if (num_items > 0) { EmptyLine(); } return(num_items); } void CppSynth::WritePrototypes(bool public_defs) { bool empty_section = true; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->IsPublic() != public_defs) continue; if (declaration->GetType() == ANT_FUNC) { FuncDeclaration *func = (FuncDeclaration*)declaration; if (!func->is_class_member_) { if (func->block_ == nullptr) { formatter_.SetNodePos(declaration); } text = func->name_; SynthFuncTypeSpecification(&text, func->function_type_, true); if (!public_defs) { text.insert(0, "static "); } Write(&text); empty_section = false; } } } if (!empty_section) { EmptyLine(); } } void CppSynth::WriteExternalDeclarations(void) { bool empty_section = true; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (!declaration->IsPublic()) continue; if (declaration->GetType() == ANT_VAR) { VarDeclaration *var = (VarDeclaration*)declaration; if (!var->HasOneOfFlags(VF_IMPLEMENTED_AS_CONSTINT)) { text = var->name_; SynthTypeSpecification(&text, var->GetTypeSpec()); text.insert(0, "extern const "); Write(&text); empty_section = false; } } } if (!empty_section) { EmptyLine(); } } int CppSynth::WriteVariablesDefinitions(void) { int num_items = 0; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_VAR) { VarDeclaration *var = (VarDeclaration*)declaration; if (!var->HasOneOfFlags(VF_IMPLEMENTED_AS_CONSTINT)) { formatter_.SetNodePos(declaration); SynthVar((VarDeclaration*)declaration); ++num_items; } } } if (num_items > 0) { EmptyLine(); } return(num_items); } int CppSynth::WriteClassIdsDefinitions(void) { int num_items = 0; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_TYPE) { TypeDeclaration *tdecl = (TypeDeclaration*)declaration; bool towrite = false; // if has base classes, downcast is possible. if (tdecl->type_spec_->GetType() == ANT_CLASS_TYPE) { AstClassType *ctype = (AstClassType*)tdecl->type_spec_; towrite = ctype->member_interfaces_.size() > 0; } if (towrite) { text = "char "; text += tdecl->name_; text += "::id__"; Write(&text); ++num_items; } } } if (num_items > 0) { EmptyLine(); } return(num_items); } int CppSynth::WriteConstructors(void) { int num_items = 0; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_TYPE) { TypeDeclaration *tdecl = (TypeDeclaration*)declaration; if (tdecl->type_spec_->GetType() == ANT_CLASS_TYPE) { AstClassType *ctype = (AstClassType*)tdecl->type_spec_; // note: if the class has functions, the constructor is placed just before the first of them if (ctype->has_constructor && !ctype->constructor_written && ctype->member_functions_.size() == 0) { ++num_items; SynthConstructor(&tdecl->name_, ctype); } } } } if (num_items > 0) { EmptyLine(); } return(num_items); } int CppSynth::WriteFunctions(void) { string text; int num_items = 0; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_FUNC) { formatter_.SetNodePos(declaration); SynthFunc((FuncDeclaration*)declaration); ++num_items; } } return(num_items); } void CppSynth::WriteReferenceGuard(const char *ref_name, bool isref) { char buf[20]; sprintf(buf, "%d", refguard_name_++); string text = "sing::Ref r"; text += buf; text += "__(\""; text += ref_name; text += " in "; text += function_name_; text += "\", "; if (isref) text += '&'; text += ref_name; text += ")"; Write(&text); } void CppSynth::WriteArgumentsGuards(AstFuncType *type_spec) { ++indent_; refguard_name_ = 0; for (int ii = 0; ii < (int)type_spec->arguments_.size(); ++ii) { VarDeclaration *arg = type_spec->arguments_[ii]; ParmPassingMethod mode = GetParameterPassingMethod(arg->GetTypeSpec(), arg->HasOneOfFlags(VF_READONLY)); if (mode != PPM_VALUE) { WriteReferenceGuard(arg->name_.c_str(), mode == PPM_CONSTREF); } } --indent_; } AstClassType *CppSynth::GetLocalClassTypeDeclaration(const char *classname) { for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_TYPE) { TypeDeclaration *tdecl = (TypeDeclaration*)declaration; if (tdecl->name_ == classname) { IAstTypeNode *ntype = tdecl->type_spec_; if (ntype != nullptr && ntype->GetType() == ANT_CLASS_TYPE) { return((AstClassType*)ntype); } return(nullptr); } } } return(nullptr); } void CppSynth::AppendMemberName(string *dst, IAstDeclarationNode *src) { assert(src != nullptr); if (src == nullptr) return; if (src->GetType() == ANT_VAR) { VarDeclaration *var = (VarDeclaration*)src; *dst += synth_options_->member_prefix_; *dst += var->name_; *dst += synth_options_->member_suffix_; } else if (src->GetType() == ANT_FUNC) { FuncDeclaration *fun = (FuncDeclaration*)src; *dst += fun->name_; } else { assert(false); } } void CppSynth::SynthDFile(FILE *dfd, const Package *package, const char *target_name) { fprintf(dfd, "%s:", target_name); const vector<AstDependency*> *vdep = &package->GetRoot()->dependencies_; for (int ii = 0; ii < vdep->size(); ++ii) { AstDependency *dep = (*vdep)[ii]; if (ii == vdep->size() - 1) { fprintf(dfd, " %s", dep->full_package_path_.c_str()); } else { fprintf(dfd, " %s \\\n", dep->full_package_path_.c_str()); } } } void CppSynth::SynthMapFile(FILE *mfd) { fprintf(mfd, "prefix = %s\r\n", synth_options_->member_prefix_.c_str()); fprintf(mfd, "suffix = %s\r\n", synth_options_->member_suffix_.c_str()); const vector<line_nums> *lines = formatter_.GetLines(); int top = lines->size() - 1; if (top < 0) { fprintf(mfd, "top_lines = 0, 0\r\n"); } else { fprintf(mfd, "top_lines = %d, %d\r\n", (*lines)[top].sing_line, (*lines)[top].cpp_line); fprintf(mfd, "lines:\r\n"); for (int ii = 0; ii <= top; ++ii) { fprintf(mfd, "%d, %d\r\n", (*lines)[ii].sing_line, (*lines)[ii].cpp_line); } } } } // namespace
31.32401
149
0.558466
mdegirolami
8ae721269e40b7d5ffeeaed58bf0df78f43da481
1,365
cpp
C++
src/endgame.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
1
2021-11-19T02:56:04.000Z
2021-11-19T02:56:04.000Z
src/endgame.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
null
null
null
src/endgame.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
null
null
null
#include "endgame.h" EndGame::EndGame() { } void EndGame::Run(State &state, Controller &controller, Renderer &renderer, TradeLog &tradelog, std::size_t &target_frame_duration){ // timing variables Uint32 title_timestamp = SDL_GetTicks(); Uint32 start = SDL_GetTicks(); Uint32 frame_start; Uint32 frame_end; Uint32 frame_duration; int frame_count = 0; // enable text input SDL_StartTextInput(); // display the end page for total_duration unless the player quits while (SDL_GetTicks() - start < total_duration && state != QUIT) { frame_start = SDL_GetTicks(); controller.HandleEndGameInput(state); Update(); renderer.RenderEndGame(tradelog, state); // end of frame timing frame_end = SDL_GetTicks(); frame_count++; frame_duration = frame_end - frame_start; // calculate frames per second if (frame_end - title_timestamp > 1000) { renderer.UpdateWindow_Title(frame_count); frame_count = 0; title_timestamp = frame_end; } // throttle the loop to target frame rate if (frame_duration < target_frame_duration) { SDL_Delay(target_frame_duration - frame_duration); } } } void EndGame::Update() { // future features }
27.3
76
0.625641
joestilin
8aec6d4b0dbb0d87b0e22e71cd47b612af21bd4c
3,803
cpp
C++
test/testMat.cpp
anazli/raymann
425c908f275309da4dc1f77fe6ea0a27ec9e30f8
[ "BSD-2-Clause" ]
null
null
null
test/testMat.cpp
anazli/raymann
425c908f275309da4dc1f77fe6ea0a27ec9e30f8
[ "BSD-2-Clause" ]
null
null
null
test/testMat.cpp
anazli/raymann
425c908f275309da4dc1f77fe6ea0a27ec9e30f8
[ "BSD-2-Clause" ]
null
null
null
#include "geometry/sphere.h" #include "gtest/gtest.h" #include "tools/tools.h" using namespace testing; class TMat : public Test { public: Sphere *s; PointLight light; }; TEST_F(TMat, createsDefaultLight) { ASSERT_TRUE(light.position() == Point3f()); ASSERT_TRUE(light.intensity() == Vec3f()); } TEST_F(TMat, createsNewLight1) { light.setPosition(Point3f(1.0f, 2.0f, 3.0f)); light.setIntensity(Vec3f(0.1f, 0.1f, 0.3f)); ASSERT_EQ(light.position().x(), 1.0f); ASSERT_EQ(light.position().y(), 2.0f); ASSERT_EQ(light.position().z(), 3.0f); ASSERT_EQ(light.intensity().x(), 0.1f); ASSERT_EQ(light.intensity().y(), 0.1f); ASSERT_EQ(light.intensity().z(), 0.3f); } TEST_F(TMat, createsNewLight2) { light = PointLight(Point3f(0.1f, -4.0f, -0.4f), Vec3f(1.0f, 4.0f, 0.0f)); ASSERT_EQ(light.position().x(), 0.1f); ASSERT_EQ(light.position().y(), -4.0f); ASSERT_EQ(light.position().z(), -0.4f); ASSERT_EQ(light.intensity().x(), 1.0f); ASSERT_EQ(light.intensity().y(), 4.0f); ASSERT_EQ(light.intensity().z(), 0.0f); } TEST_F(TMat, lightsWithEyeBetweenLightAndSurface) { //---------------------------------- // As it is in Material->lighting //---------------------------------- Vec3f eye(0.0f, 0.0f, -1.0f); light = PointLight(Point3f(0.0f, 0.0f, -10.0f), Vec3f(1.0f, 1.0f, 1.0f)); Point3f p(0.0f, 0.0f, 0.0f); Vec3f m_color(1.0f, 1.0f, 1.0f); Vec3f effective_color = m_color * light.intensity(); Vec3f lightv = (light.position() - p).normalize(); float m_ambient = 0.1f; float m_diffuse = 0.9f; float m_specular = 0.9f; float m_shininess = 200.0f; Vec3f norm(0.0f, 0.0f, -1.0f); // norm == this->normal(p) Vec3f ret_ambient = effective_color * m_ambient; Vec3f ret_diffuse; Vec3f ret_specular; float light_normal = dot(lightv, norm); if (light_normal >= 0.0f) { ret_diffuse = effective_color * m_diffuse * light_normal; Vec3f reflectv = reflect(-lightv, norm); float reflect_dot_eye = dot(reflectv, eye); if (reflect_dot_eye > 0.0f) { float factor = pow(reflect_dot_eye, m_shininess); ret_specular = light.intensity() * m_specular * factor; } } Vec3f result = ret_ambient + ret_diffuse + ret_specular; ASSERT_EQ(result.x(), 1.9f); ASSERT_EQ(result.y(), 1.9f); ASSERT_EQ(result.z(), 1.9f); ASSERT_TRUE(result == Vec3f(1.9f, 1.9f, 1.9f)); } TEST_F(TMat, lightingWithSurfaceInShadow) { //------------------------------------------------------ // As it is in Material->lighting | Update (With shadow) //------------------------------------------------------ bool in_shadow = true; Vec3f eye(0.0f, 0.0f, -1.0f); light = PointLight(Point3f(0.0f, 0.0f, -10.0f), Vec3f(1.0f, 1.0f, 1.0f)); Point3f p(0.0f, 0.0f, 0.0f); Vec3f m_color(1.0f, 1.0f, 1.0f); Vec3f effective_color = m_color * light.intensity(); Vec3f lightv = (light.position() - p).normalize(); float m_ambient = 0.1f; float m_diffuse = 0.9f; float m_specular = 0.9f; float m_shininess = 200.0f; Vec3f norm(0.0f, 0.0f, -1.0f); // norm == this->normal(p) Vec3f ret_ambient = effective_color * m_ambient; Vec3f ret_diffuse; Vec3f ret_specular; if (!in_shadow) { float light_normal = dot(lightv, norm); if (light_normal >= 0.0f) { ret_diffuse = effective_color * m_diffuse * light_normal; Vec3f reflectv = reflect(-lightv, norm); float reflect_dot_eye = dot(reflectv, eye); if (reflect_dot_eye > 0.0f) { float factor = pow(reflect_dot_eye, m_shininess); ret_specular = light.intensity() * m_specular * factor; } } } Vec3f result = ret_ambient + ret_diffuse + ret_specular; ASSERT_EQ(result.x(), 0.1f); ASSERT_EQ(result.y(), 0.1f); ASSERT_EQ(result.z(), 0.1f); ASSERT_TRUE(result == Vec3f(0.1f, 0.1f, 0.1f)); }
29.944882
75
0.621615
anazli
8af1b5bd6347590cd332381fda6ab6b0d40f2900
1,507
cpp
C++
COM Interfaces/IDispatch.cpp
ntclark/PDFium-Control
4d1f41a7a48205ea26fb46dac59fec16c53df2ef
[ "BSD-3-Clause" ]
2
2019-02-21T06:25:03.000Z
2019-06-23T04:49:14.000Z
COM Interfaces/IDispatch.cpp
ntclark/PDFium-Control
4d1f41a7a48205ea26fb46dac59fec16c53df2ef
[ "BSD-3-Clause" ]
1
2020-08-29T03:02:46.000Z
2020-08-29T03:02:46.000Z
COM Interfaces/IDispatch.cpp
ntclark/PDFium-Control
4d1f41a7a48205ea26fb46dac59fec16c53df2ef
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017, 2018, 2019 InnoVisioNate Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "PDFiumControl.h" // IDispatch STDMETHODIMP PDFiumControl::GetTypeInfoCount(UINT * pctinfo) { *pctinfo = 1; return S_OK; } long __stdcall PDFiumControl::GetTypeInfo(UINT itinfo,LCID lcid,ITypeInfo **pptinfo) { *pptinfo = NULL; if ( itinfo != 0 ) return DISP_E_BADINDEX; if ( ! pITypeInfo_IPDFiumControl ) { } *pptinfo = pITypeInfo_IPDFiumControl; pITypeInfo_IPDFiumControl -> AddRef(); return S_OK; } STDMETHODIMP PDFiumControl::GetIDsOfNames(REFIID riid,OLECHAR** rgszNames,UINT cNames,LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(pITypeInfo_IPDFiumControl, rgszNames, cNames, rgdispid); } STDMETHODIMP PDFiumControl::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags,DISPPARAMS FAR* pdispparams, VARIANT FAR* pvarResult, EXCEPINFO FAR* pexcepinfo, UINT FAR* puArgErr) { IDispatch *ppv; QueryInterface(IID_IDispatch,reinterpret_cast<void**>(&ppv)); HRESULT hr = pITypeInfo_IPDFiumControl -> Invoke(ppv,dispidMember,wFlags,pdispparams,pvarResult,pexcepinfo,puArgErr); ppv -> Release(); return hr; }
30.755102
138
0.629064
ntclark
8af345c62166da543e44498f6c87fae58444f925
72
cpp
C++
src/native/WeChatHelper/WeChatHelper27278/WeChatHelper27278.cpp
xundididi/weicai-scraper
e0e0931f769814e04e8e3f8d7c670675f420b980
[ "MIT" ]
71
2019-11-30T08:37:15.000Z
2022-02-09T02:33:08.000Z
src/native/WeChatHelper/WeChatHelper27278/WeChatHelper27278.cpp
adams549659584/weicai-scraper
e0e0931f769814e04e8e3f8d7c670675f420b980
[ "MIT" ]
9
2020-03-04T08:18:46.000Z
2021-05-10T22:38:05.000Z
src/native/WeChatHelper/WeChatHelper27278/WeChatHelper27278.cpp
adams549659584/weicai-scraper
e0e0931f769814e04e8e3f8d7c670675f420b980
[ "MIT" ]
37
2019-12-12T11:22:30.000Z
2021-11-10T14:42:15.000Z
// WeChatHelper27278.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h"
10.285714
45
0.666667
xundididi
8af8630a3bf0fa2e294f240b467fec98c75f9582
628
cpp
C++
Readme_Engine/PanelConsole.cpp
dafral/Readme_Engine
b815e1a29bfdf5e1acc9ff133d406ac9f12085d4
[ "MIT" ]
null
null
null
Readme_Engine/PanelConsole.cpp
dafral/Readme_Engine
b815e1a29bfdf5e1acc9ff133d406ac9f12085d4
[ "MIT" ]
null
null
null
Readme_Engine/PanelConsole.cpp
dafral/Readme_Engine
b815e1a29bfdf5e1acc9ff133d406ac9f12085d4
[ "MIT" ]
null
null
null
#include "PanelConsole.h" #include "Application.h" PanelConsole::PanelConsole(bool active = true) : Panel(active) {} PanelConsole::~PanelConsole() {} void PanelConsole::Draw() { ImGui::SetNextWindowPos(ImVec2(x, y)); ImGui::SetNextWindowSize(ImVec2(w, h)); ImGui::Begin("Console", &active); ImGui::Text(App->text.begin()); ImGui::End(); } void PanelConsole::ConsoleText(const char* log) { App->text.append(log); App->text.append("\n"); } void PanelConsole::AdjustPanel() { h = 300; w = App->window->GetWidth() / 2; x = (App->window->GetWidth() / 2) - (w / 2); y = App->window->GetHeight() - (MARGIN_Y + h); }
19.625
62
0.654459
dafral
8af8ce245411708801abe5cde44f4273199529df
3,738
cpp
C++
Samples/UWP/D3D12PipelineStateCache/src/MemoryMappedFile.cpp
mvisic/DirectX-Graphics-Samples
5055b4f062bbc2e5f746cca377f5760c394bc2d6
[ "MIT" ]
2
2020-09-24T09:31:52.000Z
2021-01-04T08:10:02.000Z
Samples/UWP/D3D12PipelineStateCache/src/MemoryMappedFile.cpp
mvisic/DirectX-Graphics-Samples
5055b4f062bbc2e5f746cca377f5760c394bc2d6
[ "MIT" ]
null
null
null
Samples/UWP/D3D12PipelineStateCache/src/MemoryMappedFile.cpp
mvisic/DirectX-Graphics-Samples
5055b4f062bbc2e5f746cca377f5760c394bc2d6
[ "MIT" ]
2
2020-09-24T09:31:56.000Z
2022-01-14T01:03:06.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "stdafx.h" #include "MemoryMappedFile.h" MemoryMappedFile::MemoryMappedFile() : m_mapFile(INVALID_HANDLE_VALUE), m_file(INVALID_HANDLE_VALUE), m_mapAddress(nullptr), m_currentFileSize(0) { } MemoryMappedFile::~MemoryMappedFile() { } void MemoryMappedFile::Init(std::wstring filename, UINT fileSize) { m_filename = filename; WIN32_FIND_DATA findFileData; HANDLE handle = FindFirstFileEx(filename.c_str(), FindExInfoBasic, &findFileData, FindExSearchNameMatch, nullptr, 0); bool found = handle != INVALID_HANDLE_VALUE; if (found) { FindClose(handle); } m_file = CreateFile2( filename.c_str(), GENERIC_READ | GENERIC_WRITE, 0, (found) ? OPEN_EXISTING : CREATE_NEW, nullptr); if (m_file == INVALID_HANDLE_VALUE) { std::cerr << (L"m_file is invalid. Error %ld.\n", GetLastError()); std::cerr << (L"Target file is %s\n", filename.c_str()); return; } LARGE_INTEGER realFileSize = {}; BOOL flag = GetFileSizeEx(m_file, &realFileSize); if (!flag) { std::cerr << (L"\nError %ld occurred in GetFileSizeEx!", GetLastError()); assert(false); return; } assert(realFileSize.HighPart == 0); m_currentFileSize = realFileSize.LowPart; if (m_currentFileSize == 0) { // File mapping files with a size of 0 produces an error. m_currentFileSize = DefaultFileSize; } else if(fileSize > m_currentFileSize) { // Grow to the specified size. m_currentFileSize = fileSize; } m_mapFile = CreateFileMapping(m_file, nullptr, PAGE_READWRITE, 0, m_currentFileSize, nullptr); if (m_mapFile == nullptr) { std::cerr << (L"m_mapFile is NULL: last error: %d\n", GetLastError()); assert(false); return; } m_mapAddress = MapViewOfFile(m_mapFile, FILE_MAP_ALL_ACCESS, 0, 0, m_currentFileSize); if (m_mapAddress == nullptr) { std::cerr << (L"m_mapAddress is NULL: last error: %d\n", GetLastError()); assert(false); return; } } void MemoryMappedFile::Destroy(bool deleteFile) { if (m_mapAddress) { BOOL flag = UnmapViewOfFile(m_mapAddress); if (!flag) { std::cerr << (L"\nError %ld occurred unmapping the view!", GetLastError()); assert(false); } m_mapAddress = nullptr; flag = CloseHandle(m_mapFile); // Close the file mapping object. if (!flag) { std::cerr << (L"\nError %ld occurred closing the mapping object!", GetLastError()); assert(false); } flag = CloseHandle(m_file); // Close the file itself. if (!flag) { std::cerr << (L"\nError %ld occurred closing the file!", GetLastError()); assert(false); } } if (deleteFile) { DeleteFile(m_filename.c_str()); } } void MemoryMappedFile::GrowMapping(UINT size) { // Add space for the extra size at the beginning of the file. size += sizeof(UINT); // Check the size. if (size <= m_currentFileSize) { // Don't shrink. return; } // Flush. BOOL flag = FlushViewOfFile(m_mapAddress, 0); if (!flag) { std::cerr << (L"\nError %ld occurred flushing the mapping object!", GetLastError()); assert(false); } // Close the current mapping. Destroy(false); // Update the size and create a new mapping. m_currentFileSize = size; Init(m_filename, m_currentFileSize); }
24.116129
119
0.644195
mvisic
8afcb7a84d82e8b57abbb6f1696651e331212a3e
1,354
cc
C++
src/Code.cc
GuessEver/grun-core
4250e00393251ee3a07124a9945cf1835f96922b
[ "MIT" ]
2
2017-05-06T10:02:13.000Z
2019-12-09T12:58:01.000Z
src/Code.cc
GuessEver/grun-core
4250e00393251ee3a07124a9945cf1835f96922b
[ "MIT" ]
null
null
null
src/Code.cc
GuessEver/grun-core
4250e00393251ee3a07124a9945cf1835f96922b
[ "MIT" ]
1
2018-10-09T11:17:57.000Z
2018-10-09T11:17:57.000Z
// // Created by guessever on 5/3/17. // #include <string.h> #include "Code.h" #include "Grun.h" /** * get extension from filename * @param filename * @return extension */ const char *getExtension(const char *filename) { long len = strlen(filename) - 1; for (long i = 0; filename[i]; i++) { if (filename[i] == '.') { len = i; } } return filename + len + 1; } /** * initialize data * @param path */ Code::Code(const char *path) { this->path = path; const char *ext = getExtension(this->path); if (!strcmp(ext, "pas")) { this->language = Pascal; this->extension = "pas"; } else if (!strcmp(ext, "c")) { this->language = C; this->extension = "c"; } else if (!strcmp(ext, "cc") || !strcmp(ext, "cxx") || !strcmp(ext, "cpp")) { this->language = CC; this->extension = "cc"; } else if (!strcmp(ext, "java")) { this->language = Java; this->extension = "java"; } else if (!strcmp(ext, "py")) { this->language = Python; this->extension = "py"; } else if (!strcmp(ext, "lua")) { this->language = Lua; this->extension = "lua"; } this->filename2 = "Main"; char *tmp = new char[255]; sprintf(tmp, "%s.%s", this->filename2, this->extension); this->filename = tmp; }
24.178571
82
0.526588
GuessEver
c10007ec3dce74631d45a270634358bcd3f2dc29
665
cpp
C++
Week-3/Day-16-checkValidString.cpp
utkarshavardhana/30-day-leetcoding-challenge
a47b14f74f28961a032d1f00ce710ea3dcb0d910
[ "MIT" ]
2
2020-05-02T04:21:56.000Z
2020-05-14T04:19:47.000Z
Week-3/Day-16-checkValidString.cpp
utkarshavardhana/30-day-leetcoding-challenge
a47b14f74f28961a032d1f00ce710ea3dcb0d910
[ "MIT" ]
null
null
null
Week-3/Day-16-checkValidString.cpp
utkarshavardhana/30-day-leetcoding-challenge
a47b14f74f28961a032d1f00ce710ea3dcb0d910
[ "MIT" ]
null
null
null
class Solution { public: bool checkValidString(string s) { stack<int> st, st1; int i(0); for(const auto &c: s) { if(c == '(') st.push(i); else if(c == '*') st1.push(i); else { if(st.empty() && st1.empty()) return false; else { if(!st.empty()) st.pop(); else st1.pop(); } } i++; } while(!st.empty()) { if(!st1.empty() && st.top() < st1.top()) st.pop(), st1.pop(); else return false; } return true; } };
25.576923
74
0.350376
utkarshavardhana
c1038a684e9e79e241ee1aaac41bcd566f98a22f
314
cpp
C++
usaco/milkpails.cpp
datpq/competitive-programming
ed5733cc55fa4167c4a2e828894b044ea600dcac
[ "MIT" ]
1
2022-02-24T21:35:18.000Z
2022-02-24T21:35:18.000Z
usaco/milkpails.cpp
datpq/competitive-programming
ed5733cc55fa4167c4a2e828894b044ea600dcac
[ "MIT" ]
null
null
null
usaco/milkpails.cpp
datpq/competitive-programming
ed5733cc55fa4167c4a2e828894b044ea600dcac
[ "MIT" ]
1
2022-02-12T14:40:21.000Z
2022-02-12T14:40:21.000Z
#include <fstream> using namespace std; int main() { ifstream ifs("pails.in"); ofstream ofs("pails.out"); int x, y, m; ifs >> x >> y >> m; int ans = m; for (int i = 0; i <= (m / x); i++) { int remainder = m - (i * x); ans = min(ans, remainder % y); if (ans == 0) break; } ofs << (m - ans) << endl; }
19.625
37
0.515924
datpq
c10505d2cd710a8e041e77fb1120b415f6102343
1,674
hpp
C++
IgzModelConverterGUI/3rd_party/PreCore/datas/Matrix44.hpp
AdventureT/IgzModelConverter
7b213d0dd32f04bc01524587a4fa357d204e1c04
[ "MIT" ]
9
2019-10-11T18:12:15.000Z
2022-03-26T23:57:05.000Z
IgzModelConverterGUI/3rd_party/PreCore/datas/Matrix44.hpp
AdventureT/IgzModelConverter
7b213d0dd32f04bc01524587a4fa357d204e1c04
[ "MIT" ]
2
2021-07-29T11:29:30.000Z
2021-12-12T20:40:08.000Z
IgzModelConverterGUI/3rd_party/PreCore/datas/Matrix44.hpp
AdventureT/IgzModelConverter
7b213d0dd32f04bc01524587a4fa357d204e1c04
[ "MIT" ]
1
2020-10-01T23:00:28.000Z
2020-10-01T23:00:28.000Z
/* esMatrix44 class is a simple affine matrix 4x4 more info in README for PreCore Project Copyright 2018-2019 Lukas Cone 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 "VectorsSimd.hpp" class esMatrix44 { public: Vector4A16 r1, r2, r3, r4; esMatrix44(); esMatrix44(const Vector4A16 &row1, const Vector4A16 &row2, const Vector4A16 &row3) : r1(row1), r2(row2), r3(row3) {} esMatrix44(const Vector4A16 &row1, const Vector4A16 &row2, const Vector4A16 &row3, const Vector4A16 &row4) : r1(row1), r2(row2), r3(row3), r4(row4) {} esMatrix44(const Vector4A16 &quat); esMatrix44(const Vector4A16 *rows) : r1(rows[0]), r2(rows[1]), r3(rows[2]), r4(rows[3]) {} void MakeIdentity(); void Decompose(Vector4A16 &position, Vector4A16 &rotation, Vector4A16 &scale) const; void Compose(const Vector4A16 &position, const Vector4A16 &rotation, const Vector4A16 &scale); Vector4A16 RotatePoint(const Vector4A16 &input) const; void FromQuat(const Vector4A16 &q); Vector4A16 ToQuat() const; };
38.045455
80
0.676225
AdventureT
c10bc8063d8b22b7096bbed7bbb9aff6dc1b138d
54,855
cpp
C++
tf2_src/engine/vengineserver_impl.cpp
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/engine/vengineserver_impl.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/engine/vengineserver_impl.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $NoKeywords: $ //===========================================================================// #include "server_pch.h" #include "tier0/valve_minmax_off.h" #include <algorithm> #include "tier0/valve_minmax_on.h" #include "vengineserver_impl.h" #include "vox.h" #include "sound.h" #include "gl_model_private.h" #include "host_saverestore.h" #include "world.h" #include "l_studio.h" #include "decal.h" #include "sys_dll.h" #include "sv_log.h" #include "sv_main.h" #include "tier1/strtools.h" #include "collisionutils.h" #include "staticpropmgr.h" #include "string_t.h" #include "vstdlib/random.h" #include "EngineSoundInternal.h" #include "dt_send_eng.h" #include "PlayerState.h" #include "irecipientfilter.h" #include "sv_user.h" #include "server_class.h" #include "cdll_engine_int.h" #include "enginesingleuserfilter.h" #include "ispatialpartitioninternal.h" #include "con_nprint.h" #include "tmessage.h" #include "iscratchpad3d.h" #include "pr_edict.h" #include "networkstringtableserver.h" #include "networkstringtable.h" #include "LocalNetworkBackdoor.h" #include "host_phonehome.h" #include "matchmaking.h" #include "sv_plugin.h" #include "sv_steamauth.h" #include "replay_internal.h" #include "replayserver.h" #include "replay/iserverengine.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define MAX_MESSAGE_SIZE 2500 #define MAX_TOTAL_ENT_LEAFS 128 void SV_DetermineMulticastRecipients( bool usepas, const Vector& origin, CBitVec< ABSOLUTE_PLAYER_LIMIT >& playerbits ); int MapList_ListMaps( const char *pszSubString, bool listobsolete, bool verbose, int maxcount, int maxitemlength, char maplist[][ 64 ] ); extern CNetworkStringTableContainer *networkStringTableContainerServer; CSharedEdictChangeInfo g_SharedEdictChangeInfo; CSharedEdictChangeInfo *g_pSharedChangeInfo = &g_SharedEdictChangeInfo; IAchievementMgr *g_pAchievementMgr = NULL; CGamestatsData *g_pGamestatsData = NULL; void InvalidateSharedEdictChangeInfos() { if ( g_SharedEdictChangeInfo.m_iSerialNumber == 0xFFFF ) { // Reset all edicts to 0. g_SharedEdictChangeInfo.m_iSerialNumber = 1; for ( int i=0; i < sv.num_edicts; i++ ) sv.edicts[i].SetChangeInfoSerialNumber( 0 ); } else { g_SharedEdictChangeInfo.m_iSerialNumber++; } g_SharedEdictChangeInfo.m_nChangeInfos = 0; } // ---------------------------------------------------------------------- // // Globals. // ---------------------------------------------------------------------- // struct MsgData { MsgData() { Reset(); // link buffers to messages entityMsg.m_DataOut.StartWriting( entitydata, sizeof(entitydata) ); entityMsg.m_DataOut.SetDebugName( "s_MsgData.entityMsg.m_DataOut" ); userMsg.m_DataOut.StartWriting( userdata, sizeof(userdata) ); userMsg.m_DataOut.SetDebugName( "s_MsgData.userMsg.m_DataOut" ); } void Reset() { filter = NULL; reliable = false; subtype = 0; started = false; usermessagesize = -1; usermessagename = NULL; currentMsg = NULL; } byte userdata[ PAD_NUMBER( MAX_USER_MSG_DATA, 4 ) ]; // buffer for outgoing user messages byte entitydata[ PAD_NUMBER( MAX_ENTITY_MSG_DATA, 4 ) ]; // buffer for outgoing entity messages IRecipientFilter *filter; // clients who get this message bool reliable; INetMessage *currentMsg; // pointer to entityMsg or userMessage int subtype; // usermessage index bool started; // IS THERE A MESSAGE IN THE PROCESS OF BEING SENT? int usermessagesize; char const *usermessagename; SVC_EntityMessage entityMsg; SVC_UserMessage userMsg; }; static MsgData s_MsgData; void SeedRandomNumberGenerator( bool random_invariant ) { if (!random_invariant) { long iSeed; g_pVCR->Hook_Time( &iSeed ); float flAppTime = Plat_FloatTime(); ThreadId_t threadId = ThreadGetCurrentId(); iSeed ^= (*((int *)&flAppTime)); iSeed ^= threadId; RandomSeed( iSeed ); } else { // Make those random numbers the same every time! RandomSeed( 0 ); } } // ---------------------------------------------------------------------- // // Static helpers. // ---------------------------------------------------------------------- // static void PR_CheckEmptyString (const char *s) { if (s[0] <= ' ') Host_Error ("Bad string: %s", s); } // Average a list a vertices to find an approximate "center" static void CenterVerts( Vector verts[], int vertCount, Vector& center ) { int i; float scale; if ( vertCount ) { Vector edge0, edge1, normal; VectorCopy( vec3_origin, center ); // sum up verts for ( i = 0; i < vertCount; i++ ) { VectorAdd( center, verts[i], center ); } scale = 1.0f / (float)vertCount; VectorScale( center, scale, center ); // divide by vertCount // Compute 2 poly edges VectorSubtract( verts[1], verts[0], edge0 ); VectorSubtract( verts[vertCount-1], verts[0], edge1 ); // cross for normal CrossProduct( edge0, edge1, normal ); // Find the component of center that is outside of the plane scale = DotProduct( center, normal ) - DotProduct( verts[0], normal ); // subtract it off VectorMA( center, scale, normal, center ); // center is in the plane now } } // Copy the list of verts from an msurface_t int a linear array static void SurfaceToVerts( model_t *model, SurfaceHandle_t surfID, Vector verts[], int *vertCount ) { if ( *vertCount > MSurf_VertCount( surfID ) ) *vertCount = MSurf_VertCount( surfID ); // Build the list of verts from 0 to n for ( int i = 0; i < *vertCount; i++ ) { int vertIndex = model->brush.pShared->vertindices[ MSurf_FirstVertIndex( surfID ) + i ]; Vector& vert = model->brush.pShared->vertexes[ vertIndex ].position; VectorCopy( vert, verts[i] ); } // vert[0] is the first and last vert, there is no copy } // Calculate the surface area of an arbitrary msurface_t polygon (convex with collinear verts) static float SurfaceArea( model_t *model, SurfaceHandle_t surfID ) { Vector center, verts[32]; int vertCount = 32; float area; int i; // Compute a "center" point and fan SurfaceToVerts( model, surfID, verts, &vertCount ); CenterVerts( verts, vertCount, center ); area = 0; // For a triangle of the center and each edge for ( i = 0; i < vertCount; i++ ) { Vector edge0, edge1, out; int next; next = (i+1)%vertCount; VectorSubtract( verts[i], center, edge0 ); // 0.5 * edge cross edge (0.5 is done once at the end) VectorSubtract( verts[next], center, edge1 ); CrossProduct( edge0, edge1, out ); area += VectorLength( out ); } return area * 0.5; // 0.5 here } // Average the list of vertices to find an approximate "center" static void SurfaceCenter( model_t *model, SurfaceHandle_t surfID, Vector& center ) { Vector verts[32]; // We limit faces to 32 verts elsewhere in the engine int vertCount = 32; SurfaceToVerts( model, surfID, verts, &vertCount ); CenterVerts( verts, vertCount, center ); } static bool ValidCmd( const char *pCmd ) { int len; len = strlen(pCmd); // Valid commands all have a ';' or newline '\n' as their last character if ( len && (pCmd[len-1] == '\n' || pCmd[len-1] == ';') ) return true; return false; } // ---------------------------------------------------------------------- // // CVEngineServer // ---------------------------------------------------------------------- // class CVEngineServer : public IVEngineServer { public: virtual void ChangeLevel( const char* s1, const char* s2) { if ( !s1 ) { Sys_Error( "CVEngineServer::Changelevel with NULL s1\n" ); } char cmd[ 256 ]; char s1Escaped[ sizeof( cmd ) ]; char s2Escaped[ sizeof( cmd ) ]; if ( !Cbuf_EscapeCommandArg( s1, s1Escaped, sizeof( s1Escaped ) ) || ( s2 && !Cbuf_EscapeCommandArg( s2, s2Escaped, sizeof( s2Escaped ) ))) { Warning( "Illegal map name in ChangeLevel\n" ); return; } int cmdLen = 0; if ( !s2 ) // no indication of where they are coming from; so just do a standard old changelevel { cmdLen = Q_snprintf( cmd, sizeof( cmd ), "changelevel %s\n", s1Escaped ); } else { cmdLen = Q_snprintf( cmd, sizeof( cmd ), "changelevel2 %s %s\n", s1Escaped, s2Escaped ); } if ( !cmdLen || cmdLen >= sizeof( cmd ) ) { Warning( "Paramter overflow in ChangeLevel\n" ); return; } Cbuf_AddText( cmd ); } virtual int IsMapValid( const char *filename ) { return modelloader->Map_IsValid( filename ); } virtual bool IsDedicatedServer( void ) { return sv.IsDedicated(); } virtual int IsInEditMode( void ) { #ifdef SWDS return false; #else return g_bInEditMode; #endif } virtual int IsInCommentaryMode( void ) { #ifdef SWDS return false; #else return g_bInCommentaryMode; #endif } virtual void NotifyEdictFlagsChange( int iEdict ) { if ( g_pLocalNetworkBackdoor ) g_pLocalNetworkBackdoor->NotifyEdictFlagsChange( iEdict ); } virtual const CCheckTransmitInfo* GetPrevCheckTransmitInfo( edict_t *pPlayerEdict ) { int entnum = NUM_FOR_EDICT( pPlayerEdict ); if ( entnum < 1 || entnum > sv.GetClientCount() ) { Error( "Invalid client specified in GetPrevCheckTransmitInfo\n" ); return NULL; } CGameClient *client = sv.Client( entnum-1 ); return client->GetPrevPackInfo(); } virtual int PrecacheDecal( const char *name, bool preload /*=false*/ ) { PR_CheckEmptyString( name ); int i = SV_FindOrAddDecal( name, preload ); if ( i >= 0 ) { return i; } Host_Error( "CVEngineServer::PrecacheDecal: '%s' overflow, too many decals", name ); return 0; } virtual int PrecacheModel( const char *s, bool preload /*= false*/ ) { PR_CheckEmptyString (s); int i = SV_FindOrAddModel( s, preload ); if ( i >= 0 ) { return i; } Host_Error( "CVEngineServer::PrecacheModel: '%s' overflow, too many models", s ); return 0; } virtual int PrecacheGeneric(const char *s, bool preload /*= false*/ ) { int i; PR_CheckEmptyString (s); i = SV_FindOrAddGeneric( s, preload ); if (i >= 0) { return i; } Host_Error ("CVEngineServer::PrecacheGeneric: '%s' overflow", s); return 0; } virtual bool IsModelPrecached( char const *s ) const { int idx = SV_ModelIndex( s ); return idx != -1 ? true : false; } virtual bool IsDecalPrecached( char const *s ) const { int idx = SV_DecalIndex( s ); return idx != -1 ? true : false; } virtual bool IsGenericPrecached( char const *s ) const { int idx = SV_GenericIndex( s ); return idx != -1 ? true : false; } virtual void ForceExactFile( const char *s ) { Warning( "ForceExactFile no longer supported. Use sv_pure instead. (%s)\n", s ); } virtual void ForceModelBounds( const char *s, const Vector &mins, const Vector &maxs ) { PR_CheckEmptyString( s ); SV_ForceModelBounds( s, mins, maxs ); } virtual void ForceSimpleMaterial( const char *s ) { PR_CheckEmptyString( s ); SV_ForceSimpleMaterial( s ); } virtual bool IsInternalBuild( void ) { return !phonehome->IsExternalBuild(); } //----------------------------------------------------------------------------- // Purpose: Precache a sentence file (parse on server, send to client) // Input : *s - file name //----------------------------------------------------------------------------- virtual int PrecacheSentenceFile( const char *s, bool preload /*= false*/ ) { // UNDONE: Set up preload flag // UNDONE: Send this data to the client to support multiple sentence files VOX_ReadSentenceFile( s ); return 0; } //----------------------------------------------------------------------------- // Purpose: Retrieves the pvs for an origin into the specified array // Input : *org - origin // outputpvslength - size of outputpvs array in bytes // *outputpvs - If null, then return value is the needed length // Output : int - length of pvs array used ( in bytes ) //----------------------------------------------------------------------------- virtual int GetClusterForOrigin( const Vector& org ) { return CM_LeafCluster( CM_PointLeafnum( org ) ); } virtual int GetPVSForCluster( int clusterIndex, int outputpvslength, unsigned char *outputpvs ) { int length = (CM_NumClusters()+7)>>3; if ( outputpvs ) { if ( outputpvslength < length ) { Sys_Error( "GetPVSForOrigin called with inusfficient sized pvs array, need %i bytes!", length ); return length; } CM_Vis( outputpvs, outputpvslength, clusterIndex, DVIS_PVS ); } return length; } //----------------------------------------------------------------------------- // Purpose: Test origin against pvs array retreived from GetPVSForOrigin // Input : *org - origin to chec // checkpvslength - length of pvs array // *checkpvs - // Output : bool - true if entity is visible //----------------------------------------------------------------------------- virtual bool CheckOriginInPVS( const Vector& org, const unsigned char *checkpvs, int checkpvssize ) { int clusterIndex = CM_LeafCluster( CM_PointLeafnum( org ) ); if ( clusterIndex < 0 ) return false; int offset = clusterIndex>>3; if ( offset > checkpvssize ) { Sys_Error( "CheckOriginInPVS: cluster would read past end of pvs data (%i:%i)\n", offset, checkpvssize ); return false; } if ( !(checkpvs[offset] & (1<<(clusterIndex&7)) ) ) { return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Test origin against pvs array retreived from GetPVSForOrigin // Input : *org - origin to chec // checkpvslength - length of pvs array // *checkpvs - // Output : bool - true if entity is visible //----------------------------------------------------------------------------- virtual bool CheckBoxInPVS( const Vector& mins, const Vector& maxs, const unsigned char *checkpvs, int checkpvssize ) { if ( !CM_BoxVisible( mins, maxs, checkpvs, checkpvssize ) ) { return false; } return true; } virtual int GetPlayerUserId( const edict_t *e ) { if ( !sv.IsActive() || !e) return -1; for ( int i = 0; i < sv.GetClientCount(); i++ ) { CGameClient *pClient = sv.Client(i); if ( pClient->edict == e ) { return pClient->m_UserID; } } // Couldn't find it return -1; } virtual const char *GetPlayerNetworkIDString( const edict_t *e ) { if ( !sv.IsActive() || !e) return NULL; for ( int i = 0; i < sv.GetClientCount(); i++ ) { CGameClient *pGameClient = sv.Client(i); if ( pGameClient->edict == e ) { return pGameClient->GetNetworkIDString(); } } // Couldn't find it return NULL; } virtual bool IsPlayerNameLocked( const edict_t *pEdict ) { if ( !sv.IsActive() || !pEdict ) return false; for ( int i = 0; i < sv.GetClientCount(); i++ ) { CGameClient *pClient = sv.Client( i ); if ( pClient->edict == pEdict ) { return pClient->IsPlayerNameLocked(); } } return false; } virtual bool CanPlayerChangeName( const edict_t *pEdict ) { if ( !sv.IsActive() || !pEdict ) return false; for ( int i = 0; i < sv.GetClientCount(); i++ ) { CGameClient *pClient = sv.Client( i ); if ( pClient->edict == pEdict ) { return ( !pClient->IsPlayerNameLocked() && !pClient->IsNameChangeOnCooldown() ); } } return false; } // See header comment. This is the canonical map lookup spot, and a superset of the server gameDLL's // CanProvideLevel/PrepareLevelResources virtual eFindMapResult FindMap( /* in/out */ char *pMapName, int nMapNameMax ) { char szOriginalName[256] = { 0 }; V_strncpy( szOriginalName, pMapName, sizeof( szOriginalName ) ); IServerGameDLL::eCanProvideLevelResult eCanGameDLLProvide = IServerGameDLL::eCanProvideLevel_CannotProvide; if ( g_iServerGameDLLVersion >= 10 ) { eCanGameDLLProvide = serverGameDLL->CanProvideLevel( pMapName, nMapNameMax ); } if ( eCanGameDLLProvide == IServerGameDLL::eCanProvideLevel_Possibly ) { return eFindMap_PossiblyAvailable; } else if ( eCanGameDLLProvide == IServerGameDLL::eCanProvideLevel_CanProvide ) { // See if the game dll fixed up the map name return ( V_strcmp( szOriginalName, pMapName ) == 0 ) ? eFindMap_Found : eFindMap_NonCanonical; } AssertMsg( eCanGameDLLProvide == IServerGameDLL::eCanProvideLevel_CannotProvide, "Unhandled enum member" ); char szDiskName[MAX_PATH] = { 0 }; // Check if we can directly use this as a map Host_DefaultMapFileName( pMapName, szDiskName, sizeof( szDiskName ) ); if ( *szDiskName && modelloader->Map_IsValid( szDiskName, true ) ) { return eFindMap_Found; } // Fuzzy match in map list and check file char match[1][64] = { {0} }; if ( MapList_ListMaps( pMapName, false, false, 1, sizeof( match[0] ), match ) && *(match[0]) ) { Host_DefaultMapFileName( match[0], szDiskName, sizeof( szDiskName ) ); if ( modelloader->Map_IsValid( szDiskName, true ) ) { V_strncpy( pMapName, match[0], nMapNameMax ); return eFindMap_FuzzyMatch; } } return eFindMap_NotFound; } virtual int IndexOfEdict(const edict_t *pEdict) { if ( !pEdict ) { return 0; } int index = (int) ( pEdict - sv.edicts ); if ( index < 0 || index > sv.max_edicts ) { Sys_Error( "Bad entity in IndexOfEdict() index %i pEdict %p sv.edicts %p\n", index, pEdict, sv.edicts ); } return index; } // Returns a pointer to an entity from an index, but only if the entity // is a valid DLL entity (ie. has an attached class) virtual edict_t* PEntityOfEntIndex(int iEntIndex) { if ( iEntIndex >= 0 && iEntIndex < sv.max_edicts ) { edict_t *pEdict = EDICT_NUM( iEntIndex ); if ( !pEdict->IsFree() ) { return pEdict; } } return NULL; } virtual int GetEntityCount( void ) { return sv.num_edicts - sv.free_edicts; } virtual INetChannelInfo* GetPlayerNetInfo( int playerIndex ) { if ( playerIndex < 1 || playerIndex > sv.GetClientCount() ) return NULL; CGameClient *client = sv.Client( playerIndex - 1 ); return client->m_NetChannel; } virtual edict_t* CreateEdict( int iForceEdictIndex ) { edict_t *pedict = ED_Alloc( iForceEdictIndex ); if ( g_pServerPluginHandler ) { g_pServerPluginHandler->OnEdictAllocated( pedict ); } return pedict; } virtual void RemoveEdict(edict_t* ed) { if ( g_pServerPluginHandler ) { g_pServerPluginHandler->OnEdictFreed( ed ); } ED_Free(ed); } // // Request engine to allocate "cb" bytes on the entity's private data pointer. // virtual void *PvAllocEntPrivateData( long cb ) { return calloc( 1, cb ); } // // Release the private data memory, if any. // virtual void FreeEntPrivateData( void *pEntity ) { #if defined( _DEBUG ) && defined( WIN32 ) // set the memory to a known value int size = _msize( pEntity ); memset( pEntity, 0xDD, size ); #endif if ( pEntity ) { free( pEntity ); } } virtual void *SaveAllocMemory( size_t num, size_t size ) { #ifndef SWDS return ::SaveAllocMemory(num, size); #else return NULL; #endif } virtual void SaveFreeMemory( void *pSaveMem ) { #ifndef SWDS ::SaveFreeMemory(pSaveMem); #endif } /* ================= EmitAmbientSound ================= */ virtual void EmitAmbientSound( int entindex, const Vector& pos, const char *samp, float vol, soundlevel_t soundlevel, int fFlags, int pitch, float soundtime /*=0.0f*/ ) { SoundInfo_t sound; sound.SetDefault(); sound.nEntityIndex = entindex; sound.fVolume = vol; sound.Soundlevel = soundlevel; sound.nFlags = fFlags; sound.nPitch = pitch; sound.nChannel = CHAN_STATIC; sound.vOrigin = pos; sound.bIsAmbient = true; ASSERT_COORD( sound.vOrigin ); // set sound delay if ( soundtime != 0.0f ) { sound.fDelay = soundtime - sv.GetTime(); sound.nFlags |= SND_DELAY; } // if this is a sentence, get sentence number if ( TestSoundChar(samp, CHAR_SENTENCE) ) { sound.bIsSentence = true; sound.nSoundNum = Q_atoi( PSkipSoundChars(samp) ); if ( sound.nSoundNum >= VOX_SentenceCount() ) { ConMsg("EmitAmbientSound: invalid sentence number: %s", PSkipSoundChars(samp)); return; } } else { // check to see if samp was properly precached sound.bIsSentence = false; sound.nSoundNum = SV_SoundIndex( samp ); if (sound.nSoundNum <= 0) { ConMsg ("EmitAmbientSound: sound not precached: %s\n", samp); return; } } if ( (fFlags & SND_SPAWNING) && sv.allowsignonwrites ) { SVC_Sounds sndmsg; char buffer[32]; sndmsg.m_DataOut.StartWriting(buffer, sizeof(buffer) ); sndmsg.m_nNumSounds = 1; sndmsg.m_bReliableSound = true; SoundInfo_t defaultSound; defaultSound.SetDefault(); sound.WriteDelta( &defaultSound, sndmsg.m_DataOut ); // write into signon buffer if ( !sndmsg.WriteToBuffer( sv.m_Signon ) ) { Sys_Error( "EmitAmbientSound: Init message would overflow signon buffer!\n" ); return; } } else { if ( fFlags & SND_SPAWNING ) { DevMsg("EmitAmbientSound: warning, broadcasting sound labled as SND_SPAWNING.\n" ); } // send sound to all active players CEngineRecipientFilter filter; filter.AddAllPlayers(); filter.MakeReliable(); sv.BroadcastSound( sound, filter ); } } virtual void FadeClientVolume(const edict_t *clientent, float fadePercent, float fadeOutSeconds, float holdTime, float fadeInSeconds) { int entnum = NUM_FOR_EDICT(clientent); if (entnum < 1 || entnum > sv.GetClientCount() ) { ConMsg ("tried to DLL_FadeClientVolume a non-client\n"); return; } IClient *client = sv.Client(entnum-1); NET_StringCmd sndMsg( va("soundfade %.1f %.1f %.1f %.1f", fadePercent, holdTime, fadeOutSeconds, fadeInSeconds ) ); client->SendNetMsg( sndMsg ); } //----------------------------------------------------------------------------- // // Sentence API // //----------------------------------------------------------------------------- virtual int SentenceGroupPick( int groupIndex, char *name, int nameLen ) { if ( !name ) { Sys_Error( "SentenceGroupPick with NULL name\n" ); } Assert( nameLen > 0 ); return VOX_GroupPick( groupIndex, name, nameLen ); } virtual int SentenceGroupPickSequential( int groupIndex, char *name, int nameLen, int sentenceIndex, int reset ) { if ( !name ) { Sys_Error( "SentenceGroupPickSequential with NULL name\n" ); } Assert( nameLen > 0 ); return VOX_GroupPickSequential( groupIndex, name, nameLen, sentenceIndex, reset ); } virtual int SentenceIndexFromName( const char *pSentenceName ) { if ( !pSentenceName ) { Sys_Error( "SentenceIndexFromName with NULL pSentenceName\n" ); } int sentenceIndex = -1; VOX_LookupString( pSentenceName, &sentenceIndex ); return sentenceIndex; } virtual const char *SentenceNameFromIndex( int sentenceIndex ) { return VOX_SentenceNameFromIndex( sentenceIndex ); } virtual int SentenceGroupIndexFromName( const char *pGroupName ) { if ( !pGroupName ) { Sys_Error( "SentenceGroupIndexFromName with NULL pGroupName\n" ); } return VOX_GroupIndexFromName( pGroupName ); } virtual const char *SentenceGroupNameFromIndex( int groupIndex ) { return VOX_GroupNameFromIndex( groupIndex ); } virtual float SentenceLength( int sentenceIndex ) { return VOX_SentenceLength( sentenceIndex ); } //----------------------------------------------------------------------------- virtual int CheckHeadnodeVisible( int nodenum, const byte *visbits, int vissize ) { return CM_HeadnodeVisible(nodenum, visbits, vissize ); } /* ================= ServerCommand Sends text to servers execution buffer localcmd (string) ================= */ virtual void ServerCommand( const char *str ) { if ( !str ) { Sys_Error( "ServerCommand with NULL string\n" ); } if ( ValidCmd( str ) ) { Cbuf_AddText( str ); } else { ConMsg( "Error, bad server command %s\n", str ); } } /* ================= ServerExecute Executes all commands in server buffer localcmd (string) ================= */ virtual void ServerExecute( void ) { Cbuf_Execute(); } /* ================= ClientCommand Sends text over to the client's execution buffer stuffcmd (clientent, value) ================= */ virtual void ClientCommand(edict_t* pEdict, const char* szFmt, ...) { va_list argptr; static char szOut[1024]; va_start(argptr, szFmt); Q_vsnprintf(szOut, sizeof( szOut ), szFmt, argptr); va_end(argptr); if ( szOut[0] == 0 ) { Warning( "ClientCommand, 0 length string supplied.\n" ); return; } int entnum = NUM_FOR_EDICT( pEdict ); if ( ( entnum < 1 ) || ( entnum > sv.GetClientCount() ) ) { ConMsg("\n!!!\n\nStuffCmd: Some entity tried to stuff '%s' to console buffer of entity %i when maxclients was set to %i, ignoring\n\n", szOut, entnum, sv.GetMaxClients() ); return; } NET_StringCmd string( szOut ); sv.GetClient(entnum-1)->SendNetMsg( string ); } // Send a client command keyvalues // keyvalues are deleted inside the function virtual void ClientCommandKeyValues( edict_t *pEdict, KeyValues *pCommand ) { if ( !pCommand ) return; int entnum = NUM_FOR_EDICT( pEdict ); if ( ( entnum < 1 ) || ( entnum > sv.GetClientCount() ) ) { ConMsg("\n!!!\n\nClientCommandKeyValues: Some entity tried to stuff '%s' to console buffer of entity %i when maxclients was set to %i, ignoring\n\n", pCommand->GetName(), entnum, sv.GetMaxClients() ); return; } SVC_CmdKeyValues cmd( pCommand ); sv.GetClient(entnum-1)->SendNetMsg( cmd ); } /* =============== LightStyle void(float style, string value) lightstyle =============== */ virtual void LightStyle(int style, const char* val) { if ( !val ) { Sys_Error( "LightStyle with NULL value!\n" ); } // change the string in string table INetworkStringTable *stringTable = sv.GetLightStyleTable(); stringTable->SetStringUserData( style, Q_strlen(val)+1, val ); } virtual void StaticDecal( const Vector& origin, int decalIndex, int entityIndex, int modelIndex, bool lowpriority ) { SVC_BSPDecal decal; decal.m_Pos = origin; decal.m_nDecalTextureIndex = decalIndex; decal.m_nEntityIndex = entityIndex; decal.m_nModelIndex = modelIndex; decal.m_bLowPriority = lowpriority; if ( sv.allowsignonwrites ) { decal.WriteToBuffer( sv.m_Signon ); } else { sv.BroadcastMessage( decal, false, true ); } } void Message_DetermineMulticastRecipients( bool usepas, const Vector& origin, CBitVec< ABSOLUTE_PLAYER_LIMIT >& playerbits ) { SV_DetermineMulticastRecipients( usepas, origin, playerbits ); } /* =============================================================================== MESSAGE WRITING =============================================================================== */ virtual bf_write *EntityMessageBegin( int ent_index, ServerClass * ent_class, bool reliable ) { if ( s_MsgData.started ) { Sys_Error( "EntityMessageBegin: New message started before matching call to EndMessage.\n " ); return NULL; } s_MsgData.Reset(); Assert( ent_class ); s_MsgData.filter = NULL; s_MsgData.reliable = reliable; s_MsgData.started = true; s_MsgData.currentMsg = &s_MsgData.entityMsg; s_MsgData.entityMsg.m_nEntityIndex = ent_index; s_MsgData.entityMsg.m_nClassID = ent_class->m_ClassID; s_MsgData.entityMsg.m_DataOut.Reset(); return &s_MsgData.entityMsg.m_DataOut; } virtual bf_write *UserMessageBegin( IRecipientFilter *filter, int msg_index ) { if ( s_MsgData.started ) { Sys_Error( "UserMessageBegin: New message started before matching call to EndMessage.\n " ); return NULL; } s_MsgData.Reset(); Assert( filter ); s_MsgData.filter = filter; s_MsgData.reliable = filter->IsReliable(); s_MsgData.started = true; s_MsgData.currentMsg = &s_MsgData.userMsg; s_MsgData.userMsg.m_nMsgType = msg_index; s_MsgData.userMsg.m_DataOut.Reset(); return &s_MsgData.userMsg.m_DataOut; } // Validates user message type and checks to see if it's variable length // returns true if variable length int Message_CheckMessageLength() { if ( s_MsgData.currentMsg == &s_MsgData.userMsg ) { char msgname[ 256 ]; int msgsize = -1; int msgtype = s_MsgData.userMsg.m_nMsgType; if ( !serverGameDLL->GetUserMessageInfo( msgtype, msgname, sizeof(msgname), msgsize ) ) { Warning( "Unable to find user message for index %i\n", msgtype ); return -1; } int bytesWritten = s_MsgData.userMsg.m_DataOut.GetNumBytesWritten(); if ( msgsize == -1 ) { if ( bytesWritten > MAX_USER_MSG_DATA ) { Warning( "DLL_MessageEnd: Refusing to send user message %s of %i bytes to client, user message size limit is %i bytes\n", msgname, bytesWritten, MAX_USER_MSG_DATA ); return -1; } } else if ( msgsize != bytesWritten ) { Warning( "User Msg '%s': %d bytes written, expected %d\n", msgname, bytesWritten, msgsize ); return -1; } return bytesWritten; // all checks passed, estimated final length } if ( s_MsgData.currentMsg == &s_MsgData.entityMsg ) { int bytesWritten = s_MsgData.entityMsg.m_DataOut.GetNumBytesWritten(); if ( bytesWritten > MAX_ENTITY_MSG_DATA ) // TODO use a define or so { Warning( "Entity Message to %i, %i bytes written (max is %d)\n", s_MsgData.entityMsg.m_nEntityIndex, bytesWritten, MAX_ENTITY_MSG_DATA ); return -1; } return bytesWritten; // all checks passed, estimated final length } Warning( "MessageEnd unknown message type.\n" ); return -1; } virtual void MessageEnd( void ) { if ( !s_MsgData.started ) { Sys_Error( "MESSAGE_END called with no active message\n" ); return; } int length = Message_CheckMessageLength(); // check to see if it's a valid message if ( length < 0 ) { s_MsgData.Reset(); // clear message data return; } if ( s_MsgData.filter ) { // send entity/user messages only to full connected clients in filter sv.BroadcastMessage( *s_MsgData.currentMsg, *s_MsgData.filter ); } else { // send entity messages to all full connected clients sv.BroadcastMessage( *s_MsgData.currentMsg, true, s_MsgData.reliable ); } s_MsgData.Reset(); // clear message data } /* single print to a specific client */ virtual void ClientPrintf( edict_t *pEdict, const char *szMsg ) { int entnum = NUM_FOR_EDICT( pEdict ); if (entnum < 1 || entnum > sv.GetClientCount() ) { ConMsg ("tried to sprint to a non-client\n"); return; } sv.Client(entnum-1)->ClientPrintf( "%s", szMsg ); } #ifdef SWDS void Con_NPrintf( int pos, const char *fmt, ... ) { } void Con_NXPrintf( const struct con_nprint_s *info, const char *fmt, ... ) { } #else void Con_NPrintf( int pos, const char *fmt, ... ) { if ( IsDedicatedServer() ) return; va_list argptr; char text[4096]; va_start (argptr, fmt); Q_vsnprintf(text, sizeof( text ), fmt, argptr); va_end (argptr); ::Con_NPrintf( pos, "%s", text ); } void Con_NXPrintf( const struct con_nprint_s *info, const char *fmt, ... ) { if ( IsDedicatedServer() ) return; va_list argptr; char text[4096]; va_start (argptr, fmt); Q_vsnprintf(text, sizeof( text ), fmt, argptr); va_end (argptr); ::Con_NXPrintf( info, "%s", text ); } #endif virtual void SetView(const edict_t *clientent, const edict_t *viewent) { int clientnum = NUM_FOR_EDICT( clientent ); if (clientnum < 1 || clientnum > sv.GetClientCount() ) Host_Error ("DLL_SetView: not a client"); CGameClient *client = sv.Client(clientnum-1); client->m_pViewEntity = viewent; SVC_SetView view( NUM_FOR_EDICT(viewent) ); client->SendNetMsg( view ); } virtual float Time(void) { return Sys_FloatTime(); } virtual void CrosshairAngle(const edict_t *clientent, float pitch, float yaw) { int clientnum = NUM_FOR_EDICT( clientent ); if (clientnum < 1 || clientnum > sv.GetClientCount() ) Host_Error ("DLL_Crosshairangle: not a client"); IClient *client = sv.Client(clientnum-1); if (pitch > 180) pitch -= 360; if (pitch < -180) pitch += 360; if (yaw > 180) yaw -= 360; if (yaw < -180) yaw += 360; SVC_CrosshairAngle crossHairMsg; crossHairMsg.m_Angle.x = pitch; crossHairMsg.m_Angle.y = yaw; crossHairMsg.m_Angle.y = 0; client->SendNetMsg( crossHairMsg ); } virtual void GetGameDir( char *szGetGameDir, int maxlength ) { COM_GetGameDir(szGetGameDir, maxlength ); } virtual int CompareFileTime( const char *filename1, const char *filename2, int *iCompare) { return COM_CompareFileTime(filename1, filename2, iCompare); } virtual bool LockNetworkStringTables( bool lock ) { return networkStringTableContainerServer->Lock( lock ); } // For use with FAKE CLIENTS virtual edict_t* CreateFakeClient( const char *netname ) { CGameClient *fcl = static_cast<CGameClient*>( sv.CreateFakeClient( netname ) ); if ( !fcl ) { // server is full return NULL; } return fcl->edict; } // For use with FAKE CLIENTS virtual edict_t* CreateFakeClientEx( const char *netname, bool bReportFakeClient /*= true*/ ) { sv.SetReportNewFakeClients( bReportFakeClient ); edict_t *ret = CreateFakeClient( netname ); sv.SetReportNewFakeClients( true ); // Leave this set as true so other callers of sv.CreateFakeClient behave correctly. return ret; } // Get a keyvalue for s specified client virtual const char *GetClientConVarValue( int clientIndex, const char *name ) { if ( clientIndex < 1 || clientIndex > sv.GetClientCount() ) { DevMsg( 1, "GetClientConVarValue: player invalid index %i\n", clientIndex ); return ""; } return sv.GetClient( clientIndex - 1 )->GetUserSetting( name ); } virtual const char *ParseFile(const char *data, char *token, int maxlen) { return ::COM_ParseFile(data, token, maxlen ); } virtual bool CopyFile( const char *source, const char *destination ) { return ::COM_CopyFile( source, destination ); } virtual void AddOriginToPVS( const Vector& origin ) { ::SV_AddOriginToPVS(origin); } virtual void ResetPVS( byte* pvs, int pvssize ) { ::SV_ResetPVS( pvs, pvssize ); } virtual void SetAreaPortalState( int portalNumber, int isOpen ) { CM_SetAreaPortalState(portalNumber, isOpen); } virtual void SetAreaPortalStates( const int *portalNumbers, const int *isOpen, int nPortals ) { CM_SetAreaPortalStates( portalNumbers, isOpen, nPortals ); } virtual void DrawMapToScratchPad( IScratchPad3D *pPad, unsigned long iFlags ) { worldbrushdata_t *pData = host_state.worldmodel->brush.pShared; if ( !pData ) return; SurfaceHandle_t surfID = SurfaceHandleFromIndex( host_state.worldmodel->brush.firstmodelsurface, pData ); for (int i=0; i< host_state.worldmodel->brush.nummodelsurfaces; ++i, ++surfID) { // Don't bother with nodraw surfaces if( MSurf_Flags( surfID ) & SURFDRAW_NODRAW ) continue; CSPVertList vertList; for ( int iVert=0; iVert < MSurf_VertCount( surfID ); iVert++ ) { int iWorldVert = pData->vertindices[surfID->firstvertindex + iVert]; const Vector &vPos = pData->vertexes[iWorldVert].position; vertList.m_Verts.AddToTail( CSPVert( vPos ) ); } pPad->DrawPolygon( vertList ); } } const CBitVec<MAX_EDICTS>* GetEntityTransmitBitsForClient( int iClientIndex ) { if ( iClientIndex < 0 || iClientIndex >= sv.GetClientCount() ) { Assert( false ); return NULL; } CGameClient *pClient = sv.Client( iClientIndex ); CClientFrame *deltaFrame = pClient->GetClientFrame( pClient->m_nDeltaTick ); if ( !deltaFrame ) return NULL; return &deltaFrame->transmit_entity; } virtual bool IsPaused() { return sv.IsPaused(); } virtual void SetFakeClientConVarValue( edict_t *pEntity, const char *pCvarName, const char *value ) { int clientnum = NUM_FOR_EDICT( pEntity ); if (clientnum < 1 || clientnum > sv.GetClientCount() ) Host_Error ("DLL_SetView: not a client"); CGameClient *client = sv.Client(clientnum-1); if ( client->IsFakeClient() ) { client->SetUserCVar( pCvarName, value ); client->m_bConVarsChanged = true; } } virtual CSharedEdictChangeInfo* GetSharedEdictChangeInfo() { return &g_SharedEdictChangeInfo; } virtual IChangeInfoAccessor *GetChangeAccessor( const edict_t *pEdict ) { return &sv.edictchangeinfo[ NUM_FOR_EDICT( pEdict ) ]; } virtual QueryCvarCookie_t StartQueryCvarValue( edict_t *pPlayerEntity, const char *pCvarName ) { int clientnum = NUM_FOR_EDICT( pPlayerEntity ); if (clientnum < 1 || clientnum > sv.GetClientCount() ) Host_Error( "StartQueryCvarValue: not a client" ); CGameClient *client = sv.Client( clientnum-1 ); return SendCvarValueQueryToClient( client, pCvarName, false ); } // Name of most recently load .sav file virtual char const *GetMostRecentlyLoadedFileName() { #if !defined( SWDS ) return saverestore->GetMostRecentlyLoadedFileName(); #else return ""; #endif } virtual char const *GetSaveFileName() { #if !defined( SWDS ) return saverestore->GetSaveFileName(); #else return ""; #endif } // Tells the engine we can immdiately re-use all edict indices // even though we may not have waited enough time virtual void AllowImmediateEdictReuse( ) { ED_AllowImmediateReuse(); } virtual void MultiplayerEndGame() { #if !defined( SWDS ) g_pMatchmaking->EndGame(); #endif } virtual void ChangeTeam( const char *pTeamName ) { #if !defined( SWDS ) g_pMatchmaking->ChangeTeam( pTeamName ); #endif } virtual void SetAchievementMgr( IAchievementMgr *pAchievementMgr ) { g_pAchievementMgr = pAchievementMgr; } virtual IAchievementMgr *GetAchievementMgr() { return g_pAchievementMgr; } virtual int GetAppID() { return GetSteamAppID(); } virtual bool IsLowViolence(); /* ================= InsertServerCommand Sends text to servers execution buffer localcmd (string) ================= */ virtual void InsertServerCommand( const char *str ) { if ( !str ) { Sys_Error( "InsertServerCommand with NULL string\n" ); } if ( ValidCmd( str ) ) { Cbuf_InsertText( str ); } else { ConMsg( "Error, bad server command %s (InsertServerCommand)\n", str ); } } bool GetPlayerInfo( int ent_num, player_info_t *pinfo ) { // Entity numbers are offset by 1 from the player numbers return sv.GetPlayerInfo( (ent_num-1), pinfo ); } bool IsClientFullyAuthenticated( edict_t *pEdict ) { int entnum = NUM_FOR_EDICT( pEdict ); if (entnum < 1 || entnum > sv.GetClientCount() ) return false; // Entity numbers are offset by 1 from the player numbers CGameClient *client = sv.Client(entnum-1); if ( client ) return client->IsFullyAuthenticated(); return false; } void SetDedicatedServerBenchmarkMode( bool bBenchmarkMode ) { g_bDedicatedServerBenchmarkMode = bBenchmarkMode; if ( bBenchmarkMode ) { extern ConVar sv_stressbots; sv_stressbots.SetValue( (int)1 ); } } // Returns the SteamID of the game server const CSteamID *GetGameServerSteamID() { if ( !Steam3Server().GetGSSteamID().IsValid() ) return NULL; return &Steam3Server().GetGSSteamID(); } // Returns the SteamID of the specified player. It'll be NULL if the player hasn't authenticated yet. const CSteamID *GetClientSteamID( edict_t *pPlayerEdict ) { int entnum = NUM_FOR_EDICT( pPlayerEdict ); return GetClientSteamIDByPlayerIndex( entnum ); } const CSteamID *GetClientSteamIDByPlayerIndex( int entnum ) { if (entnum < 1 || entnum > sv.GetClientCount() ) return NULL; // Entity numbers are offset by 1 from the player numbers CGameClient *client = sv.Client(entnum-1); if ( !client ) return NULL; // Make sure they are connected and Steam ID is valid if ( !client->IsConnected() || !client->m_SteamID.IsValid() ) return NULL; return &client->m_SteamID; } void SetGamestatsData( CGamestatsData *pGamestatsData ) { g_pGamestatsData = pGamestatsData; } CGamestatsData *GetGamestatsData() { return g_pGamestatsData; } virtual IReplaySystem *GetReplay() { return g_pReplay; } virtual int GetClusterCount() { CCollisionBSPData *pBSPData = GetCollisionBSPData(); if ( pBSPData && pBSPData->map_vis ) return pBSPData->map_vis->numclusters; return 0; } virtual int GetAllClusterBounds( bbox_t *pBBoxList, int maxBBox ) { CCollisionBSPData *pBSPData = GetCollisionBSPData(); if ( pBSPData && pBSPData->map_vis && host_state.worldbrush ) { // clamp to max clusters in the map if ( maxBBox > pBSPData->map_vis->numclusters ) { maxBBox = pBSPData->map_vis->numclusters; } // reset all of the bboxes for ( int i = 0; i < maxBBox; i++ ) { ClearBounds( pBBoxList[i].mins, pBBoxList[i].maxs ); } // add each leaf's bounds to the bounds for that cluster for ( int i = 0; i < host_state.worldbrush->numleafs; i++ ) { mleaf_t *pLeaf = &host_state.worldbrush->leafs[i]; // skip solid leaves and leaves with cluster < 0 if ( !(pLeaf->contents & CONTENTS_SOLID) && pLeaf->cluster >= 0 && pLeaf->cluster < maxBBox ) { Vector mins, maxs; mins = pLeaf->m_vecCenter - pLeaf->m_vecHalfDiagonal; maxs = pLeaf->m_vecCenter + pLeaf->m_vecHalfDiagonal; AddPointToBounds( mins, pBBoxList[pLeaf->cluster].mins, pBBoxList[pLeaf->cluster].maxs ); AddPointToBounds( maxs, pBBoxList[pLeaf->cluster].mins, pBBoxList[pLeaf->cluster].maxs ); } } return pBSPData->map_vis->numclusters; } return 0; } virtual int GetServerVersion() const OVERRIDE { return GetSteamInfIDVersionInfo().ServerVersion; } virtual float GetServerTime() const OVERRIDE { return sv.GetTime(); } virtual IServer *GetIServer() OVERRIDE { return (IServer *)&sv; } virtual void SetPausedForced( bool bPaused, float flDuration /*= -1.f*/ ) OVERRIDE { sv.SetPausedForced( bPaused, flDuration ); } private: // Purpose: Sends a temp entity to the client ( follows the format of the original MESSAGE_BEGIN stuff from HL1 virtual void PlaybackTempEntity( IRecipientFilter& filter, float delay, const void *pSender, const SendTable *pST, int classID ); virtual int CheckAreasConnected( int area1, int area2 ); virtual int GetArea( const Vector& origin ); virtual void GetAreaBits( int area, unsigned char *bits, int buflen ); virtual bool GetAreaPortalPlane( Vector const &vViewOrigin, int portalKey, VPlane *pPlane ); virtual client_textmessage_t *TextMessageGet( const char *pName ); virtual void LogPrint(const char * msg); virtual bool LoadGameState( char const *pMapName, bool createPlayers ); virtual void LoadAdjacentEnts( const char *pOldLevel, const char *pLandmarkName ); virtual void ClearSaveDir(); virtual void ClearSaveDirAfterClientLoad(); virtual const char* GetMapEntitiesString(); virtual void BuildEntityClusterList( edict_t *pEdict, PVSInfo_t *pPVSInfo ); virtual void CleanUpEntityClusterList( PVSInfo_t *pPVSInfo ); virtual void SolidMoved( edict_t *pSolidEnt, ICollideable *pSolidCollide, const Vector* pPrevAbsOrigin, bool accurateBboxTriggerChecks ); virtual void TriggerMoved( edict_t *pTriggerEnt, bool accurateBboxTriggerChecks ); virtual ISpatialPartition *CreateSpatialPartition( const Vector& worldmin, const Vector& worldmax ) { return ::CreateSpatialPartition( worldmin, worldmax ); } virtual void DestroySpatialPartition( ISpatialPartition *pPartition ) { ::DestroySpatialPartition( pPartition ); } }; // Backwards-compat shim that inherits newest then provides overrides for the legacy behavior class CVEngineServer22 : public CVEngineServer { virtual int IsMapValid( const char *filename ) OVERRIDE { // For users of the older interface, preserve here the old modelloader behavior of wrapping maps/%.bsp around // the filename. This went away in newer interfaces since maps can now live in other places. char szWrappedName[MAX_PATH] = { 0 }; V_snprintf( szWrappedName, sizeof( szWrappedName ), "maps/%s.bsp", filename ); return modelloader->Map_IsValid( szWrappedName ); } }; //----------------------------------------------------------------------------- // Expose CVEngineServer to the game DLL. //----------------------------------------------------------------------------- static CVEngineServer g_VEngineServer; static CVEngineServer22 g_VEngineServer22; // INTERFACEVERSION_VENGINESERVER_VERSION_21 is compatible with 22 latest since we only added virtuals to the end, so expose that as well. EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CVEngineServer, IVEngineServer021, INTERFACEVERSION_VENGINESERVER_VERSION_21, g_VEngineServer22 ); EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CVEngineServer, IVEngineServer022, INTERFACEVERSION_VENGINESERVER_VERSION_22, g_VEngineServer22 ); EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CVEngineServer, IVEngineServer, INTERFACEVERSION_VENGINESERVER, g_VEngineServer ); // When bumping the version to this interface, check that our assumption is still valid and expose the older version in the same way COMPILE_TIME_ASSERT( INTERFACEVERSION_VENGINESERVER_INT == 23 ); //----------------------------------------------------------------------------- // Expose CVEngineServer to the engine. //----------------------------------------------------------------------------- IVEngineServer *g_pVEngineServer = &g_VEngineServer; //----------------------------------------------------------------------------- // Used to allocate pvs infos //----------------------------------------------------------------------------- static CUtlMemoryPool s_PVSInfoAllocator( 128, 128 * 64, CUtlMemoryPool::GROW_SLOW, "pvsinfopool", 128 ); //----------------------------------------------------------------------------- // Purpose: Sends a temp entity to the client ( follows the format of the original MESSAGE_BEGIN stuff from HL1 // Input : msg_dest - // delay - // *origin - // *recipient - // *pSender - // *pST - // classID - //----------------------------------------------------------------------------- void CVEngineServer::PlaybackTempEntity( IRecipientFilter& filter, float delay, const void *pSender, const SendTable *pST, int classID ) { VPROF( "PlaybackTempEntity" ); // don't add more events to a snapshot than a client can receive if ( sv.m_TempEntities.Count() >= ((1<<CEventInfo::EVENT_INDEX_BITS)-1) ) { // remove oldest effect delete sv.m_TempEntities[0]; sv.m_TempEntities.Remove( 0 ); } // Make this start at 1 classID = classID + 1; // Encode now! ALIGN4 unsigned char data[ CEventInfo::MAX_EVENT_DATA ] ALIGN4_POST; bf_write buffer( "PlaybackTempEntity", data, sizeof(data) ); // write all properties, if init or reliable message delta against zero values if( !SendTable_Encode( pST, pSender, &buffer, classID, NULL, false ) ) { Host_Error( "PlaybackTempEntity: SendTable_Encode returned false (ent %d), overflow? %i\n", classID, buffer.IsOverflowed() ? 1 : 0 ); return; } // create CEventInfo: CEventInfo *newEvent = new CEventInfo; //copy client filter newEvent->filter.AddPlayersFromFilter( &filter ); newEvent->classID = classID; newEvent->pSendTable= pST; newEvent->fire_delay= delay; newEvent->bits = buffer.GetNumBitsWritten(); int size = Bits2Bytes( buffer.GetNumBitsWritten() ); newEvent->pData = new byte[size]; Q_memcpy( newEvent->pData, data, size ); // add to list sv.m_TempEntities[sv.m_TempEntities.AddToTail()] = newEvent; } int CVEngineServer::CheckAreasConnected( int area1, int area2 ) { return CM_AreasConnected(area1, area2); } //----------------------------------------------------------------------------- // Purpose: // Input : *origin - // *bits - // Output : void //----------------------------------------------------------------------------- int CVEngineServer::GetArea( const Vector& origin ) { return CM_LeafArea( CM_PointLeafnum( origin ) ); } void CVEngineServer::GetAreaBits( int area, unsigned char *bits, int buflen ) { CM_WriteAreaBits( bits, buflen, area ); } bool CVEngineServer::GetAreaPortalPlane( Vector const &vViewOrigin, int portalKey, VPlane *pPlane ) { return CM_GetAreaPortalPlane( vViewOrigin, portalKey, pPlane ); } client_textmessage_t *CVEngineServer::TextMessageGet( const char *pName ) { return ::TextMessageGet( pName ); } void CVEngineServer::LogPrint(const char * msg) { g_Log.Print( msg ); } // HACKHACK: Save/restore wrapper - Move this to a different interface bool CVEngineServer::LoadGameState( char const *pMapName, bool createPlayers ) { #ifndef SWDS return saverestore->LoadGameState( pMapName, createPlayers ) != 0; #else return 0; #endif } void CVEngineServer::LoadAdjacentEnts( const char *pOldLevel, const char *pLandmarkName ) { #ifndef SWDS saverestore->LoadAdjacentEnts( pOldLevel, pLandmarkName ); #endif } void CVEngineServer::ClearSaveDir() { #ifndef SWDS saverestore->ClearSaveDir(); #endif } void CVEngineServer::ClearSaveDirAfterClientLoad() { #ifndef SWDS saverestore->RequestClearSaveDir(); #endif } const char* CVEngineServer::GetMapEntitiesString() { return CM_EntityString(); } //----------------------------------------------------------------------------- // Builds PVS information for an entity //----------------------------------------------------------------------------- inline bool SortClusterLessFunc( const int &left, const int &right ) { return left < right; } void CVEngineServer::BuildEntityClusterList( edict_t *pEdict, PVSInfo_t *pPVSInfo ) { int i, j; int topnode; int leafCount; int leafs[MAX_TOTAL_ENT_LEAFS], clusters[MAX_TOTAL_ENT_LEAFS]; int area; CleanUpEntityClusterList( pPVSInfo ); pPVSInfo->m_pClusters = 0; pPVSInfo->m_nClusterCount = 0; pPVSInfo->m_nAreaNum = 0; pPVSInfo->m_nAreaNum2 = 0; if ( !pEdict ) return; ICollideable *pCollideable = pEdict->GetCollideable(); Assert( pCollideable ); if ( !pCollideable ) return; topnode = -1; //get all leafs, including solids Vector vecWorldMins, vecWorldMaxs; pCollideable->WorldSpaceSurroundingBounds( &vecWorldMins, &vecWorldMaxs ); leafCount = CM_BoxLeafnums( vecWorldMins, vecWorldMaxs, leafs, MAX_TOTAL_ENT_LEAFS, &topnode ); // set areas for ( i = 0; i < leafCount; i++ ) { clusters[i] = CM_LeafCluster( leafs[i] ); area = CM_LeafArea( leafs[i] ); if ( area == 0 ) continue; // doors may legally straggle two areas, // but nothing should ever need more than that if ( pPVSInfo->m_nAreaNum && pPVSInfo->m_nAreaNum != area ) { if ( pPVSInfo->m_nAreaNum2 && pPVSInfo->m_nAreaNum2 != area && sv.IsLoading() ) { ConDMsg ("Object touching 3 areas at %f %f %f\n", vecWorldMins[0], vecWorldMins[1], vecWorldMins[2]); } pPVSInfo->m_nAreaNum2 = area; } else { pPVSInfo->m_nAreaNum = area; } } Vector center = (vecWorldMins+vecWorldMaxs) * 0.5f; // calc center pPVSInfo->m_nHeadNode = topnode; // save headnode // save origin pPVSInfo->m_vCenter[0] = center[0]; pPVSInfo->m_vCenter[1] = center[1]; pPVSInfo->m_vCenter[2] = center[2]; if ( leafCount >= MAX_TOTAL_ENT_LEAFS ) { // assume we missed some leafs, and mark by headnode pPVSInfo->m_nClusterCount = -1; return; } pPVSInfo->m_pClusters = pPVSInfo->m_pClustersInline; if ( leafCount >= 16 ) { std::make_heap( clusters, clusters + leafCount, SortClusterLessFunc ); std::sort_heap( clusters, clusters + leafCount, SortClusterLessFunc ); for ( i = 0; i < leafCount; i++ ) { if ( clusters[i] == -1 ) continue; // not a visible leaf if ( ( i > 0 ) && ( clusters[i] == clusters[i-1] ) ) continue; if ( pPVSInfo->m_nClusterCount == MAX_FAST_ENT_CLUSTERS ) { unsigned short *pClusters = (unsigned short *)s_PVSInfoAllocator.Alloc(); memcpy( pClusters, pPVSInfo->m_pClusters, MAX_FAST_ENT_CLUSTERS * sizeof(unsigned short) ); pPVSInfo->m_pClusters = pClusters; } else if ( pPVSInfo->m_nClusterCount == MAX_ENT_CLUSTERS ) { // assume we missed some leafs, and mark by headnode s_PVSInfoAllocator.Free( pPVSInfo->m_pClusters ); pPVSInfo->m_pClusters = 0; pPVSInfo->m_nClusterCount = -1; break; } pPVSInfo->m_pClusters[pPVSInfo->m_nClusterCount++] = (short)clusters[i]; } return; } for ( i = 0; i < leafCount; i++ ) { if ( clusters[i] == -1 ) continue; // not a visible leaf for ( j = 0; j < i; j++ ) { if ( clusters[j] == clusters[i] ) break; } if ( j != i ) continue; if ( pPVSInfo->m_nClusterCount == MAX_FAST_ENT_CLUSTERS ) { unsigned short *pClusters = (unsigned short*)s_PVSInfoAllocator.Alloc(); memcpy( pClusters, pPVSInfo->m_pClusters, MAX_FAST_ENT_CLUSTERS * sizeof(unsigned short) ); pPVSInfo->m_pClusters = pClusters; } else if ( pPVSInfo->m_nClusterCount == MAX_ENT_CLUSTERS ) { // assume we missed some leafs, and mark by headnode s_PVSInfoAllocator.Free( pPVSInfo->m_pClusters ); pPVSInfo->m_pClusters = 0; pPVSInfo->m_nClusterCount = -1; break; } pPVSInfo->m_pClusters[pPVSInfo->m_nClusterCount++] = (short)clusters[i]; } } //----------------------------------------------------------------------------- // Cleans up the cluster list //----------------------------------------------------------------------------- void CVEngineServer::CleanUpEntityClusterList( PVSInfo_t *pPVSInfo ) { if ( pPVSInfo->m_nClusterCount > MAX_FAST_ENT_CLUSTERS ) { s_PVSInfoAllocator.Free( pPVSInfo->m_pClusters ); pPVSInfo->m_pClusters = 0; pPVSInfo->m_nClusterCount = 0; } } //----------------------------------------------------------------------------- // Adds a handle to the list of entities to update when a partition query occurs //----------------------------------------------------------------------------- void CVEngineServer::SolidMoved( edict_t *pSolidEnt, ICollideable *pSolidCollide, const Vector* pPrevAbsOrigin, bool accurateBboxTriggerChecks ) { SV_SolidMoved( pSolidEnt, pSolidCollide, pPrevAbsOrigin, accurateBboxTriggerChecks ); } void CVEngineServer::TriggerMoved( edict_t *pTriggerEnt, bool accurateBboxTriggerChecks ) { SV_TriggerMoved( pTriggerEnt, accurateBboxTriggerChecks ); } //----------------------------------------------------------------------------- // Called by the server to determine violence settings. //----------------------------------------------------------------------------- bool CVEngineServer::IsLowViolence() { return g_bLowViolence; }
26.071768
159
0.652338
IamIndeedGamingAsHardAsICan03489
c10c7a43c480235d208526c1abf035cec9f8a363
62
cpp
C++
source/lib.cpp
vsdmars/sing
6c84c4c92c446b119291d205a50df450ae994326
[ "Unlicense" ]
null
null
null
source/lib.cpp
vsdmars/sing
6c84c4c92c446b119291d205a50df450ae994326
[ "Unlicense" ]
null
null
null
source/lib.cpp
vsdmars/sing
6c84c4c92c446b119291d205a50df450ae994326
[ "Unlicense" ]
null
null
null
#include "lib.hpp" library::library() : name("sing") { }
8.857143
18
0.564516
vsdmars
c10d66994ef114033e8fe779172cf9ddc10c4bdc
566
hh
C++
src/proof-fwd.hh
ciaranm/certified-constraint-solver
986b0149341474f911977f3093b1224ada90f605
[ "MIT" ]
null
null
null
src/proof-fwd.hh
ciaranm/certified-constraint-solver
986b0149341474f911977f3093b1224ada90f605
[ "MIT" ]
null
null
null
src/proof-fwd.hh
ciaranm/certified-constraint-solver
986b0149341474f911977f3093b1224ada90f605
[ "MIT" ]
1
2019-08-21T03:29:11.000Z
2019-08-21T03:29:11.000Z
/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #ifndef CERTIFIED_CONSTRAINT_SOLVER_GUARD_SRC_PROOF_FWD_HH #define CERTIFIED_CONSTRAINT_SOLVER_GUARD_SRC_PROOF_FWD_HH 1 #include "strong_typedef.hpp" #include <string> struct Proof; using UnderlyingVariableID = jss::strong_typedef<struct UnderlyingVariableIDTag, std::string, jss::strong_typedef_properties::streamable>; using ProofLineNumber = jss::strong_typedef<struct ProofLineNumberTag, int, jss::strong_typedef_properties::comparable, jss::strong_typedef_properties::streamable>; #endif
29.789474
93
0.803887
ciaranm
c10f3febab8b3be2d570fec9be19669791f9ceb8
7,311
cpp
C++
tests/Unit/IO/Observers/Test_ReductionObserver.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
tests/Unit/IO/Observers/Test_ReductionObserver.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
tests/Unit/IO/Observers/Test_ReductionObserver.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #include "tests/Unit/TestingFramework.hpp" #include <cstddef> #include <functional> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "DataStructures/Matrix.hpp" #include "Domain/ElementId.hpp" #include "Domain/ElementIndex.hpp" #include "IO/H5/AccessType.hpp" #include "IO/H5/Dat.hpp" #include "IO/H5/File.hpp" #include "IO/Observer/Actions.hpp" // IWYU pragma: keep #include "IO/Observer/ArrayComponentId.hpp" #include "IO/Observer/Initialize.hpp" // IWYU pragma: keep #include "IO/Observer/ObservationId.hpp" #include "IO/Observer/ObserverComponent.hpp" // IWYU pragma: keep #include "IO/Observer/ReductionActions.hpp" // IWYU pragma: keep #include "IO/Observer/Tags.hpp" // IWYU pragma: keep #include "IO/Observer/TypeOfObservation.hpp" #include "Parallel/ArrayIndex.hpp" #include "Parallel/Reduction.hpp" #include "Utilities/FileSystem.hpp" #include "Utilities/Functional.hpp" #include "Utilities/Numeric.hpp" #include "Utilities/TaggedTuple.hpp" #include "tests/Unit/ActionTesting.hpp" #include "tests/Unit/IO/Observers/ObserverHelpers.hpp" // NOLINTNEXTLINE(google-build-using-namespace) using namespace TestObservers_detail; SPECTRE_TEST_CASE("Unit.IO.Observers.ReductionObserver", "[Unit][Observers]") { using TupleOfMockDistributedObjects = typename ActionTesting::MockRuntimeSystem< Metavariables>::TupleOfMockDistributedObjects; using obs_component = observer_component<Metavariables>; using obs_writer = observer_writer_component<Metavariables>; using element_comp = element_component<Metavariables>; using MockRuntimeSystem = ActionTesting::MockRuntimeSystem<Metavariables>; using ObserverMockDistributedObjectsTag = typename MockRuntimeSystem::template MockDistributedObjectsTag< obs_component>; using WriterMockDistributedObjectsTag = typename MockRuntimeSystem::template MockDistributedObjectsTag< obs_writer>; using ElementMockDistributedObjectsTag = typename MockRuntimeSystem::template MockDistributedObjectsTag< element_comp>; TupleOfMockDistributedObjects dist_objects{}; tuples::get<ObserverMockDistributedObjectsTag>(dist_objects) .emplace(0, ActionTesting::MockDistributedObject<obs_component>{}); tuples::get<WriterMockDistributedObjectsTag>(dist_objects) .emplace(0, ActionTesting::MockDistributedObject<obs_writer>{}); // Specific IDs have no significance, just need different IDs. const std::vector<ElementId<2>> element_ids{{1, {{{1, 0}, {1, 0}}}}, {1, {{{1, 1}, {1, 0}}}}, {1, {{{1, 0}, {2, 3}}}}, {1, {{{1, 0}, {5, 4}}}}, {0, {{{1, 0}, {1, 0}}}}}; for (const auto& id : element_ids) { tuples::get<ElementMockDistributedObjectsTag>(dist_objects) .emplace(ElementIndex<2>{id}, ActionTesting::MockDistributedObject<element_comp>{}); } tuples::TaggedTuple<observers::OptionTags::ReductionFileName, observers::OptionTags::VolumeFileName> cache_data{}; const auto& output_file_prefix = tuples::get<observers::OptionTags::ReductionFileName>(cache_data) = "./Unit.IO.Observers.ReductionObserver"; ActionTesting::MockRuntimeSystem<Metavariables> runner{ cache_data, std::move(dist_objects)}; runner.simple_action<obs_component, observers::Actions::Initialize<Metavariables>>(0); runner.simple_action<obs_writer, observers::Actions::InitializeWriter<Metavariables>>(0); // Register elements for (const auto& id : element_ids) { runner.simple_action<element_comp, observers::Actions::RegisterWithObservers< observers::TypeOfObservation::Reduction>>(id, 0); // Invoke the simple_action RegisterSenderWithSelf that was called on the // observer component by the RegisterWithObservers action. runner.invoke_queued_simple_action<obs_component>(0); } const std::string h5_file_name = output_file_prefix + ".h5"; if (file_system::check_if_file_exists(h5_file_name)) { file_system::rm(h5_file_name, true); } using Redum = Parallel::ReductionDatum<double, funcl::Plus<>, funcl::Sqrt<funcl::Divides<>>, std::index_sequence<1>>; using ReData = Parallel::ReductionData< Parallel::ReductionDatum<double, funcl::AssertEqual<>>, Parallel::ReductionDatum<size_t, funcl::Plus<>>, Redum, Redum>; const auto make_fake_reduction_data = []( const observers::ArrayComponentId& id, const double time) noexcept { const auto hashed_id = static_cast<double>(std::hash<observers::ArrayComponentId>{}(id)); constexpr size_t number_of_grid_points = 4; const double error0 = 1.0e-10 * hashed_id + time; const double error1 = 1.0e-12 * hashed_id + 2 * time; return ReData{time, number_of_grid_points, error0, error1}; }; const TimeId time(3); const std::vector<std::string> legend{"Time", "NumberOfPoints", "Error0", "Error1"}; // Test passing reduction data. for (const auto& id : element_ids) { const observers::ArrayComponentId array_id( std::add_pointer_t<element_comp>{nullptr}, Parallel::ArrayIndex<ElementIndex<2>>{ElementIndex<2>{id}}); auto reduction_data_fakes = make_fake_reduction_data(array_id, time.value()); runner.simple_action<obs_component, observers::Actions::ContributeReductionData>( 0, observers::ObservationId(time), legend, std::move(reduction_data_fakes)); } // Invke the threaded action 'WriteReductionData' to write reduction data to // disk. runner.invoke_queued_threaded_action<obs_writer>(0); // Check that the H5 file was written correctly. { const auto file = h5::H5File<h5::AccessType::ReadOnly>(h5_file_name); const auto& dat_file = file.get<h5::Dat>("/element_data"); const Matrix written_data = dat_file.get_data(); const auto& written_legend = dat_file.get_legend(); CHECK(written_legend == legend); const auto expected = alg::accumulate( element_ids, ReData(time.value(), 0, 0.0, 0.0), [&time, &make_fake_reduction_data ]( ReData state, const ElementId<2>& id) noexcept { const observers::ArrayComponentId array_id( std::add_pointer_t<element_comp>{nullptr}, Parallel::ArrayIndex<ElementIndex<2>>{ElementIndex<2>{id}}); return state.combine( make_fake_reduction_data(array_id, time.value())); }) .finalize() .data(); CHECK(std::get<0>(expected) == written_data(0, 0)); CHECK(std::get<1>(expected) == written_data(0, 1)); CHECK(std::get<2>(expected) == written_data(0, 2)); CHECK(std::get<3>(expected) == written_data(0, 3)); } if (file_system::check_if_file_exists(h5_file_name)) { file_system::rm(h5_file_name, true); } }
42.754386
79
0.669265
marissawalker
c113ea03e9db5a31e4a47dc40a69e4463857cd95
2,038
cpp
C++
Engine/src/Platform/RayTracer/Samplers/MultiJittered.cpp
jeroennelis/Engine
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
[ "Apache-2.0" ]
null
null
null
Engine/src/Platform/RayTracer/Samplers/MultiJittered.cpp
jeroennelis/Engine
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
[ "Apache-2.0" ]
null
null
null
Engine/src/Platform/RayTracer/Samplers/MultiJittered.cpp
jeroennelis/Engine
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
[ "Apache-2.0" ]
null
null
null
#include "enpch.h" #include "MultiJittered.h" #include "Engine/Maths.h" namespace Engine { MultiJittered::MultiJittered() :Sampler() { generate_samples(); } MultiJittered::MultiJittered(const int numSamples) : Sampler(numSamples) { generate_samples(); } MultiJittered::MultiJittered(const int numSamples, const int numSet) : Sampler(numSamples, numSet) { generate_samples(); } MultiJittered::MultiJittered(const MultiJittered& mj) : Sampler(mj) { } MultiJittered::~MultiJittered() { } void MultiJittered::generate_samples(void) { // num_samples needs to be a perfect square int n = (int)sqrt((float)num_samples); float subcell_width = 1.0 / ((float)num_samples); // fill the samples array with dummy points to allow us to use the [ ] notation when we set the // initial patterns glm::vec2 fill_point; for (int j = 0; j < num_samples * num_sets; j++) samples.push_back(fill_point); // distribute points in the initial patterns for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { samples[i * n + j + p * num_samples].x = (i * n + j) * subcell_width + rand_float(0, subcell_width); samples[i * n + j + p * num_samples].y = (j * n + i) * subcell_width + rand_float(0, subcell_width); } // shuffle x coordinates for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int k = rand_int(j, n - 1); float t = samples[i * n + j + p * num_samples].x; samples[i * n + j + p * num_samples].x = samples[i * n + k + p * num_samples].x; samples[i * n + k + p * num_samples].x = t; } // shuffle y coordinates for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int k = rand_int(j, n - 1); float t = samples[j * n + i + p * num_samples].y; samples[j * n + i + p * num_samples].y = samples[k * n + i + p * num_samples].y; samples[k * n + i + p * num_samples].y = t; } } }
24.261905
105
0.594701
jeroennelis
c114d89d3f36bf5664fa842d7f1bf9c3ddded22e
1,016
cpp
C++
Backtracking/letter_phone.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Backtracking/letter_phone.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Backtracking/letter_phone.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; map<char, vector<char>> m; string current; void util(string &A, int i, vector<string> &ans) { if(i >= A.size()) { ans.push_back(current); return; } for(char ch: m[A[i]]) { current.push_back(ch); util(A, i + 1, ans); current.pop_back(); } } vector<string> letterCombinations(string A) { m.insert({'1', vector<char>{'1'}}); m.insert({'2', vector<char>{'a', 'b', 'c'}}); m.insert({'3', vector<char>{'d', 'e', 'f'}}); m.insert({'4', vector<char>{'g', 'h', 'i'}}); m.insert({'5', vector<char>{'j', 'k', 'l'}}); m.insert({'6', vector<char>{'m', 'n', 'o'}}); m.insert({'7', vector<char>{'p', 'q', 'r', 's'}}); m.insert({'8', vector<char>{'t', 'u', 'v'}}); m.insert({'9', vector<char>{'w', 'x', 'y', 'z'}}); m.insert({'0', vector<char>{'0'}}); vector<string> ans; util(A, 0, ans); sort(ans.begin(), ans.end()); return ans; } int main(void) { string s; cin >> s; for(string a: letterCombinations(s)) { cout << a << endl; } return 0; }
20.734694
51
0.540354
aneesh001
c11682a871c77334bfadcc50e6e2df9c4b193e48
6,416
cpp
C++
plugins/QGames/Tga.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
1
2020-07-19T10:19:18.000Z
2020-07-19T10:19:18.000Z
plugins/QGames/Tga.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
null
null
null
plugins/QGames/Tga.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Tga.cpp /////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Joe Riedel // 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 the <ORGANIZATION> 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. /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Tga.h" #include "ByteParser.h" #include <algorithm> static bool UnpackTGAByte3(unsigned char *DestBuffer,const unsigned char *InputPtr,int Pixels, int buffLength) { int Count; do { if (buffLength<1) return false; Count = *InputPtr++; /* Get the counter */ if (Count&0x80) { /* Packed? */ if (buffLength<3) return false; unsigned short Temp; unsigned char Temp2; Count = Count-0x7F; /* Remove the high bit */ Pixels = Pixels-Count; Temp = LoadIntelShort(((const unsigned short *)(InputPtr+1))[0]); /* Get G,R */ Temp2 = InputPtr[0]; /* Blue */ InputPtr = InputPtr+3; buffLength -= 3; do { ((unsigned short *)DestBuffer)[0] = Temp; /* R and G */ DestBuffer[2] = Temp2; /* Blue */ DestBuffer = DestBuffer+3; } while (--Count); } else { ++Count; /* +1 to the count */ if (buffLength<Count) return false; Pixels = Pixels-Count; /* Adjust amount */ buffLength -= Count; do { DestBuffer[0] = InputPtr[2]; /* Red */ DestBuffer[1] = InputPtr[1]; /* Green */ DestBuffer[2] = InputPtr[0]; /* Blue */ DestBuffer = DestBuffer+3; /* Next index */ InputPtr = InputPtr+3; } while (--Count); /* All done? */ } } while (Pixels>0); /* Is there still more? */ return true; } static bool UnpackTGALong(unsigned char *DestBuffer,const unsigned char *InputPtr,int Pixels, int buffLength) { int Count; do { if (buffLength<1) return false; Count = *InputPtr++; /* Get the counter */ if (Count&0x80) { /* Packed? */ if (buffLength<4) return false; unsigned int Temp; Count = Count-0x7F; /* Remove the high bit and add 1 */ Pixels = Pixels-Count; ((unsigned char *)&Temp)[0] = InputPtr[2]; /* Red */ ((unsigned char *)&Temp)[1] = InputPtr[1]; /* Green */ ((unsigned char *)&Temp)[2] = InputPtr[0]; /* Blue */ ((unsigned char *)&Temp)[3] = InputPtr[3]; /* Alpha */ InputPtr = InputPtr+4; buffLength -= 4; do { ((unsigned int *)DestBuffer)[0] = Temp; /* Fill memory */ DestBuffer = DestBuffer+4; } while (--Count); } else { ++Count; /* +1 to the count */ if (buffLength<Count) return false; Pixels = Pixels-Count; /* Adjust amount */ buffLength -= Count; do { DestBuffer[0] = InputPtr[2]; /* Red */ DestBuffer[1] = InputPtr[1]; /* Green */ DestBuffer[2] = InputPtr[0]; /* Blue */ DestBuffer[3] = InputPtr[3]; /* Alpha */ InputPtr = InputPtr+4; DestBuffer = DestBuffer+4; } while (--Count); /* All done? */ } } while (Pixels>0); /* Is there still more? */ return true; } bool CTga::IsTga(const void *buff, int len) { if (len < 18) return false; const unsigned char *ptr = reinterpret_cast<const unsigned char*>(buff); return ptr[2] == 2 || ptr[2] == 10; } bool CTga::ReadInfo(const void *buff, int len, int *width, int *height, int *bpp) { if (!IsTga(buff, len)) return false; CByteParser parser(buff, len); parser.Skip(12); *width = parser.ReadShort(); *height = parser.ReadShort(); int bits = parser.ReadByte(); *bpp = bits / 8; return true; } bool CTga::Read(const void *buff, int len, void **dst, int *width, int *height, int *bpp) { if (!IsTga(buff, len)) return false; CByteParser parser(buff, len); int tagLen = parser.ReadByte(); parser.Skip(1); int type = parser.ReadByte(); parser.Skip(9); //int xorg = parser.ReadShort(); //int yorg = parser.ReadShort(); *width = parser.ReadShort(); *height = parser.ReadShort(); int bits = parser.ReadByte(); *bpp = bits / 8; int flags = parser.ReadByte(); parser.Skip(tagLen); int imgLen = *width * *height * *bpp; len = parser.Left(); if (!len) return false; unsigned char *ptr = new unsigned char[len]; parser.Read(ptr, len); switch (type) { case 2: // BGR uncompressed { *dst = ptr; } break; case 10: // BGR rle { *dst = new unsigned char[imgLen]; if (*bpp == 3) { UnpackTGAByte3((unsigned char*)*dst, ptr, imgLen / *bpp, len); } else { UnpackTGALong((unsigned char*)*dst, ptr, imgLen / *bpp, len); } delete [] ptr; ptr = (unsigned char*)*dst; } break; } unsigned char *work = ptr; for (int i = 0; i < imgLen/(*bpp); ++i) { std::swap(work[0], work[2]); work += *bpp; } if ((flags&32) == 0) { int scan = *width * *bpp; unsigned char *swap = new unsigned char[scan]; for (int y = 0; y < *height/2 ; ++y) { int flipY = *height - y - 1; void *a = &ptr[y * scan]; void *b = &ptr[flipY * scan]; memcpy(swap, a, scan); memcpy(a, b, scan); memcpy(b, swap, scan); } delete [] swap; } // a2l return true; }
30.552381
110
0.618142
joeriedel
c117aaceae41803129778da51a659d80452bd47c
3,871
cpp
C++
cnes/src/otb/Noise.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
null
null
null
cnes/src/otb/Noise.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
null
null
null
cnes/src/otb/Noise.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
1
2019-11-02T11:01:58.000Z
2019-11-02T11:01:58.000Z
//---------------------------------------------------------------------------- // // "Copyright Centre National d'Etudes Spatiales" // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #include <otb/Noise.h> #include <ossim/base/ossimDpt3d.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimNotify.h> #include <ossim/base/ossimString.h> namespace ossimplugins { static const char NOISE[] = "noise"; static const char NUMBER_OF_NOISE_RECORDS_KW[] = "numberOfNoiseRecords"; static const char NAME_OF_NOISE_POLARISATION_KW[] = "nameOfNoisePolarisation"; Noise::Noise(): _numberOfNoiseRecords(0), _tabImageNoise(), _polarisation("UNDEFINED") { } Noise::~Noise() { } Noise::Noise(const Noise& rhs): _numberOfNoiseRecords(rhs._numberOfNoiseRecords), _tabImageNoise(rhs._tabImageNoise), _polarisation(rhs._polarisation) { } Noise& Noise::operator=(const Noise& rhs) { _numberOfNoiseRecords = rhs._numberOfNoiseRecords; _tabImageNoise = rhs._tabImageNoise; _polarisation = rhs._polarisation; return *this; } bool Noise::saveState(ossimKeywordlist& kwl, const char* prefix) const { std::string pfx; if (prefix) { pfx = prefix; } pfx += NOISE; std::string s = pfx + "." + NAME_OF_NOISE_POLARISATION_KW; kwl.add(prefix, s.c_str(), _polarisation); s = pfx + "." + NUMBER_OF_NOISE_RECORDS_KW; kwl.add(prefix, s.c_str(), _numberOfNoiseRecords); for (unsigned int i = 0; i < _tabImageNoise.size(); ++i) { ossimString s2 = pfx + "[" + ossimString::toString(i).c_str() + "]"; _tabImageNoise[i].saveState(kwl, s2.c_str()); } return true; } bool Noise::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "Noise::loadState"; bool result = true; std::string pfx(""); if (prefix) { pfx = prefix; } pfx += NOISE; ossimString s; const char* lookup = 0; std::string s1 = pfx + "."; lookup = kwl.find(s1.c_str(), NAME_OF_NOISE_POLARISATION_KW); if (lookup) { _polarisation = lookup; } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Keyword not found: " << NAME_OF_NOISE_POLARISATION_KW << "\n"; result = false; } lookup = kwl.find(s1.c_str(), NUMBER_OF_NOISE_RECORDS_KW); if (lookup) { s = lookup; _numberOfNoiseRecords = s.toUInt32(); } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Keyword not found: " << NUMBER_OF_NOISE_RECORDS_KW << "\n"; result = false; } _tabImageNoise.clear(); for (unsigned int i = 0; i < _numberOfNoiseRecords; ++i) { std::string s2 = pfx + "[" + ossimString::toString(i).c_str() + "]"; ImageNoise in; result = in.loadState(kwl, s2.c_str()); _tabImageNoise.push_back(in); } if( _numberOfNoiseRecords != _tabImageNoise.size() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Keyword " << NUMBER_OF_NOISE_RECORDS_KW << " is different with the number of ImageNoise nodes \n"; } return result; } std::ostream& Noise::print(std::ostream& out) const { out << setprecision(15) << setiosflags(ios::fixed) << "\n Noise class data members:\n"; const char* prefix = 0; ossimKeywordlist kwl; ossimString pfx; pfx += NOISE; ossimString s = pfx + "." + NUMBER_OF_NOISE_RECORDS_KW; kwl.add(prefix, s.c_str(), _numberOfNoiseRecords); s = pfx + "." + NAME_OF_NOISE_POLARISATION_KW; kwl.add(prefix, s.chars(), _polarisation); for (unsigned int i = 0; i < _tabImageNoise.size(); ++i) { ossimString s2 = pfx + "[" + ossimString::toString(i).c_str() + "]"; _tabImageNoise[i].saveState(kwl, s2.c_str()); } out << kwl; return out; } }
24.043478
122
0.624128
dardok
c12061ea6d495f6cbb54a586ee13c5faac0dcc83
2,550
hpp
C++
source/xyo/xyo-managedmemory-tsingletonprocess.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
source/xyo/xyo-managedmemory-tsingletonprocess.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
source/xyo/xyo-managedmemory-tsingletonprocess.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
// // XYO // // Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com> // Created by Grigore Stefan <g_stefan@yahoo.com> // // MIT License (MIT) <http://opensource.org/licenses/MIT> // #ifndef XYO_MANAGEDMEMORY_TSINGLETONPROCESS_HPP #define XYO_MANAGEDMEMORY_TSINGLETONPROCESS_HPP #ifndef XYO_MANAGEDMEMORY_TMEMORYSYSTEM_HPP #include "xyo-managedmemory-tmemorysystem.hpp" #endif #ifndef XYO_MANAGEDMEMORY_REGISTRYPROCESS_HPP #include "xyo-managedmemory-registryprocess.hpp" #endif #ifndef XYO_MULTITHREADING_TATOMIC_HPP #include "xyo-multithreading-tatomic.hpp" #endif namespace XYO { namespace ManagedMemory { using namespace XYO::Multithreading; template<typename T> class TSingletonProcess { XYO_DISALLOW_COPY_ASSIGN_MOVE(TSingletonProcess); protected: inline TSingletonProcess() { }; public: static TAtomic<T *> singletonLink; static const char *registryKey(); static void resourceDelete(void *); static void resourceFinalizer(void *); static inline T *getValue() { T *retV = singletonLink.get(); if(retV == nullptr) { initMemory(); return singletonLink.get(); }; return retV; }; static inline void initMemory() { void *registryLink; if(RegistryProcess::checkAndRegisterKey(registryKey(), registryLink, [] { return (singletonLink.get() == nullptr); }, [](void *this__) { T *this_ = reinterpret_cast<T *> (this__); singletonLink.set(this_); })) { TMemorySystem<T>::initMemory(); T *this_ = TMemorySystem<T>::newMemory(); TIfHasIncReferenceCount<T>::incReferenceCount(this_); singletonLink.set(this_); RegistryProcess::setValue( registryLink, RegistryLevel::Singleton, this_, resourceDelete, (THasActiveFinalizer<T>::value) ? resourceFinalizer : nullptr); }; }; }; template<typename T> const char *TSingletonProcess<T>::registryKey() { return typeid(TSingletonProcess<T>).name(); }; template<typename T> TAtomic<T *> TSingletonProcess<T>::singletonLink(nullptr); template<typename T> void TSingletonProcess<T>::resourceDelete(void *this_) { TMemorySystem<T>::deleteMemory(reinterpret_cast<T *>(this_)); }; template<typename T> void TSingletonProcess<T>::resourceFinalizer(void *this_) { TIfHasActiveFinalizer<T>::activeFinalizer(reinterpret_cast<T *>(this_)); }; }; }; #endif
24.056604
79
0.663137
g-stefan
c1233652cc2ab2625d61c8c01b8fe368ad956c66
1,152
cpp
C++
Plugins/org.blueberry.core.runtime/src/internal/berryRegistryContributor.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Plugins/org.blueberry.core.runtime/src/internal/berryRegistryContributor.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.blueberry.core.runtime/src/internal/berryRegistryContributor.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryRegistryContributor.h" namespace berry { RegistryContributor::RegistryContributor(const QString& actualId, const QString& actualName, const QString& hostId, const QString& hostName) : actualContributorId(actualId), actualContributorName(actualName) { if (!hostId.isEmpty()) { this->hostId = hostId; this->hostName = hostName; } else { this->hostId = actualId; this->hostName = actualName; } } QString RegistryContributor::GetActualId() const { return actualContributorId; } QString RegistryContributor::GetActualName() const { return actualContributorName; } QString RegistryContributor::GetId() const { return hostId; } QString RegistryContributor::GetName() const { return hostName; } }
21.333333
92
0.633681
zhaomengxiao
c12754fe654a4374f75083a3e645efd115126352
6,148
cc
C++
src/app.cc
PaoJiao/slide
fccdcac94e951de113b8f0116084c41974e956da
[ "MIT" ]
null
null
null
src/app.cc
PaoJiao/slide
fccdcac94e951de113b8f0116084c41974e956da
[ "MIT" ]
null
null
null
src/app.cc
PaoJiao/slide
fccdcac94e951de113b8f0116084c41974e956da
[ "MIT" ]
null
null
null
#include "app.h" #include "debug_print.h" namespace slide { App::App(void) { wview_.title = "Slide"; wview_.url = html_data_uri; wview_.width = 480; wview_.height = 320; wview_.resizable = 1; wview_.userdata = this; // The callback for when a webview event is invoked is the handleCommand // method wview_.external_invoke_cb = [](struct webview *w, const char *data) { App *app = static_cast<App *>(w->userdata); app->HandleCommand(data); }; // Command Pattern used. // These must be static to prevent segfault // If new commands are required, just make it here, then // add it's command string to the map as done here. static CreateFileCmd create; static OpenFileCmd open; static ExportPdfCmd pdf; static SetPreviewSizeCmd prev; static SetTextCmd text; static SetPaletteCmd pal; static SetCursorCmd cur; cmds_map_["create_file"] = &create; cmds_map_["open_file"] = &open; cmds_map_["export_pdf"] = &pdf; cmds_map_["set_preview_size"] = &prev; cmds_map_["set_palette"] = &pal; cmds_map_["set_text"] = &text; cmds_map_["set_cursor"] = &cur; } void App::Run(void) { webview_init(&wview_); webview_dispatch(&wview_, [](struct webview *w, void *arg) { App *app = static_cast<App *>(w->userdata); webview_eval(w, CssInject(styles_css).c_str()); webview_eval(w, picodom_js); webview_eval(w, app_js); }, nullptr); while (webview_loop(&wview_, 1) == 0) { /* Intentionally Blank */ } webview_exit(&wview_); } void App::HandleCommand(const std::string &data) { auto json = nlohmann::json::parse(data); auto cmd = json.at("cmd").get<std::string>(); // If the command isn't found, but we try to access it the command_map will // add the key with a null value, so before accessing confirm it's in the map if (cmds_map_.find(cmd) == cmds_map_.end()) { debug_print(cmd << " is not a valid command"); return; } cmds_map_[cmd]->Execute(*this, json); Render(); } void App::RenderCurrentSlide(void) { if (current_slide_ != -1) { debug_print("App::RenderCurrentSlide()"); debug_print("app instance details: " << *this); PNG png(preview_size_.Width(), preview_size_.Height()); slide::Render(png, deck_[current_slide_], foreground_, background_); debug_print("App::RenderCurrentSlide() render complete"); preview_data_uri_ = png.DataUri(); } } void App::Render(void) { auto json = nlohmann::json({}); json["text"] = current_text_; json["previewDataURI"] = preview_data_uri_; // std::cerr << "JSON Dump: " << json.dump() << std::endl; webview_eval( &wview_, ("window.app.state=" + json.dump() + "; window.render()").c_str()); } //----------- Below here is the command implementations for each key in the // command map. // If adding a new command simply add it here. void CreateFileCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Creating File" << std::endl; char path[PATH_MAX]; webview_dialog(&app.webview(), WEBVIEW_DIALOG_TYPE_SAVE, 0, "New presentation...", nullptr, path, PATH_MAX - 1); if (std::string(path).length() != 0) { app.CurrentFile() = std::string(path); webview_set_title(&app.webview(), ("Slide - " + app.CurrentFile()).c_str()); } } void OpenFileCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Opening File" << std::endl; char path[PATH_MAX]; webview_dialog(&app.webview(), WEBVIEW_DIALOG_TYPE_OPEN, 0, "Open presentation...", nullptr, path, sizeof(path) - 1); if (std::string(path).length() != 0) { app.CurrentFile() = path; webview_set_title(&app.webview(), ("Slide - " + app.CurrentFile()).c_str()); std::ifstream ifs(app.CurrentFile()); std::string text((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); app.CurrentText() = text; app.Deck() = slide::Parse(app.CurrentText()); } } void ExportPdfCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Exporting to PDF" << std::endl; char path[PATH_MAX]; webview_dialog(&app.webview(), WEBVIEW_DIALOG_TYPE_SAVE, 0, "Export PDF...", nullptr, path, sizeof(path) - 1); if (strlen(path) != 0) { std::string path_str(path); const std::string extension(".pdf"); if (path_str.length() <= extension.length() || path_str.compare(path_str.length() - extension.length(), extension.length(), extension)) { path_str += extension; } // std::cerr << "writing to " << path_str << std::endl; PDF pdf(path_str, 640, 480); for (auto slide : app.Deck()) { pdf.BeginPage(); slide::Render(pdf, slide, app.Foreground(), app.Background()); pdf.EndPage(); } } } void SetPreviewSizeCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Setting Preview Size" << std::endl; app.PreviewSize().Width() = json.at("w").get<int>(); app.PreviewSize().Height() = json.at("h").get<int>(); app.RenderCurrentSlide(); } void SetPaletteCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Setting palette" << std::endl; app.Foreground() = json.at("fg").get<int>(); app.Background() = json.at("bg").get<int>(); app.RenderCurrentSlide(); } void SetTextCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Setting Text" << std::endl; app.CurrentText() = json.at("text").get<std::string>(); app.Deck() = slide::Parse(app.CurrentText()); std::ofstream file(app.CurrentFile()); file << app.CurrentText(); app.RenderCurrentSlide(); } void SetCursorCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Setting Cursor" << std::endl; auto cursor = json.at("cursor").get<int>(); app.CurrentSlide() = -1; for (int i = 0; app.CurrentSlide() == -1 && i < app.Deck().size(); i++) { for (auto token : app.Deck()[i]) { if (token.position() >= cursor) { app.CurrentSlide() = i; break; } } } app.RenderCurrentSlide(); } } // namespace slide
32.877005
80
0.621828
PaoJiao
c128913a7f57128044d9526daee53d864ed3b411
183
cpp
C++
src/core/i_heat_source_component.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
3
2015-02-22T20:34:28.000Z
2020-03-04T08:55:25.000Z
src/core/i_heat_source_component.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
22
2015-12-13T16:29:40.000Z
2017-03-04T15:45:44.000Z
src/core/i_heat_source_component.cpp
Reaping2/Reaping2
0d4c988c99413e50cc474f6206cf64176eeec95d
[ "MIT" ]
14
2015-11-23T21:25:09.000Z
2020-07-17T17:03:23.000Z
#include "i_heat_source_component.h" #include <portable_iarchive.hpp> #include <portable_oarchive.hpp> REAPING2_CLASS_EXPORT_IMPLEMENT( IHeatSourceComponent, IHeatSourceComponent );
30.5
78
0.852459
MrPepperoni
c1299f21b1f8a218c5a8dd42e4ce9fd050e391cc
737
cpp
C++
Unidad-3/Aula25/AViciusPikemanEasy.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
Unidad-3/Aula25/AViciusPikemanEasy.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
Unidad-3/Aula25/AViciusPikemanEasy.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // https://open.kattis.com/problems/pikemaneasy typedef long long int ll; ll ARRA[10000]; int COMPARATION(const void *p, const void *q) { int *a = (int *) p; int *b = (int *) q; return *a - *b; } int main(int argc, char const *argv[]) { ll x, y, z, m, n, o = 0 ,p = 0, l = 0, i; cin >> x >> y >> z >> m >> n >> ARRA[0]; for (i = 1; i < x; ++i){ ARRA[i] = (z * ARRA[i-1] + m) % n + 1; } qsort(ARRA, x, sizeof(ll), COMPARATION); for (i = 0; i < x; ++i){ if (l + ARRA[i] <= y){ o = (o + ARRA[i] + l) % 1000000007; l += ARRA[i]; p++; } else break; } cout << p << " " << o << '\n'; return 0; }
21.676471
47
0.447761
luismoroco
c12a5cddd924ce38ee929ca606ed7cac3786cb88
313
hpp
C++
src/copy_and_move/src/Foo.hpp
VincentPopie/Sandbox
882c5bf7325af595739fd9004ba1774ceeee272f
[ "MIT" ]
null
null
null
src/copy_and_move/src/Foo.hpp
VincentPopie/Sandbox
882c5bf7325af595739fd9004ba1774ceeee272f
[ "MIT" ]
null
null
null
src/copy_and_move/src/Foo.hpp
VincentPopie/Sandbox
882c5bf7325af595739fd9004ba1774ceeee272f
[ "MIT" ]
null
null
null
#pragma once #include<string> /* * Class Foo contains a _name attribute. */ class Foo{ public: /* * Foo constructor, set the _name. */ Foo(const std::string& iName): _name(iName){} /* * Retrieve Foo name. */ std::string getName() const { return _name;} private: std::string _name; };
13.041667
47
0.616613
VincentPopie
c12fac520b506da953ffbe92b0e4f58dfac8cf71
3,920
cxx
C++
Applications/AdaptiveParaView/pqCustomDisplayPolicy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
Applications/AdaptiveParaView/pqCustomDisplayPolicy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
Applications/AdaptiveParaView/pqCustomDisplayPolicy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
#include "pqCustomDisplayPolicy.h" #include <pqPipelineSource.h> #include <vtkSMSourceProxy.h> #include <pqOutputPort.h> #include <vtkPVDataInformation.h> #include <QString> #include <vtkStructuredData.h> #include <pqTwoDRenderView.h> #include <pqApplicationCore.h> #include <pqDataRepresentation.h> #include <pqObjectBuilder.h> #include <QDebug> pqCustomDisplayPolicy::pqCustomDisplayPolicy(QObject *o) : pqDisplayPolicy(o) { } pqCustomDisplayPolicy::~pqCustomDisplayPolicy() { } //----------------------------------------------------------------------------- QString pqCustomDisplayPolicy::getPreferredViewType(pqOutputPort* opPort, bool update_pipeline) const { pqPipelineSource* source = opPort->getSource(); if (update_pipeline) { source->updatePipeline(); } QString view_type = QString::null; // HACK: for now, when update_pipeline is false, we don't do any gather // information as that can result in progress events which may case Qt paint // issues. vtkSMSourceProxy* spProxy = vtkSMSourceProxy::SafeDownCast( source->getProxy()); if (!spProxy || (!update_pipeline && !spProxy->GetOutputPortsCreated())) { // If parts aren't created, don't update the information at all. // Typically means that the filter hasn't been "Applied" even once and // updating information on it may raise errors. return view_type; } vtkPVDataInformation* datainfo = update_pipeline? opPort->getDataInformation(true) : opPort->getCachedDataInformation(); QString className = datainfo? datainfo->GetDataClassName() : QString(); // * Check if we should create the 2D view. if ((className == "vtkImageData" || className == "vtkUniformGrid") && datainfo->GetCompositeDataClassName()==0) { int extent[6]; datainfo->GetExtent(extent); int temp[6]={0, 0, 0, 0, 0, 0}; int dimensionality = vtkStructuredData::GetDataDimension( vtkStructuredData::SetExtent(extent, temp)); if (dimensionality == 2) { return pqTwoDRenderView::twoDRenderViewType(); } } return view_type; } //----------------------------------------------------------------------------- pqDataRepresentation* pqCustomDisplayPolicy::setRepresentationVisibility( pqOutputPort* opPort, pqView* view, bool visible) { if (!opPort) { // Cannot really repr a NULL source. return 0; } pqDataRepresentation* repr = opPort->getRepresentation(view); if (!repr && !visible) { // isn't visible already, nothing to change. return 0; } else if(!repr) { // FIXME:UDA -- can't we simply use createPreferredRepresentation? // No repr exists for this view. // First check if the view exists. If not, we will create a "suitable" view. if (!view) { view = this->getPreferredView(opPort, view); } if (view) { repr = pqApplicationCore::instance()->getObjectBuilder()-> createDataRepresentation(opPort, view); } } if (!repr) { qDebug() << "Cannot show the data in the current view although" "the view reported that it can show the data."; return 0; } repr->setVisible(visible); // If this is the only source displayed in the view, reset the camera to make // sure its visible. Only do so if a source is being turned ON. Otherwise when // the next to last source is turned off, the camera would be reset to fit the // last remaining one which would be unexpected to the user // (hence the conditional on "visible") // // The static pointer makes it not reset the viewpoint when we hide and // show the same thing. static pqView *lview = NULL; if(view->getNumberOfVisibleRepresentations()==1 && visible) { pqRenderViewBase* ren = qobject_cast<pqRenderViewBase*>(view); if (ren && lview != view) { ren->resetCamera(); lview = view; } } return repr; }
29.69697
81
0.653571
matthb2
c132f471cf543582185d7b30aaaa4942c150155c
1,606
hpp
C++
TopGraph/extendedpersistence/utils/mo_algorithm.hpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
55
2018-01-11T02:20:02.000Z
2022-03-24T06:18:54.000Z
TopGraph/extendedpersistence/utils/mo_algorithm.hpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
10
2016-10-29T08:20:04.000Z
2021-02-27T13:14:53.000Z
TopGraph/extendedpersistence/utils/mo_algorithm.hpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
11
2016-10-29T06:00:53.000Z
2021-06-16T14:32:43.000Z
#pragma once #include <algorithm> #include <cmath> #include <numeric> #include <tuple> #include <utility> #include <vector> // struct mo_struct { // typedef int64_t value_type; // typedef int64_t result_type; // void add_right(int nr, value_type x_r) { // } // void add_left(int nl, value_type x_nl) { // } // void remove_right(int nr, value_type x_nr) { // } // void remove_left(int nl, value_type x_l) { // } // result_type query() { // return 0; // } // }; template <class Mo> std::vector<typename Mo::result_type> run_mo_algorithm(Mo mo, const std::vector<typename Mo::value_type>& values, const std::vector<std::pair<int, int> >& queries) { int n = values.size(); int m = queries.size(); // sort queries int sq_n = std::sqrt(n); std::vector<int> order(m); std::iota(ALL(order), 0); std::sort(ALL(order), [&](int i, int j) { int l_i, r_i; std::tie(l_i, r_i) = queries[i]; int l_j, r_j; std::tie(l_j, r_j) = queries[j]; return std::make_pair(l_i / sq_n, r_i) < std::make_pair(l_j / sq_n, r_j); }); // compute queries std::vector<typename Mo::result_type> ans(m); int l = 0; int r = 0; for (int j : order) { int nl, nr; std::tie(nl, nr) = queries[j]; for (; r < nr; ++ r) mo.add_right(r + 1, values[r]); for (; nl < l; -- l) mo.add_left(l - 1, values[l - 1]); for (; nr < r; -- r) mo.remove_right(r - 1, values[r - 1]); for (; l < nl; ++ l) mo.remove_left(l + 1, values[l]); ans[j] = mo.query(); } return ans; }
29.740741
165
0.557908
mityanony404
c13f5206521d4c221977c6376b97b0baff56db4a
27,449
cc
C++
engine/source/2d/assets/ParticleAssetEmitter.cc
close-code/Torque2D
ad141fc7b5f28b75f727ef29dcc93aafbb3f5aa3
[ "MIT" ]
1,309
2015-01-01T02:46:14.000Z
2022-03-14T04:56:02.000Z
engine/source/2d/assets/ParticleAssetEmitter.cc
SwaroopGuvvala/Torque2D
55efccc7c7a4331547f5d71c733a75b8de1189e8
[ "MIT" ]
155
2015-01-11T19:26:32.000Z
2021-11-22T04:08:55.000Z
engine/source/2d/assets/ParticleAssetEmitter.cc
SwaroopGuvvala/Torque2D
55efccc7c7a4331547f5d71c733a75b8de1189e8
[ "MIT" ]
1,595
2015-01-01T23:19:48.000Z
2022-02-17T07:00:52.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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 "2d/assets/ParticleAssetEmitter.h" #ifndef _PARTICLE_ASSET_H_ #include "2d/assets/ParticleAsset.h" #endif #ifndef _CONSOLETYPES_H_ #include "console/consoleTypes.h" #endif // Script bindings. #include "ParticleAssetEmitter_ScriptBinding.h" //------------------------------------------------------------------------------ static EnumTable::Enums emitterTypeLookup[] = { { ParticleAssetEmitter::POINT_EMITTER, "POINT" }, { ParticleAssetEmitter::LINE_EMITTER, "LINE" }, { ParticleAssetEmitter::BOX_EMITTER, "BOX" }, { ParticleAssetEmitter::DISK_EMITTER, "DISK" }, { ParticleAssetEmitter::ELLIPSE_EMITTER, "ELLIPSE" }, { ParticleAssetEmitter::TORUS_EMITTER, "TORUS" }, }; //------------------------------------------------------------------------------ static EnumTable EmitterTypeTable(sizeof(emitterTypeLookup) / sizeof(EnumTable::Enums), &emitterTypeLookup[0]); //------------------------------------------------------------------------------ ParticleAssetEmitter::EmitterType ParticleAssetEmitter::getEmitterTypeEnum(const char* label) { // Search for Mnemonic. for(U32 i = 0; i < (sizeof(emitterTypeLookup) / sizeof(EnumTable::Enums)); i++) if( dStricmp(emitterTypeLookup[i].label, label) == 0) return((ParticleAssetEmitter::EmitterType)emitterTypeLookup[i].index); // Warn. Con::warnf( "ParticleAssetEmitter::getEmitterTypeEnum() - Invalid emitter-type '%s'.", label ); return ParticleAssetEmitter::INVALID_EMITTER_TYPE; } //----------------------------------------------------------------------------- const char* ParticleAssetEmitter::getEmitterTypeDescription( const EmitterType emitterType ) { // Search for Mnemonic. for (U32 i = 0; i < (sizeof(emitterTypeLookup) / sizeof(EnumTable::Enums)); i++) { if( emitterTypeLookup[i].index == (S32)emitterType ) return emitterTypeLookup[i].label; } // Warn. Con::warnf( "ParticleAssetEmitter::getEmitterTypeDescription() - Invalid emitter-type." ); return StringTable->EmptyString; } //------------------------------------------------------------------------------ static EnumTable::Enums particleOrientationTypeLookup[] = { { ParticleAssetEmitter::FIXED_ORIENTATION, "FIXED" }, { ParticleAssetEmitter::ALIGNED_ORIENTATION, "ALIGNED" }, { ParticleAssetEmitter::RANDOM_ORIENTATION, "RANDOM" }, }; //------------------------------------------------------------------------------ static EnumTable OrientationTypeTable(sizeof(particleOrientationTypeLookup) / sizeof(EnumTable::Enums), &particleOrientationTypeLookup[0]); //------------------------------------------------------------------------------ ParticleAssetEmitter::ParticleOrientationType ParticleAssetEmitter::getOrientationTypeEnum(const char* label) { // Search for Mnemonic. for(U32 i = 0; i < (sizeof(particleOrientationTypeLookup) / sizeof(EnumTable::Enums)); i++) if( dStricmp(particleOrientationTypeLookup[i].label, label) == 0) return((ParticleAssetEmitter::ParticleOrientationType)particleOrientationTypeLookup[i].index); // Warn. Con::warnf( "ParticleAssetEmitter::getOrientationTypeEnum() - Invalid orientation type '%s'.", label ); return ParticleAssetEmitter::INVALID_ORIENTATION; } //------------------------------------------------------------------------------ const char* ParticleAssetEmitter::getOrientationTypeDescription( const ParticleOrientationType orientationType ) { // Search for Mnemonic. for (U32 i = 0; i < (sizeof(particleOrientationTypeLookup) / sizeof(EnumTable::Enums)); i++) { if( particleOrientationTypeLookup[i].index == (S32)orientationType ) return particleOrientationTypeLookup[i].label; } // Warn. Con::warnf( "ParticleAssetEmitter::getOrientationTypeDescription() - Invalid orientation-type" ); return StringTable->EmptyString; } //------------------------------------------------------------------------------ ParticleAssetEmitter::ParticleAssetEmitter() : mEmitterName( StringTable->EmptyString ), mOwner( NULL ), mEmitterType( POINT_EMITTER ), mEmitterOffset( 0.0f, 0.0f), mEmitterAngle( 0.0f ), mEmitterSize( 10.0f, 10.0f ), mFixedAspect( true ), mOrientationType( FIXED_ORIENTATION ), mKeepAligned( false ), mAlignedAngleOffset( 0.0f ), mRandomAngleOffset( 0.0f ), mRandomArc( 360.0f ), mFixedAngleOffset( 0.0f ), mLinkEmissionRotation( true ), mIntenseParticles( false ), mSingleParticle( false ), mAttachPositionToEmitter( false ), mAttachRotationToEmitter( false ), mOldestInFront( false ), mStaticMode( true ), mImageAsset( NULL ), mImageFrame( 0 ), mRandomImageFrame( false ), mAnimationAsset( NULL ), mBlendMode( true ), mSrcBlendFactor( GL_SRC_ALPHA ), mDstBlendFactor( GL_ONE_MINUS_SRC_ALPHA ), mAlphaTest( -1.0f ) { // Set the pivot point. // NOTE: This is called to set the local AABB. setPivotPoint( Vector2::getZero() ); // Set fixed force angle. // NOTE: This is called to set the fixed-force-direction. setFixedForceAngle( 0.0f ); // Initialize particle fields. mParticleFields.addField( mParticleLife.getBase(), "Lifetime", 1000.0f, 0.0f, 10000.0f, 2.0f ); mParticleFields.addField( mParticleLife.getVariation(), "LifetimeVariation", 1000.0f, 0.0f, 5000.0f, 0.0f ); mParticleFields.addField( mQuantity.getBase(), "Quantity", 1000.0f, 0.0f, 100000.0f, 10.0f ); mParticleFields.addField( mQuantity.getVariation(), "QuantityVariation", 1000.0f, 0.0f, 100000.0f, 0.0f ); mParticleFields.addField( mSizeX.getBase(), "SizeX", 1000.0f, 0.0f, 100.0f, 2.0f ); mParticleFields.addField( mSizeX.getVariation(), "SizeXVariation", 1000.0f, 0.0f, 200.0f, 0.0f ); mParticleFields.addField( mSizeX.getLife(), "SizeXLife", 1.0f, -100.0f, 100.0f, 1.0f ); mParticleFields.addField( mSizeY.getBase(), "SizeY", 1000.0f, 0.0f, 100.0f, 2.0f ); mParticleFields.addField( mSizeY.getVariation(), "SizeYVariation", 1000.0f, 0.0f, 200.0f, 0.0f ); mParticleFields.addField( mSizeY.getLife(), "SizeYLife", 1.0f, -100.0f, 100.0f, 1.0f ); mParticleFields.addField( mSpeed.getBase(), "Speed", 1000.0f, 0.0f, 100.0f, 10.0f ); mParticleFields.addField( mSpeed.getVariation(), "SpeedVariation", 1000.0f, 0.0f, 200.0f, 0.0f ); mParticleFields.addField( mSpeed.getLife(), "SpeedLife", 1.0f, -100.0f, 100.0f, 1.0f ); mParticleFields.addField( mSpin.getBase(), "Spin", 1000.0f, -1000.0f, 1000.0f, 0.0f ); mParticleFields.addField( mSpin.getVariation(), "SpinVariation", 1000.0f, 0.0f, 2000.0f, 0.0f ); mParticleFields.addField( mSpin.getLife(), "SpinLife", 1.0f, -1000.0f, 1000.0f, 1.0f ); mParticleFields.addField( mFixedForce.getBase(), "FixedForce", 1000.0f, -1000.0f, 1000.0f, 0.0f ); mParticleFields.addField( mFixedForce.getVariation(), "FixedForceVariation", 1000.0f, 0.0f, 2000.0f, 0.0f ); mParticleFields.addField( mFixedForce.getLife(), "FixedForceLife", 1.0f, -1000.0f, 1000.0f, 1.0f ); mParticleFields.addField( mRandomMotion.getBase(), "RandomMotion", 1000.0f, 0.0f, 1000.0f, 0.0f ); mParticleFields.addField( mRandomMotion.getVariation(), "RandomMotionVariation", 1000.0f, 0.0f, 2000.0f, 0.0f ); mParticleFields.addField( mRandomMotion.getLife(), "RandomMotionLife", 1.0f, -100.0f, 100.0f, 1.0f ); mParticleFields.addField( mEmissionForce.getBase(), "EmissionForce", 1000.0f, -100.0f, 1000.0f, 5.0f ); mParticleFields.addField( mEmissionForce.getVariation(), "EmissionForceVariation", 1000.0f, -500.0f, 500.0f, 5.0f ); mParticleFields.addField( mEmissionAngle.getBase(), "EmissionAngle", 1000.0f, -180.0f, 180.0f, 0.0f ); mParticleFields.addField( mEmissionAngle.getVariation(), "EmissionAngleVariation", 1000.0f, 0.0f, 360.0f, 0.0f ); mParticleFields.addField( mEmissionArc.getBase(), "EmissionArc", 1000.0f, 0.0f, 360.0f, 360.0f ); mParticleFields.addField( mEmissionArc.getVariation(), "EmissionArcVariation", 1000.0f, 0.0f, 720.0f, 0.0f ); mParticleFields.addField( mRedChannel.getLife(), "RedChannel", 1.0f, 0.0f, 1.0f, 1.0f ); mParticleFields.addField( mGreenChannel.getLife(), "GreenChannel", 1.0f, 0.0f, 1.0f, 1.0f ); mParticleFields.addField( mBlueChannel.getLife(), "BlueChannel", 1.0f, 0.0f, 1.0f, 1.0f ); mParticleFields.addField( mAlphaChannel.getLife(), "AlphaChannel", 1.0f, 0.0f, 1.0f, 1.0f ); // Register for refresh notifications. mImageAsset.registerRefreshNotify( this ); mAnimationAsset.registerRefreshNotify( this ); mNamedImageFrame = ""; mUsingNamedFrame = false; } //------------------------------------------------------------------------------ ParticleAssetEmitter::~ParticleAssetEmitter() { } //------------------------------------------------------------------------------ void ParticleAssetEmitter::initPersistFields() { // Call parent. Parent::initPersistFields(); addProtectedField("EmitterName", TypeString, Offset(mEmitterName, ParticleAssetEmitter), &setEmitterName, &defaultProtectedGetFn, &defaultProtectedWriteFn, ""); addProtectedField("EmitterType", TypeEnum, Offset(mEmitterType, ParticleAssetEmitter), &setEmitterType, &defaultProtectedGetFn, &writeEmitterType, 1, &EmitterTypeTable); addProtectedField("EmitterOffset", TypeVector2, Offset(mEmitterOffset, ParticleAssetEmitter), &setEmitterOffset, &defaultProtectedGetFn, &writeEmitterOffset, ""); addProtectedField("EmitterAngle", TypeF32, Offset(mEmitterAngle, ParticleAssetEmitter), &setEmitterAngle, &defaultProtectedGetFn, &writeEmitterAngle, ""); addProtectedField("EmitterSize", TypeVector2, Offset(mEmitterSize, ParticleAssetEmitter), &setEmitterSize, &defaultProtectedGetFn, &writeEmitterSize, ""); addProtectedField("FixedAspect", TypeBool, Offset(mFixedAspect, ParticleAssetEmitter), &setFixedAspect, &defaultProtectedGetFn, &writeFixedAspect, ""); addProtectedField("FixedForceAngle", TypeF32, Offset(mFixedForceAngle, ParticleAssetEmitter), &setFixedForceAngle, &defaultProtectedGetFn, &writeFixedForceAngle, ""); addProtectedField("OrientationType", TypeEnum, Offset(mOrientationType, ParticleAssetEmitter), &setOrientationType, &defaultProtectedGetFn, &writeOrientationType, 1, &OrientationTypeTable); addProtectedField("KeepAligned", TypeBool, Offset(mKeepAligned, ParticleAssetEmitter), &setKeepAligned, &defaultProtectedGetFn, &writeKeepAligned, ""); addProtectedField("AlignedAngleOffset", TypeF32, Offset(mAlignedAngleOffset, ParticleAssetEmitter), &setAlignedAngleOffset, &defaultProtectedGetFn, &writeAlignedAngleOffset, ""); addProtectedField("RandomAngleOffset", TypeF32, Offset(mRandomAngleOffset, ParticleAssetEmitter), &setRandomAngleOffset, &defaultProtectedGetFn, &writeRandomAngleOffset, ""); addProtectedField("RandomArc", TypeF32, Offset(mRandomArc, ParticleAssetEmitter), &setRandomArc, &defaultProtectedGetFn, &writeRandomArc, ""); addProtectedField("FixedAngleOffset", TypeF32, Offset(mFixedAngleOffset, ParticleAssetEmitter), &setFixedAngleOffset, &defaultProtectedGetFn, &writeFixedAngleOffset, ""); addProtectedField("PivotPoint", TypeVector2, Offset(mPivotPoint, ParticleAssetEmitter), &setPivotPoint, &defaultProtectedGetFn, &writePivotPoint, ""); addProtectedField("LinkEmissionRotation", TypeBool, Offset(mLinkEmissionRotation, ParticleAssetEmitter), &setLinkEmissionRotation, &defaultProtectedGetFn, &writeLinkEmissionRotation, ""); addProtectedField("IntenseParticles", TypeBool, Offset(mIntenseParticles, ParticleAssetEmitter), &setIntenseParticles, &defaultProtectedGetFn, &writeIntenseParticles, ""); addProtectedField("SingleParticle", TypeBool, Offset(mSingleParticle, ParticleAssetEmitter), &setSingleParticle, &defaultProtectedGetFn, &writeSingleParticle, ""); addProtectedField("AttachPositionToEmitter", TypeBool, Offset(mAttachPositionToEmitter, ParticleAssetEmitter), &setAttachPositionToEmitter, &defaultProtectedGetFn, &writeAttachPositionToEmitter, ""); addProtectedField("AttachRotationToEmitter", TypeBool, Offset(mAttachRotationToEmitter, ParticleAssetEmitter), &setAttachRotationToEmitter, &defaultProtectedGetFn, &writeAttachRotationToEmitter, ""); addProtectedField("OldestInFront", TypeBool, Offset(mOldestInFront, ParticleAssetEmitter), &setOldestInFront, &defaultProtectedGetFn, &writeOldestInFront, ""); addProtectedField("BlendMode", TypeBool, Offset(mBlendMode, ParticleAssetEmitter), &setBlendMode, &defaultProtectedGetFn, &writeBlendMode, ""); addProtectedField("SrcBlendFactor", TypeEnum, Offset(mSrcBlendFactor, ParticleAssetEmitter), &setSrcBlendFactor, &defaultProtectedGetFn, &writeSrcBlendFactor, 1, &srcBlendFactorTable, ""); addProtectedField("DstBlendFactor", TypeEnum, Offset(mDstBlendFactor, ParticleAssetEmitter), &setDstBlendFactor, &defaultProtectedGetFn, &writeDstBlendFactor, 1, &dstBlendFactorTable, ""); addProtectedField("AlphaTest", TypeF32, Offset(mAlphaTest, ParticleAssetEmitter), &setAlphaTest, &defaultProtectedGetFn, &writeAlphaTest, ""); addProtectedField("Image", TypeImageAssetPtr, Offset(mImageAsset, ParticleAssetEmitter), &setImage, &getImage, &writeImage, ""); addProtectedField("Frame", TypeS32, Offset(mImageFrame, ParticleAssetEmitter), &setImageFrame, &defaultProtectedGetFn, &writeImageFrame, ""); addProtectedField("NamedFrame", TypeString, Offset(mNamedImageFrame, ParticleAssetEmitter), &setNamedImageFrame, &defaultProtectedGetFn, &writeNamedImageFrame, ""); addProtectedField("RandomImageFrame", TypeBool, Offset(mRandomImageFrame, ParticleAssetEmitter), &setRandomImageFrame, &defaultProtectedGetFn, &writeRandomImageFrame, ""); addProtectedField("Animation", TypeAnimationAssetPtr, Offset(mAnimationAsset, ParticleAssetEmitter), &setAnimation, &getAnimation, &writeAnimation, ""); } //------------------------------------------------------------------------------ void ParticleAssetEmitter::copyTo(SimObject* object) { // Fetch particle asset emitter object. ParticleAssetEmitter* pParticleAssetEmitter = static_cast<ParticleAssetEmitter*>( object ); // Sanity! AssertFatal( pParticleAssetEmitter != NULL, "ParticleAssetEmitter::copyTo() - Object is not the correct type."); // Copy parent. Parent::copyTo( object ); // Copy fields. pParticleAssetEmitter->setEmitterName( getEmitterName() ); pParticleAssetEmitter->setEmitterType( getEmitterType() ); pParticleAssetEmitter->setEmitterOffset( getEmitterOffset() ); pParticleAssetEmitter->setEmitterSize( getEmitterSize() ); pParticleAssetEmitter->setEmitterAngle( getEmitterAngle() ); pParticleAssetEmitter->setFixedAspect( getFixedAspect() ); pParticleAssetEmitter->setFixedForceAngle( getFixedForceAngle() ); pParticleAssetEmitter->setOrientationType( getOrientationType() ); pParticleAssetEmitter->setKeepAligned( getKeepAligned() ); pParticleAssetEmitter->setAlignedAngleOffset( getAlignedAngleOffset() ); pParticleAssetEmitter->setRandomAngleOffset( getRandomAngleOffset() ); pParticleAssetEmitter->setRandomArc( getRandomArc() ); pParticleAssetEmitter->setFixedAngleOffset( getFixedAngleOffset() ); pParticleAssetEmitter->setPivotPoint( getPivotPoint() ); pParticleAssetEmitter->setLinkEmissionRotation( getLinkEmissionRotation() ); pParticleAssetEmitter->setIntenseParticles( getIntenseParticles() ); pParticleAssetEmitter->setSingleParticle( getSingleParticle() ); pParticleAssetEmitter->setAttachPositionToEmitter( getAttachPositionToEmitter() ); pParticleAssetEmitter->setAttachRotationToEmitter( getAttachRotationToEmitter() ); pParticleAssetEmitter->setOldestInFront( getOldestInFront() ); pParticleAssetEmitter->setBlendMode( getBlendMode() ); pParticleAssetEmitter->setSrcBlendFactor( getSrcBlendFactor() ); pParticleAssetEmitter->setDstBlendFactor( getDstBlendFactor() ); pParticleAssetEmitter->setAlphaTest( getAlphaTest() ); pParticleAssetEmitter->setRandomImageFrame( getRandomImageFrame() ); // Static provider? if ( pParticleAssetEmitter->isStaticFrameProvider() ) { // Named image frame? if ( pParticleAssetEmitter->isUsingNamedImageFrame() ) pParticleAssetEmitter->setImage( getImage(), getNamedImageFrame() ); else pParticleAssetEmitter->setImage( getImage(), getImageFrame() ); } else { pParticleAssetEmitter->setAnimation( getAnimation() ); } // Copy particle fields. mParticleFields.copyTo( pParticleAssetEmitter->mParticleFields ); } //----------------------------------------------------------------------------- void ParticleAssetEmitter::setEmitterName( const char* pEmitterName ) { // Sanity! AssertFatal( mEmitterName != NULL, "ParticleAssetEmitter::setEmitterName() - Cannot set a NULL particle asset emitter name." ); // Set the emitter name. mEmitterName = StringTable->insert( pEmitterName ); // Refresh the asset. refreshAsset(); } //----------------------------------------------------------------------------- void ParticleAssetEmitter::setOwner( ParticleAsset* pParticleAsset ) { // Sanity! AssertFatal( mOwner == NULL, "ParticleAssetEmitter::setOwner() - Cannot set an owner when one is already assigned." ); // Set owner. mOwner = pParticleAsset; } //------------------------------------------------------------------------------ void ParticleAssetEmitter::setPivotPoint( const Vector2& pivotPoint ) { // Set the pivot point. mPivotPoint = pivotPoint; // Calculate the local pivot AABB. mLocalPivotAABB[0].Set( -0.5f + mPivotPoint.x, -0.5f + mPivotPoint.y ); mLocalPivotAABB[1].Set( 0.5f + mPivotPoint.x, -0.5f + mPivotPoint.y ); mLocalPivotAABB[2].Set( 0.5f + mPivotPoint.x, 0.5f + mPivotPoint.y ); mLocalPivotAABB[3].Set( -0.5f + mPivotPoint.x, 0.5f + mPivotPoint.y ); // Refresh the asset. refreshAsset(); } //------------------------------------------------------------------------------ void ParticleAssetEmitter::setFixedForceAngle( F32 fixedForceAngle ) { // Set Fixed-Force Angle. mFixedForceAngle = fixedForceAngle; // Calculate the angle in radians. const F32 fixedForceAngleRadians = mDegToRad(mFixedForceAngle); // Set Fixed-Force Direction. mFixedForceDirection.Set( mCos(fixedForceAngleRadians), mSin(fixedForceAngleRadians) ); // Refresh the asset. refreshAsset(); } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setImage( const char* pAssetId, U32 frame ) { // Sanity! AssertFatal( pAssetId != NULL, "ParticleAssetEmitter::setImage() - Cannot use a NULL asset Id." ); // Set static mode. mStaticMode = true; // Clear animation asset. mAnimationAsset.clear(); // Set asset Id. mImageAsset = pAssetId; // Is there an asset? if ( mImageAsset.notNull() ) { // Yes, so is the frame valid? if ( frame >= mImageAsset->getFrameCount() ) { // No, so warn. Con::warnf( "ParticleAssetEmitter::setImage() - Invalid frame '%d' for ImageAsset '%s'.", frame, mImageAsset.getAssetId() ); } else { // Yes, so set the frame. mImageFrame = frame; } } else { // No, so reset the image frame. mImageFrame = 0; } // Using a numerical frame index mUsingNamedFrame = false; // Refresh the asset. refreshAsset(); // Return Okay. return true; } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setImage( const char* pAssetId, const char* frameName ) { // Sanity! AssertFatal( pAssetId != NULL, "ParticleAssetEmitter::setImage() - Cannot use a NULL asset Id." ); // Set static mode. mStaticMode = true; // Clear animation asset. mAnimationAsset.clear(); // Set asset Id. mImageAsset = pAssetId; // Is there an asset? if ( mImageAsset.notNull() ) { // Yes, so is the frame valid? if ( !mImageAsset->containsFrame(frameName) ) { // No, so warn. Con::warnf( "ParticleAssetEmitter::setImage() - Invalid frame '%s' for ImageAsset '%s'.", frameName, mImageAsset.getAssetId() ); } else { // Yes, so set the frame. mNamedImageFrame = StringTable->insert(frameName); } } else { // No, so reset the image frame. mNamedImageFrame = StringTable->insert(StringTable->EmptyString); } // Using a named frame index mUsingNamedFrame = true; // Refresh the asset. refreshAsset(); // Return Okay. return true; } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setImageFrame( const U32 frame ) { // Check Existing Image. if ( mImageAsset.isNull() ) { // Warn. Con::warnf("ParticleAssetEmitter::setImageFrame() - Cannot set Frame without existing asset Id."); // Return Here. return false; } // Check Frame Validity. if ( frame >= mImageAsset->getFrameCount() ) { // Warn. Con::warnf( "ParticleAssetEmitter::setImageFrame() - Invalid Frame #%d for asset Id '%s'.", frame, mImageAsset.getAssetId() ); // Return Here. return false; } // Set Frame. mImageFrame = frame; // Using a numerical frame index. mUsingNamedFrame = false; // Refresh the asset. refreshAsset(); // Return Okay. return true; } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setNamedImageFrame( const char* frameName ) { // Check Existing Image. if ( mImageAsset.isNull() ) { // Warn. Con::warnf("ParticleAssetEmitter::setNamedImageFrame() - Cannot set Frame without existing asset Id."); // Return Here. return false; } // Check Frame Validity. if ( !mImageAsset->containsFrame(frameName) ) { // Warn. Con::warnf( "ParticleAssetEmitter::setNamedImageFrame() - Invalid Frame %s for asset Id '%s'.", frameName, mImageAsset.getAssetId() ); // Return Here. return false; } // Set frame. mNamedImageFrame = StringTable->insert(frameName); // Using a named frame index mUsingNamedFrame = true; // Refresh the asset. refreshAsset(); // Return Okay. return true; } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setAnimation( const char* pAnimationAssetId ) { // Sanity! AssertFatal( pAnimationAssetId != NULL, "ParticleAssetEmitter::setAnimation() - Cannot use NULL asset Id." ); // Set animated mode. mStaticMode = false; // Clear static asset. mImageAsset.clear(); // Set animation asset. mAnimationAsset = pAnimationAssetId; // Refresh the asset. refreshAsset(); return true; } //------------------------------------------------------------------------------ void ParticleAssetEmitter::refreshAsset( void ) { // Finish if no owner. if ( mOwner == NULL ) return; // Refresh the asset. mOwner->refreshAsset(); } //------------------------------------------------------------------------------ void ParticleAssetEmitter::onAssetRefreshed( AssetPtrBase* pAssetPtrBase ) { // Either the image or animation asset has been refreshed to just refresh the // asset that this emitter may belong to. ParticleAssetEmitter::refreshAsset(); } //------------------------------------------------------------------------------ void ParticleAssetEmitter::onTamlCustomWrite( TamlCustomNodes& customNodes ) { // Debug Profiling. PROFILE_SCOPE(ParticleAssetEmitter_OnTamlCustomWrite); // Write the fields. mParticleFields.onTamlCustomWrite( customNodes ); } //----------------------------------------------------------------------------- void ParticleAssetEmitter::onTamlCustomRead( const TamlCustomNodes& customNodes ) { // Debug Profiling. PROFILE_SCOPE(ParticleAssetEmitter_OnTamlCustomRead); // Read the fields. mParticleFields.onTamlCustomRead( customNodes ); } //----------------------------------------------------------------------------- static void WriteCustomTamlSchema( const AbstractClassRep* pClassRep, TiXmlElement* pParentElement ) { // Sanity! AssertFatal( pClassRep != NULL, "ParticleAssetEmitter::WriteCustomTamlSchema() - ClassRep cannot be NULL." ); AssertFatal( pParentElement != NULL, "ParticleAssetEmitter::WriteCustomTamlSchema() - Parent Element cannot be NULL." ); // Write the particle asset emitter fields. ParticleAssetEmitter particleAssetEmitter; particleAssetEmitter.getParticleFields().WriteCustomTamlSchema( pClassRep, pParentElement ); } //----------------------------------------------------------------------------- IMPLEMENT_CONOBJECT_SCHEMA(ParticleAssetEmitter, WriteCustomTamlSchema);
43.988782
203
0.633611
close-code
c144552f3079ed40d3570ff9f7e2090fedade582
606
hpp
C++
android-28/android/util/TimeUtils.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/util/TimeUtils.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-28/android/util/TimeUtils.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" class JString; namespace java::util { class TimeZone; } namespace android::util { class TimeUtils : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit TimeUtils(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} TimeUtils(QJniObject obj); // Constructors // Methods static java::util::TimeZone getTimeZone(jint arg0, jboolean arg1, jlong arg2, JString arg3); static JString getTimeZoneDatabaseVersion(); }; } // namespace android::util
20.2
150
0.69637
YJBeetle
c1448d8b832318d1fc649c638df8ce0147489690
62,276
cc
C++
protocal/control/control_conf.pb.cc
racestart/g2r
d115ebaab13829d716750eab2ebdcc51d79ff32e
[ "Apache-2.0" ]
1
2020-03-05T12:49:21.000Z
2020-03-05T12:49:21.000Z
protocal/control/control_conf.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
null
null
null
protocal/control/control_conf.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
1
2020-03-25T15:06:39.000Z
2020-03-25T15:06:39.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: control/control_conf.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "control/control_conf.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace apollo { namespace control { namespace { const ::google::protobuf::Descriptor* ControlConf_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ControlConf_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* ControlConf_ControllerType_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_control_2fcontrol_5fconf_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AssignDesc_control_2fcontrol_5fconf_2eproto() { protobuf_AddDesc_control_2fcontrol_5fconf_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "control/control_conf.proto"); GOOGLE_CHECK(file != NULL); ControlConf_descriptor_ = file->message_type(0); static const int ControlConf_offsets_[18] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, control_period_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, max_planning_interval_sec_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, max_planning_delay_threshold_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, driving_mode_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, action_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, soft_estop_brake_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, active_controllers_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, max_steering_percentage_allowed_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, max_status_interval_sec_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, lat_controller_conf_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, lon_controller_conf_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, trajectory_period_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, chassis_period_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, localization_period_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, minimum_speed_resolution_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, mpc_controller_conf_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, query_relative_time_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, minimum_speed_protection_), }; ControlConf_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( ControlConf_descriptor_, ControlConf::default_instance_, ControlConf_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, _has_bits_[0]), -1, -1, sizeof(ControlConf), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, _internal_metadata_), -1); ControlConf_ControllerType_descriptor_ = ControlConf_descriptor_->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_control_2fcontrol_5fconf_2eproto); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ControlConf_descriptor_, &ControlConf::default_instance()); } } // namespace void protobuf_ShutdownFile_control_2fcontrol_5fconf_2eproto() { delete ControlConf::default_instance_; delete ControlConf_reflection_; } void protobuf_AddDesc_control_2fcontrol_5fconf_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AddDesc_control_2fcontrol_5fconf_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::apollo::canbus::protobuf_AddDesc_canbus_2fchassis_2eproto(); ::apollo::control::protobuf_AddDesc_control_2fpad_5fmsg_2eproto(); ::apollo::control::protobuf_AddDesc_control_2flat_5fcontroller_5fconf_2eproto(); ::apollo::control::protobuf_AddDesc_control_2flon_5fcontroller_5fconf_2eproto(); ::apollo::control::protobuf_AddDesc_control_2fmpc_5fcontroller_5fconf_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\032control/control_conf.proto\022\016apollo.con" "trol\032\024canbus/chassis.proto\032\025control/pad_" "msg.proto\032!control/lat_controller_conf.p" "roto\032!control/lon_controller_conf.proto\032" "!control/mpc_controller_conf.proto\"\302\006\n\013C" "ontrolConf\022\026\n\016control_period\030\001 \001(\001\022!\n\031ma" "x_planning_interval_sec\030\002 \001(\001\022$\n\034max_pla" "nning_delay_threshold\030\003 \001(\001\0228\n\014driving_m" "ode\030\004 \001(\0162\".apollo.canbus.Chassis.Drivin" "gMode\022-\n\006action\030\005 \001(\0162\035.apollo.control.D" "rivingAction\022\030\n\020soft_estop_brake\030\006 \001(\001\022F" "\n\022active_controllers\030\007 \003(\0162*.apollo.cont" "rol.ControlConf.ControllerType\022\'\n\037max_st" "eering_percentage_allowed\030\010 \001(\005\022\037\n\027max_s" "tatus_interval_sec\030\t \001(\001\022>\n\023lat_controll" "er_conf\030\n \001(\0132!.apollo.control.LatContro" "llerConf\022>\n\023lon_controller_conf\030\013 \001(\0132!." "apollo.control.LonControllerConf\022\031\n\021traj" "ectory_period\030\014 \001(\001\022\026\n\016chassis_period\030\r " "\001(\001\022\033\n\023localization_period\030\016 \001(\001\022 \n\030mini" "mum_speed_resolution\030\017 \001(\001\022>\n\023mpc_contro" "ller_conf\030\020 \001(\0132!.apollo.control.MPCCont" "rollerConf\022\033\n\023query_relative_time\030\021 \001(\001\022" " \n\030minimum_speed_protection\030\022 \001(\001\"L\n\016Con" "trollerType\022\022\n\016LAT_CONTROLLER\020\000\022\022\n\016LON_C" "ONTROLLER\020\001\022\022\n\016MPC_CONTROLLER\020\002", 1031); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "control/control_conf.proto", &protobuf_RegisterTypes); ControlConf::default_instance_ = new ControlConf(); ControlConf::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_control_2fcontrol_5fconf_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_control_2fcontrol_5fconf_2eproto { StaticDescriptorInitializer_control_2fcontrol_5fconf_2eproto() { protobuf_AddDesc_control_2fcontrol_5fconf_2eproto(); } } static_descriptor_initializer_control_2fcontrol_5fconf_2eproto_; // =================================================================== const ::google::protobuf::EnumDescriptor* ControlConf_ControllerType_descriptor() { protobuf_AssignDescriptorsOnce(); return ControlConf_ControllerType_descriptor_; } bool ControlConf_ControllerType_IsValid(int value) { switch(value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const ControlConf_ControllerType ControlConf::LAT_CONTROLLER; const ControlConf_ControllerType ControlConf::LON_CONTROLLER; const ControlConf_ControllerType ControlConf::MPC_CONTROLLER; const ControlConf_ControllerType ControlConf::ControllerType_MIN; const ControlConf_ControllerType ControlConf::ControllerType_MAX; const int ControlConf::ControllerType_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int ControlConf::kControlPeriodFieldNumber; const int ControlConf::kMaxPlanningIntervalSecFieldNumber; const int ControlConf::kMaxPlanningDelayThresholdFieldNumber; const int ControlConf::kDrivingModeFieldNumber; const int ControlConf::kActionFieldNumber; const int ControlConf::kSoftEstopBrakeFieldNumber; const int ControlConf::kActiveControllersFieldNumber; const int ControlConf::kMaxSteeringPercentageAllowedFieldNumber; const int ControlConf::kMaxStatusIntervalSecFieldNumber; const int ControlConf::kLatControllerConfFieldNumber; const int ControlConf::kLonControllerConfFieldNumber; const int ControlConf::kTrajectoryPeriodFieldNumber; const int ControlConf::kChassisPeriodFieldNumber; const int ControlConf::kLocalizationPeriodFieldNumber; const int ControlConf::kMinimumSpeedResolutionFieldNumber; const int ControlConf::kMpcControllerConfFieldNumber; const int ControlConf::kQueryRelativeTimeFieldNumber; const int ControlConf::kMinimumSpeedProtectionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ControlConf::ControlConf() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.control.ControlConf) } void ControlConf::InitAsDefaultInstance() { lat_controller_conf_ = const_cast< ::apollo::control::LatControllerConf*>(&::apollo::control::LatControllerConf::default_instance()); lon_controller_conf_ = const_cast< ::apollo::control::LonControllerConf*>(&::apollo::control::LonControllerConf::default_instance()); mpc_controller_conf_ = const_cast< ::apollo::control::MPCControllerConf*>(&::apollo::control::MPCControllerConf::default_instance()); } ControlConf::ControlConf(const ControlConf& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.control.ControlConf) } void ControlConf::SharedCtor() { _cached_size_ = 0; control_period_ = 0; max_planning_interval_sec_ = 0; max_planning_delay_threshold_ = 0; driving_mode_ = 0; action_ = 0; soft_estop_brake_ = 0; max_steering_percentage_allowed_ = 0; max_status_interval_sec_ = 0; lat_controller_conf_ = NULL; lon_controller_conf_ = NULL; trajectory_period_ = 0; chassis_period_ = 0; localization_period_ = 0; minimum_speed_resolution_ = 0; mpc_controller_conf_ = NULL; query_relative_time_ = 0; minimum_speed_protection_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ControlConf::~ControlConf() { // @@protoc_insertion_point(destructor:apollo.control.ControlConf) SharedDtor(); } void ControlConf::SharedDtor() { if (this != default_instance_) { delete lat_controller_conf_; delete lon_controller_conf_; delete mpc_controller_conf_; } } void ControlConf::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ControlConf::descriptor() { protobuf_AssignDescriptorsOnce(); return ControlConf_descriptor_; } const ControlConf& ControlConf::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_control_2fcontrol_5fconf_2eproto(); return *default_instance_; } ControlConf* ControlConf::default_instance_ = NULL; ControlConf* ControlConf::New(::google::protobuf::Arena* arena) const { ControlConf* n = new ControlConf; if (arena != NULL) { arena->Own(n); } return n; } void ControlConf::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.control.ControlConf) #if defined(__clang__) #define ZR_HELPER_(f) \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \ __builtin_offsetof(ControlConf, f) \ _Pragma("clang diagnostic pop") #else #define ZR_HELPER_(f) reinterpret_cast<char*>(\ &reinterpret_cast<ControlConf*>(16)->f) #endif #define ZR_(first, last) do {\ ::memset(&first, 0,\ ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\ } while (0) if (_has_bits_[0 / 32] & 191u) { ZR_(control_period_, soft_estop_brake_); max_steering_percentage_allowed_ = 0; } if (_has_bits_[8 / 32] & 65280u) { ZR_(trajectory_period_, minimum_speed_resolution_); max_status_interval_sec_ = 0; if (has_lat_controller_conf()) { if (lat_controller_conf_ != NULL) lat_controller_conf_->::apollo::control::LatControllerConf::Clear(); } if (has_lon_controller_conf()) { if (lon_controller_conf_ != NULL) lon_controller_conf_->::apollo::control::LonControllerConf::Clear(); } if (has_mpc_controller_conf()) { if (mpc_controller_conf_ != NULL) mpc_controller_conf_->::apollo::control::MPCControllerConf::Clear(); } } ZR_(query_relative_time_, minimum_speed_protection_); #undef ZR_HELPER_ #undef ZR_ active_controllers_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool ControlConf::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.control.ControlConf) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(16383); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional double control_period = 1; case 1: { if (tag == 9) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &control_period_))); set_has_control_period(); } else { goto handle_unusual; } if (input->ExpectTag(17)) goto parse_max_planning_interval_sec; break; } // optional double max_planning_interval_sec = 2; case 2: { if (tag == 17) { parse_max_planning_interval_sec: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &max_planning_interval_sec_))); set_has_max_planning_interval_sec(); } else { goto handle_unusual; } if (input->ExpectTag(25)) goto parse_max_planning_delay_threshold; break; } // optional double max_planning_delay_threshold = 3; case 3: { if (tag == 25) { parse_max_planning_delay_threshold: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &max_planning_delay_threshold_))); set_has_max_planning_delay_threshold(); } else { goto handle_unusual; } if (input->ExpectTag(32)) goto parse_driving_mode; break; } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; case 4: { if (tag == 32) { parse_driving_mode: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::canbus::Chassis_DrivingMode_IsValid(value)) { set_driving_mode(static_cast< ::apollo::canbus::Chassis_DrivingMode >(value)); } else { mutable_unknown_fields()->AddVarint(4, value); } } else { goto handle_unusual; } if (input->ExpectTag(40)) goto parse_action; break; } // optional .apollo.control.DrivingAction action = 5; case 5: { if (tag == 40) { parse_action: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::control::DrivingAction_IsValid(value)) { set_action(static_cast< ::apollo::control::DrivingAction >(value)); } else { mutable_unknown_fields()->AddVarint(5, value); } } else { goto handle_unusual; } if (input->ExpectTag(49)) goto parse_soft_estop_brake; break; } // optional double soft_estop_brake = 6; case 6: { if (tag == 49) { parse_soft_estop_brake: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &soft_estop_brake_))); set_has_soft_estop_brake(); } else { goto handle_unusual; } if (input->ExpectTag(56)) goto parse_active_controllers; break; } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; case 7: { if (tag == 56) { parse_active_controllers: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::control::ControlConf_ControllerType_IsValid(value)) { add_active_controllers(static_cast< ::apollo::control::ControlConf_ControllerType >(value)); } else { mutable_unknown_fields()->AddVarint(7, value); } } else if (tag == 58) { DO_((::google::protobuf::internal::WireFormat::ReadPackedEnumPreserveUnknowns( input, 7, ::apollo::control::ControlConf_ControllerType_IsValid, mutable_unknown_fields(), this->mutable_active_controllers()))); } else { goto handle_unusual; } if (input->ExpectTag(56)) goto parse_active_controllers; if (input->ExpectTag(64)) goto parse_max_steering_percentage_allowed; break; } // optional int32 max_steering_percentage_allowed = 8; case 8: { if (tag == 64) { parse_max_steering_percentage_allowed: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &max_steering_percentage_allowed_))); set_has_max_steering_percentage_allowed(); } else { goto handle_unusual; } if (input->ExpectTag(73)) goto parse_max_status_interval_sec; break; } // optional double max_status_interval_sec = 9; case 9: { if (tag == 73) { parse_max_status_interval_sec: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &max_status_interval_sec_))); set_has_max_status_interval_sec(); } else { goto handle_unusual; } if (input->ExpectTag(82)) goto parse_lat_controller_conf; break; } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; case 10: { if (tag == 82) { parse_lat_controller_conf: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_lat_controller_conf())); } else { goto handle_unusual; } if (input->ExpectTag(90)) goto parse_lon_controller_conf; break; } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; case 11: { if (tag == 90) { parse_lon_controller_conf: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_lon_controller_conf())); } else { goto handle_unusual; } if (input->ExpectTag(97)) goto parse_trajectory_period; break; } // optional double trajectory_period = 12; case 12: { if (tag == 97) { parse_trajectory_period: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &trajectory_period_))); set_has_trajectory_period(); } else { goto handle_unusual; } if (input->ExpectTag(105)) goto parse_chassis_period; break; } // optional double chassis_period = 13; case 13: { if (tag == 105) { parse_chassis_period: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &chassis_period_))); set_has_chassis_period(); } else { goto handle_unusual; } if (input->ExpectTag(113)) goto parse_localization_period; break; } // optional double localization_period = 14; case 14: { if (tag == 113) { parse_localization_period: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &localization_period_))); set_has_localization_period(); } else { goto handle_unusual; } if (input->ExpectTag(121)) goto parse_minimum_speed_resolution; break; } // optional double minimum_speed_resolution = 15; case 15: { if (tag == 121) { parse_minimum_speed_resolution: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &minimum_speed_resolution_))); set_has_minimum_speed_resolution(); } else { goto handle_unusual; } if (input->ExpectTag(130)) goto parse_mpc_controller_conf; break; } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; case 16: { if (tag == 130) { parse_mpc_controller_conf: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_mpc_controller_conf())); } else { goto handle_unusual; } if (input->ExpectTag(137)) goto parse_query_relative_time; break; } // optional double query_relative_time = 17; case 17: { if (tag == 137) { parse_query_relative_time: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &query_relative_time_))); set_has_query_relative_time(); } else { goto handle_unusual; } if (input->ExpectTag(145)) goto parse_minimum_speed_protection; break; } // optional double minimum_speed_protection = 18; case 18: { if (tag == 145) { parse_minimum_speed_protection: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &minimum_speed_protection_))); set_has_minimum_speed_protection(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.control.ControlConf) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.control.ControlConf) return false; #undef DO_ } void ControlConf::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.control.ControlConf) // optional double control_period = 1; if (has_control_period()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->control_period(), output); } // optional double max_planning_interval_sec = 2; if (has_max_planning_interval_sec()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->max_planning_interval_sec(), output); } // optional double max_planning_delay_threshold = 3; if (has_max_planning_delay_threshold()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->max_planning_delay_threshold(), output); } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; if (has_driving_mode()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 4, this->driving_mode(), output); } // optional .apollo.control.DrivingAction action = 5; if (has_action()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 5, this->action(), output); } // optional double soft_estop_brake = 6; if (has_soft_estop_brake()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->soft_estop_brake(), output); } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; for (int i = 0; i < this->active_controllers_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 7, this->active_controllers(i), output); } // optional int32 max_steering_percentage_allowed = 8; if (has_max_steering_percentage_allowed()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(8, this->max_steering_percentage_allowed(), output); } // optional double max_status_interval_sec = 9; if (has_max_status_interval_sec()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(9, this->max_status_interval_sec(), output); } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; if (has_lat_controller_conf()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 10, *this->lat_controller_conf_, output); } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; if (has_lon_controller_conf()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 11, *this->lon_controller_conf_, output); } // optional double trajectory_period = 12; if (has_trajectory_period()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(12, this->trajectory_period(), output); } // optional double chassis_period = 13; if (has_chassis_period()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(13, this->chassis_period(), output); } // optional double localization_period = 14; if (has_localization_period()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(14, this->localization_period(), output); } // optional double minimum_speed_resolution = 15; if (has_minimum_speed_resolution()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(15, this->minimum_speed_resolution(), output); } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; if (has_mpc_controller_conf()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 16, *this->mpc_controller_conf_, output); } // optional double query_relative_time = 17; if (has_query_relative_time()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(17, this->query_relative_time(), output); } // optional double minimum_speed_protection = 18; if (has_minimum_speed_protection()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(18, this->minimum_speed_protection(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.control.ControlConf) } ::google::protobuf::uint8* ControlConf::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.control.ControlConf) // optional double control_period = 1; if (has_control_period()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->control_period(), target); } // optional double max_planning_interval_sec = 2; if (has_max_planning_interval_sec()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->max_planning_interval_sec(), target); } // optional double max_planning_delay_threshold = 3; if (has_max_planning_delay_threshold()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->max_planning_delay_threshold(), target); } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; if (has_driving_mode()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 4, this->driving_mode(), target); } // optional .apollo.control.DrivingAction action = 5; if (has_action()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 5, this->action(), target); } // optional double soft_estop_brake = 6; if (has_soft_estop_brake()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->soft_estop_brake(), target); } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; for (int i = 0; i < this->active_controllers_size(); i++) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 7, this->active_controllers(i), target); } // optional int32 max_steering_percentage_allowed = 8; if (has_max_steering_percentage_allowed()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(8, this->max_steering_percentage_allowed(), target); } // optional double max_status_interval_sec = 9; if (has_max_status_interval_sec()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(9, this->max_status_interval_sec(), target); } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; if (has_lat_controller_conf()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 10, *this->lat_controller_conf_, false, target); } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; if (has_lon_controller_conf()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 11, *this->lon_controller_conf_, false, target); } // optional double trajectory_period = 12; if (has_trajectory_period()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(12, this->trajectory_period(), target); } // optional double chassis_period = 13; if (has_chassis_period()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(13, this->chassis_period(), target); } // optional double localization_period = 14; if (has_localization_period()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(14, this->localization_period(), target); } // optional double minimum_speed_resolution = 15; if (has_minimum_speed_resolution()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(15, this->minimum_speed_resolution(), target); } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; if (has_mpc_controller_conf()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 16, *this->mpc_controller_conf_, false, target); } // optional double query_relative_time = 17; if (has_query_relative_time()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(17, this->query_relative_time(), target); } // optional double minimum_speed_protection = 18; if (has_minimum_speed_protection()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(18, this->minimum_speed_protection(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.control.ControlConf) return target; } int ControlConf::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.control.ControlConf) int total_size = 0; if (_has_bits_[0 / 32] & 191u) { // optional double control_period = 1; if (has_control_period()) { total_size += 1 + 8; } // optional double max_planning_interval_sec = 2; if (has_max_planning_interval_sec()) { total_size += 1 + 8; } // optional double max_planning_delay_threshold = 3; if (has_max_planning_delay_threshold()) { total_size += 1 + 8; } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; if (has_driving_mode()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->driving_mode()); } // optional .apollo.control.DrivingAction action = 5; if (has_action()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->action()); } // optional double soft_estop_brake = 6; if (has_soft_estop_brake()) { total_size += 1 + 8; } // optional int32 max_steering_percentage_allowed = 8; if (has_max_steering_percentage_allowed()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->max_steering_percentage_allowed()); } } if (_has_bits_[8 / 32] & 65280u) { // optional double max_status_interval_sec = 9; if (has_max_status_interval_sec()) { total_size += 1 + 8; } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; if (has_lat_controller_conf()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->lat_controller_conf_); } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; if (has_lon_controller_conf()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->lon_controller_conf_); } // optional double trajectory_period = 12; if (has_trajectory_period()) { total_size += 1 + 8; } // optional double chassis_period = 13; if (has_chassis_period()) { total_size += 1 + 8; } // optional double localization_period = 14; if (has_localization_period()) { total_size += 1 + 8; } // optional double minimum_speed_resolution = 15; if (has_minimum_speed_resolution()) { total_size += 1 + 8; } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; if (has_mpc_controller_conf()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->mpc_controller_conf_); } } if (_has_bits_[16 / 32] & 196608u) { // optional double query_relative_time = 17; if (has_query_relative_time()) { total_size += 2 + 8; } // optional double minimum_speed_protection = 18; if (has_minimum_speed_protection()) { total_size += 2 + 8; } } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; { int data_size = 0; for (int i = 0; i < this->active_controllers_size(); i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->active_controllers(i)); } total_size += 1 * this->active_controllers_size() + data_size; } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ControlConf::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.control.ControlConf) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const ControlConf* source = ::google::protobuf::internal::DynamicCastToGenerated<const ControlConf>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.control.ControlConf) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.control.ControlConf) MergeFrom(*source); } } void ControlConf::MergeFrom(const ControlConf& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.control.ControlConf) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } active_controllers_.MergeFrom(from.active_controllers_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_control_period()) { set_control_period(from.control_period()); } if (from.has_max_planning_interval_sec()) { set_max_planning_interval_sec(from.max_planning_interval_sec()); } if (from.has_max_planning_delay_threshold()) { set_max_planning_delay_threshold(from.max_planning_delay_threshold()); } if (from.has_driving_mode()) { set_driving_mode(from.driving_mode()); } if (from.has_action()) { set_action(from.action()); } if (from.has_soft_estop_brake()) { set_soft_estop_brake(from.soft_estop_brake()); } if (from.has_max_steering_percentage_allowed()) { set_max_steering_percentage_allowed(from.max_steering_percentage_allowed()); } } if (from._has_bits_[8 / 32] & (0xffu << (8 % 32))) { if (from.has_max_status_interval_sec()) { set_max_status_interval_sec(from.max_status_interval_sec()); } if (from.has_lat_controller_conf()) { mutable_lat_controller_conf()->::apollo::control::LatControllerConf::MergeFrom(from.lat_controller_conf()); } if (from.has_lon_controller_conf()) { mutable_lon_controller_conf()->::apollo::control::LonControllerConf::MergeFrom(from.lon_controller_conf()); } if (from.has_trajectory_period()) { set_trajectory_period(from.trajectory_period()); } if (from.has_chassis_period()) { set_chassis_period(from.chassis_period()); } if (from.has_localization_period()) { set_localization_period(from.localization_period()); } if (from.has_minimum_speed_resolution()) { set_minimum_speed_resolution(from.minimum_speed_resolution()); } if (from.has_mpc_controller_conf()) { mutable_mpc_controller_conf()->::apollo::control::MPCControllerConf::MergeFrom(from.mpc_controller_conf()); } } if (from._has_bits_[16 / 32] & (0xffu << (16 % 32))) { if (from.has_query_relative_time()) { set_query_relative_time(from.query_relative_time()); } if (from.has_minimum_speed_protection()) { set_minimum_speed_protection(from.minimum_speed_protection()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void ControlConf::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.control.ControlConf) if (&from == this) return; Clear(); MergeFrom(from); } void ControlConf::CopyFrom(const ControlConf& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.control.ControlConf) if (&from == this) return; Clear(); MergeFrom(from); } bool ControlConf::IsInitialized() const { return true; } void ControlConf::Swap(ControlConf* other) { if (other == this) return; InternalSwap(other); } void ControlConf::InternalSwap(ControlConf* other) { std::swap(control_period_, other->control_period_); std::swap(max_planning_interval_sec_, other->max_planning_interval_sec_); std::swap(max_planning_delay_threshold_, other->max_planning_delay_threshold_); std::swap(driving_mode_, other->driving_mode_); std::swap(action_, other->action_); std::swap(soft_estop_brake_, other->soft_estop_brake_); active_controllers_.UnsafeArenaSwap(&other->active_controllers_); std::swap(max_steering_percentage_allowed_, other->max_steering_percentage_allowed_); std::swap(max_status_interval_sec_, other->max_status_interval_sec_); std::swap(lat_controller_conf_, other->lat_controller_conf_); std::swap(lon_controller_conf_, other->lon_controller_conf_); std::swap(trajectory_period_, other->trajectory_period_); std::swap(chassis_period_, other->chassis_period_); std::swap(localization_period_, other->localization_period_); std::swap(minimum_speed_resolution_, other->minimum_speed_resolution_); std::swap(mpc_controller_conf_, other->mpc_controller_conf_); std::swap(query_relative_time_, other->query_relative_time_); std::swap(minimum_speed_protection_, other->minimum_speed_protection_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata ControlConf::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ControlConf_descriptor_; metadata.reflection = ControlConf_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // ControlConf // optional double control_period = 1; bool ControlConf::has_control_period() const { return (_has_bits_[0] & 0x00000001u) != 0; } void ControlConf::set_has_control_period() { _has_bits_[0] |= 0x00000001u; } void ControlConf::clear_has_control_period() { _has_bits_[0] &= ~0x00000001u; } void ControlConf::clear_control_period() { control_period_ = 0; clear_has_control_period(); } double ControlConf::control_period() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.control_period) return control_period_; } void ControlConf::set_control_period(double value) { set_has_control_period(); control_period_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.control_period) } // optional double max_planning_interval_sec = 2; bool ControlConf::has_max_planning_interval_sec() const { return (_has_bits_[0] & 0x00000002u) != 0; } void ControlConf::set_has_max_planning_interval_sec() { _has_bits_[0] |= 0x00000002u; } void ControlConf::clear_has_max_planning_interval_sec() { _has_bits_[0] &= ~0x00000002u; } void ControlConf::clear_max_planning_interval_sec() { max_planning_interval_sec_ = 0; clear_has_max_planning_interval_sec(); } double ControlConf::max_planning_interval_sec() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.max_planning_interval_sec) return max_planning_interval_sec_; } void ControlConf::set_max_planning_interval_sec(double value) { set_has_max_planning_interval_sec(); max_planning_interval_sec_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.max_planning_interval_sec) } // optional double max_planning_delay_threshold = 3; bool ControlConf::has_max_planning_delay_threshold() const { return (_has_bits_[0] & 0x00000004u) != 0; } void ControlConf::set_has_max_planning_delay_threshold() { _has_bits_[0] |= 0x00000004u; } void ControlConf::clear_has_max_planning_delay_threshold() { _has_bits_[0] &= ~0x00000004u; } void ControlConf::clear_max_planning_delay_threshold() { max_planning_delay_threshold_ = 0; clear_has_max_planning_delay_threshold(); } double ControlConf::max_planning_delay_threshold() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.max_planning_delay_threshold) return max_planning_delay_threshold_; } void ControlConf::set_max_planning_delay_threshold(double value) { set_has_max_planning_delay_threshold(); max_planning_delay_threshold_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.max_planning_delay_threshold) } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; bool ControlConf::has_driving_mode() const { return (_has_bits_[0] & 0x00000008u) != 0; } void ControlConf::set_has_driving_mode() { _has_bits_[0] |= 0x00000008u; } void ControlConf::clear_has_driving_mode() { _has_bits_[0] &= ~0x00000008u; } void ControlConf::clear_driving_mode() { driving_mode_ = 0; clear_has_driving_mode(); } ::apollo::canbus::Chassis_DrivingMode ControlConf::driving_mode() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.driving_mode) return static_cast< ::apollo::canbus::Chassis_DrivingMode >(driving_mode_); } void ControlConf::set_driving_mode(::apollo::canbus::Chassis_DrivingMode value) { assert(::apollo::canbus::Chassis_DrivingMode_IsValid(value)); set_has_driving_mode(); driving_mode_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.driving_mode) } // optional .apollo.control.DrivingAction action = 5; bool ControlConf::has_action() const { return (_has_bits_[0] & 0x00000010u) != 0; } void ControlConf::set_has_action() { _has_bits_[0] |= 0x00000010u; } void ControlConf::clear_has_action() { _has_bits_[0] &= ~0x00000010u; } void ControlConf::clear_action() { action_ = 0; clear_has_action(); } ::apollo::control::DrivingAction ControlConf::action() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.action) return static_cast< ::apollo::control::DrivingAction >(action_); } void ControlConf::set_action(::apollo::control::DrivingAction value) { assert(::apollo::control::DrivingAction_IsValid(value)); set_has_action(); action_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.action) } // optional double soft_estop_brake = 6; bool ControlConf::has_soft_estop_brake() const { return (_has_bits_[0] & 0x00000020u) != 0; } void ControlConf::set_has_soft_estop_brake() { _has_bits_[0] |= 0x00000020u; } void ControlConf::clear_has_soft_estop_brake() { _has_bits_[0] &= ~0x00000020u; } void ControlConf::clear_soft_estop_brake() { soft_estop_brake_ = 0; clear_has_soft_estop_brake(); } double ControlConf::soft_estop_brake() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.soft_estop_brake) return soft_estop_brake_; } void ControlConf::set_soft_estop_brake(double value) { set_has_soft_estop_brake(); soft_estop_brake_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.soft_estop_brake) } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; int ControlConf::active_controllers_size() const { return active_controllers_.size(); } void ControlConf::clear_active_controllers() { active_controllers_.Clear(); } ::apollo::control::ControlConf_ControllerType ControlConf::active_controllers(int index) const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.active_controllers) return static_cast< ::apollo::control::ControlConf_ControllerType >(active_controllers_.Get(index)); } void ControlConf::set_active_controllers(int index, ::apollo::control::ControlConf_ControllerType value) { assert(::apollo::control::ControlConf_ControllerType_IsValid(value)); active_controllers_.Set(index, value); // @@protoc_insertion_point(field_set:apollo.control.ControlConf.active_controllers) } void ControlConf::add_active_controllers(::apollo::control::ControlConf_ControllerType value) { assert(::apollo::control::ControlConf_ControllerType_IsValid(value)); active_controllers_.Add(value); // @@protoc_insertion_point(field_add:apollo.control.ControlConf.active_controllers) } const ::google::protobuf::RepeatedField<int>& ControlConf::active_controllers() const { // @@protoc_insertion_point(field_list:apollo.control.ControlConf.active_controllers) return active_controllers_; } ::google::protobuf::RepeatedField<int>* ControlConf::mutable_active_controllers() { // @@protoc_insertion_point(field_mutable_list:apollo.control.ControlConf.active_controllers) return &active_controllers_; } // optional int32 max_steering_percentage_allowed = 8; bool ControlConf::has_max_steering_percentage_allowed() const { return (_has_bits_[0] & 0x00000080u) != 0; } void ControlConf::set_has_max_steering_percentage_allowed() { _has_bits_[0] |= 0x00000080u; } void ControlConf::clear_has_max_steering_percentage_allowed() { _has_bits_[0] &= ~0x00000080u; } void ControlConf::clear_max_steering_percentage_allowed() { max_steering_percentage_allowed_ = 0; clear_has_max_steering_percentage_allowed(); } ::google::protobuf::int32 ControlConf::max_steering_percentage_allowed() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.max_steering_percentage_allowed) return max_steering_percentage_allowed_; } void ControlConf::set_max_steering_percentage_allowed(::google::protobuf::int32 value) { set_has_max_steering_percentage_allowed(); max_steering_percentage_allowed_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.max_steering_percentage_allowed) } // optional double max_status_interval_sec = 9; bool ControlConf::has_max_status_interval_sec() const { return (_has_bits_[0] & 0x00000100u) != 0; } void ControlConf::set_has_max_status_interval_sec() { _has_bits_[0] |= 0x00000100u; } void ControlConf::clear_has_max_status_interval_sec() { _has_bits_[0] &= ~0x00000100u; } void ControlConf::clear_max_status_interval_sec() { max_status_interval_sec_ = 0; clear_has_max_status_interval_sec(); } double ControlConf::max_status_interval_sec() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.max_status_interval_sec) return max_status_interval_sec_; } void ControlConf::set_max_status_interval_sec(double value) { set_has_max_status_interval_sec(); max_status_interval_sec_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.max_status_interval_sec) } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; bool ControlConf::has_lat_controller_conf() const { return (_has_bits_[0] & 0x00000200u) != 0; } void ControlConf::set_has_lat_controller_conf() { _has_bits_[0] |= 0x00000200u; } void ControlConf::clear_has_lat_controller_conf() { _has_bits_[0] &= ~0x00000200u; } void ControlConf::clear_lat_controller_conf() { if (lat_controller_conf_ != NULL) lat_controller_conf_->::apollo::control::LatControllerConf::Clear(); clear_has_lat_controller_conf(); } const ::apollo::control::LatControllerConf& ControlConf::lat_controller_conf() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.lat_controller_conf) return lat_controller_conf_ != NULL ? *lat_controller_conf_ : *default_instance_->lat_controller_conf_; } ::apollo::control::LatControllerConf* ControlConf::mutable_lat_controller_conf() { set_has_lat_controller_conf(); if (lat_controller_conf_ == NULL) { lat_controller_conf_ = new ::apollo::control::LatControllerConf; } // @@protoc_insertion_point(field_mutable:apollo.control.ControlConf.lat_controller_conf) return lat_controller_conf_; } ::apollo::control::LatControllerConf* ControlConf::release_lat_controller_conf() { // @@protoc_insertion_point(field_release:apollo.control.ControlConf.lat_controller_conf) clear_has_lat_controller_conf(); ::apollo::control::LatControllerConf* temp = lat_controller_conf_; lat_controller_conf_ = NULL; return temp; } void ControlConf::set_allocated_lat_controller_conf(::apollo::control::LatControllerConf* lat_controller_conf) { delete lat_controller_conf_; lat_controller_conf_ = lat_controller_conf; if (lat_controller_conf) { set_has_lat_controller_conf(); } else { clear_has_lat_controller_conf(); } // @@protoc_insertion_point(field_set_allocated:apollo.control.ControlConf.lat_controller_conf) } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; bool ControlConf::has_lon_controller_conf() const { return (_has_bits_[0] & 0x00000400u) != 0; } void ControlConf::set_has_lon_controller_conf() { _has_bits_[0] |= 0x00000400u; } void ControlConf::clear_has_lon_controller_conf() { _has_bits_[0] &= ~0x00000400u; } void ControlConf::clear_lon_controller_conf() { if (lon_controller_conf_ != NULL) lon_controller_conf_->::apollo::control::LonControllerConf::Clear(); clear_has_lon_controller_conf(); } const ::apollo::control::LonControllerConf& ControlConf::lon_controller_conf() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.lon_controller_conf) return lon_controller_conf_ != NULL ? *lon_controller_conf_ : *default_instance_->lon_controller_conf_; } ::apollo::control::LonControllerConf* ControlConf::mutable_lon_controller_conf() { set_has_lon_controller_conf(); if (lon_controller_conf_ == NULL) { lon_controller_conf_ = new ::apollo::control::LonControllerConf; } // @@protoc_insertion_point(field_mutable:apollo.control.ControlConf.lon_controller_conf) return lon_controller_conf_; } ::apollo::control::LonControllerConf* ControlConf::release_lon_controller_conf() { // @@protoc_insertion_point(field_release:apollo.control.ControlConf.lon_controller_conf) clear_has_lon_controller_conf(); ::apollo::control::LonControllerConf* temp = lon_controller_conf_; lon_controller_conf_ = NULL; return temp; } void ControlConf::set_allocated_lon_controller_conf(::apollo::control::LonControllerConf* lon_controller_conf) { delete lon_controller_conf_; lon_controller_conf_ = lon_controller_conf; if (lon_controller_conf) { set_has_lon_controller_conf(); } else { clear_has_lon_controller_conf(); } // @@protoc_insertion_point(field_set_allocated:apollo.control.ControlConf.lon_controller_conf) } // optional double trajectory_period = 12; bool ControlConf::has_trajectory_period() const { return (_has_bits_[0] & 0x00000800u) != 0; } void ControlConf::set_has_trajectory_period() { _has_bits_[0] |= 0x00000800u; } void ControlConf::clear_has_trajectory_period() { _has_bits_[0] &= ~0x00000800u; } void ControlConf::clear_trajectory_period() { trajectory_period_ = 0; clear_has_trajectory_period(); } double ControlConf::trajectory_period() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.trajectory_period) return trajectory_period_; } void ControlConf::set_trajectory_period(double value) { set_has_trajectory_period(); trajectory_period_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.trajectory_period) } // optional double chassis_period = 13; bool ControlConf::has_chassis_period() const { return (_has_bits_[0] & 0x00001000u) != 0; } void ControlConf::set_has_chassis_period() { _has_bits_[0] |= 0x00001000u; } void ControlConf::clear_has_chassis_period() { _has_bits_[0] &= ~0x00001000u; } void ControlConf::clear_chassis_period() { chassis_period_ = 0; clear_has_chassis_period(); } double ControlConf::chassis_period() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.chassis_period) return chassis_period_; } void ControlConf::set_chassis_period(double value) { set_has_chassis_period(); chassis_period_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.chassis_period) } // optional double localization_period = 14; bool ControlConf::has_localization_period() const { return (_has_bits_[0] & 0x00002000u) != 0; } void ControlConf::set_has_localization_period() { _has_bits_[0] |= 0x00002000u; } void ControlConf::clear_has_localization_period() { _has_bits_[0] &= ~0x00002000u; } void ControlConf::clear_localization_period() { localization_period_ = 0; clear_has_localization_period(); } double ControlConf::localization_period() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.localization_period) return localization_period_; } void ControlConf::set_localization_period(double value) { set_has_localization_period(); localization_period_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.localization_period) } // optional double minimum_speed_resolution = 15; bool ControlConf::has_minimum_speed_resolution() const { return (_has_bits_[0] & 0x00004000u) != 0; } void ControlConf::set_has_minimum_speed_resolution() { _has_bits_[0] |= 0x00004000u; } void ControlConf::clear_has_minimum_speed_resolution() { _has_bits_[0] &= ~0x00004000u; } void ControlConf::clear_minimum_speed_resolution() { minimum_speed_resolution_ = 0; clear_has_minimum_speed_resolution(); } double ControlConf::minimum_speed_resolution() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.minimum_speed_resolution) return minimum_speed_resolution_; } void ControlConf::set_minimum_speed_resolution(double value) { set_has_minimum_speed_resolution(); minimum_speed_resolution_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.minimum_speed_resolution) } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; bool ControlConf::has_mpc_controller_conf() const { return (_has_bits_[0] & 0x00008000u) != 0; } void ControlConf::set_has_mpc_controller_conf() { _has_bits_[0] |= 0x00008000u; } void ControlConf::clear_has_mpc_controller_conf() { _has_bits_[0] &= ~0x00008000u; } void ControlConf::clear_mpc_controller_conf() { if (mpc_controller_conf_ != NULL) mpc_controller_conf_->::apollo::control::MPCControllerConf::Clear(); clear_has_mpc_controller_conf(); } const ::apollo::control::MPCControllerConf& ControlConf::mpc_controller_conf() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.mpc_controller_conf) return mpc_controller_conf_ != NULL ? *mpc_controller_conf_ : *default_instance_->mpc_controller_conf_; } ::apollo::control::MPCControllerConf* ControlConf::mutable_mpc_controller_conf() { set_has_mpc_controller_conf(); if (mpc_controller_conf_ == NULL) { mpc_controller_conf_ = new ::apollo::control::MPCControllerConf; } // @@protoc_insertion_point(field_mutable:apollo.control.ControlConf.mpc_controller_conf) return mpc_controller_conf_; } ::apollo::control::MPCControllerConf* ControlConf::release_mpc_controller_conf() { // @@protoc_insertion_point(field_release:apollo.control.ControlConf.mpc_controller_conf) clear_has_mpc_controller_conf(); ::apollo::control::MPCControllerConf* temp = mpc_controller_conf_; mpc_controller_conf_ = NULL; return temp; } void ControlConf::set_allocated_mpc_controller_conf(::apollo::control::MPCControllerConf* mpc_controller_conf) { delete mpc_controller_conf_; mpc_controller_conf_ = mpc_controller_conf; if (mpc_controller_conf) { set_has_mpc_controller_conf(); } else { clear_has_mpc_controller_conf(); } // @@protoc_insertion_point(field_set_allocated:apollo.control.ControlConf.mpc_controller_conf) } // optional double query_relative_time = 17; bool ControlConf::has_query_relative_time() const { return (_has_bits_[0] & 0x00010000u) != 0; } void ControlConf::set_has_query_relative_time() { _has_bits_[0] |= 0x00010000u; } void ControlConf::clear_has_query_relative_time() { _has_bits_[0] &= ~0x00010000u; } void ControlConf::clear_query_relative_time() { query_relative_time_ = 0; clear_has_query_relative_time(); } double ControlConf::query_relative_time() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.query_relative_time) return query_relative_time_; } void ControlConf::set_query_relative_time(double value) { set_has_query_relative_time(); query_relative_time_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.query_relative_time) } // optional double minimum_speed_protection = 18; bool ControlConf::has_minimum_speed_protection() const { return (_has_bits_[0] & 0x00020000u) != 0; } void ControlConf::set_has_minimum_speed_protection() { _has_bits_[0] |= 0x00020000u; } void ControlConf::clear_has_minimum_speed_protection() { _has_bits_[0] &= ~0x00020000u; } void ControlConf::clear_minimum_speed_protection() { minimum_speed_protection_ = 0; clear_has_minimum_speed_protection(); } double ControlConf::minimum_speed_protection() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.minimum_speed_protection) return minimum_speed_protection_; } void ControlConf::set_minimum_speed_protection(double value) { set_has_minimum_speed_protection(); minimum_speed_protection_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.minimum_speed_protection) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace control } // namespace apollo // @@protoc_insertion_point(global_scope)
38.066015
135
0.730843
racestart
c1479ada0fad341ed4cad2268e40ee87fc39b67b
132
cpp
C++
benchmark/fenwick/micro/add_byte23bit.cpp
pacman616/hybrid-fenwick-tree
84e7cc8aa84b87937b98d85f3c2ed1998c0d79af
[ "MIT" ]
4
2019-01-10T17:55:43.000Z
2019-11-26T09:33:38.000Z
benchmark/fenwick/micro/add_byte23bit.cpp
pacman616/hybrid-fenwick-tree
84e7cc8aa84b87937b98d85f3c2ed1998c0d79af
[ "MIT" ]
null
null
null
benchmark/fenwick/micro/add_byte23bit.cpp
pacman616/hybrid-fenwick-tree
84e7cc8aa84b87937b98d85f3c2ed1998c0d79af
[ "MIT" ]
null
null
null
#define __HFT_BENCHMARK_FUNCTION__ add<Hybrid<ByteL, BitF, 64, 23>>(name + "/" + "Byte23Bit", queries, re); #include "../micro.cpp"
44
107
0.689394
pacman616
c15218d5e665c1371261e2caaaf75cc3d7b48bc3
1,125
cpp
C++
perf_test/thread/ThreadTest.cpp
armsword/DLog
6b049124098f6c0f622e9a610a87fea27125e0da
[ "MIT" ]
33
2016-09-10T16:42:16.000Z
2021-05-13T07:02:06.000Z
perf_test/thread/ThreadTest.cpp
armsword/DLog
6b049124098f6c0f622e9a610a87fea27125e0da
[ "MIT" ]
1
2016-09-26T16:07:54.000Z
2016-09-26T17:07:29.000Z
perf_test/thread/ThreadTest.cpp
armsword/DLog
6b049124098f6c0f622e9a610a87fea27125e0da
[ "MIT" ]
13
2016-09-14T10:24:15.000Z
2021-01-05T18:46:56.000Z
#include <dlog/logger/Log.h> #include <unistd.h> #include <stdlib.h> #include <sys/time.h> #include <stdint.h> #include <iostream> #include <string.h> #include <pthread.h> using namespace dlog::logger; int64_t currentTime() { struct timeval tval; gettimeofday(&tval, NULL); return (tval.tv_sec * 1000000LL + tval.tv_usec) / 1000000; // 返回秒 } void *print(void* buffer) { for(int i = 0; i < 1500000; i++) { DLOG_LOG(DEBUG, "%s", (char*)buffer); } return ((void*)0); } int main() { DLOG_INIT(); pthread_t tid[2]; char buffer[256]; int i; for(i = 0; i < 255; i++) { buffer[i] = 'A' + rand() % 26; } buffer[i] = '\0'; int64_t begin = currentTime(); for(i = 0; i < 2; i++) { if(pthread_create(&tid[i],NULL,print,buffer) != 0) { std::cout << "create thread error!" << std::endl; exit(1); } } for(i = 0; i < 2; i++) { pthread_join(tid[i], NULL); } int64_t end = currentTime(); int64_t total = end - begin; std::cout << "total time is: " << total << std::endl; return 0; }
21.634615
71
0.537778
armsword
c152bdba5071a5589bb030f6c48876fb4c4a169b
42,535
cpp
C++
AIPDebug/Function-Module/Widget_INDL.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
AIPDebug/Function-Module/Widget_INDL.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
AIPDebug/Function-Module/Widget_INDL.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
#include "Widget_INDL.h" #include "ui_Widget_INDL.h" Widget_INDL::Widget_INDL(QWidget *parent) : QWidget(parent), ui(new Ui::Widget_INDL) { ui->setupUi(this); // 电感设置表头 ui->indlTab->horizontalHeader()->setStyleSheet\ ("QHeaderView::section{background-color:#191919;color: white;"\ "padding-left: 4px;border: 1px solid #447684;}"); ui->indlTab->horizontalHeader()->setFixedHeight(35); ui->indlTab->horizontalHeader()->setResizeMode(QHeaderView::Fixed); ui->indlTab->setColumnWidth(0, 45); // -序号 ui->indlTab->setColumnWidth(1, 45); // -端子T1 ui->indlTab->setColumnWidth(2, 45); // -端子T2 ui->indlTab->setColumnWidth(3, 70); // -下限 ui->indlTab->setColumnWidth(4, 70); // -上限 ui->indlTab->setColumnWidth(5, 70); // -Q值下限 ui->indlTab->setColumnWidth(6, 70); // -Q值上限 ui->indlTab->setColumnWidth(7, 60); // -补偿数值 ui->indlTab->setColumnWidth(8, 60); // -标准值 ui->indlTab->setColumnWidth(9, 60); // -使能 ui->indlTab->setColumnWidth(10, 50); // -使能 INDL_Group = new QButtonGroup; INDL_Group->addButton(ui->Key_1, 1); INDL_Group->addButton(ui->Key_2, 2); INDL_Group->addButton(ui->Key_3, 3); INDL_Group->addButton(ui->Key_4, 4); INDL_Group->addButton(ui->Key_5, 5); INDL_Group->addButton(ui->Key_6, 6); INDL_Group->addButton(ui->Key_7, 7); INDL_Group->addButton(ui->Key_8, 8); connect(INDL_Group, SIGNAL(buttonClicked(int)), this, SLOT(join_buttonJudge(int))); ui->dockWidget->hide(); INDL_Labelhide = new QLabel(this); INDL_Labelhide->setGeometry(0, 0, 800, 600); INDL_Labelhide->hide(); INDL_Init_Flag = false; ui->Button_Comp->hide(); Init_Channel_6 = false; } Widget_INDL::~Widget_INDL() { delete ui; } void Widget_INDL::mousePressEvent(QMouseEvent *event) // 处理鼠标被按下事件 { if ((ui->indlTab->currentColumn() == 1) || \ (ui->indlTab->currentColumn() == 2)) { ui->dockWidget->hide(); INDL_Labelhide->hide(); } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: 初始化电感设置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Init() { int i; INDL_Init_Flag = true; ui->indlTab->setRowCount(8); // 设置电感行数 INDL_QTableWidgetItem.clear(); Box_INDL_Grade_List.clear(); INDL_Unit.clear(); INDL_Unit << "uH" << "mH"; // 电感单位 ui->INDL_time->setValue(Copy_INDL_List.at(0).toInt()); ui->INDL_balance->setValue(Copy_INDL_List.at(1).toDouble()); ui->Com_fre->setCurrentIndex(Copy_INDL_List.at(2).toInt()); ui->Com_connetct->setCurrentIndex(Copy_INDL_List.at(3).toInt()); ui->INDL_Max->setValue(Copy_INDL_List.at(4).toInt()); ui->INDL_Min->setValue(Copy_INDL_List.at(5).toInt()); ui->Com_test->setCurrentIndex(Copy_INDL_List.at(6).toInt()); ui->Q_balance->setValue(Copy_INDL_List.at(7).toDouble()); ui->Com_volt->setCurrentIndex(Copy_INDL_List.at(8).toInt()); for (i = 0; i < 8; i++) { ui->indlTab->setRowHeight(i, 53); QTableWidgetItem *INDL_Number = new QTableWidgetItem; // 序号 INDL_Number->setTextAlignment(Qt::AlignCenter); INDL_Number->setText(QString::number(i+1)); INDL_Number->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(i, 0, INDL_Number); QTableWidgetItem *INDL_Point_one = new QTableWidgetItem; // 端子 1 INDL_Point_one->setTextAlignment(Qt::AlignCenter); INDL_Point_one->setText(Copy_INDL_List.at(INDL_init_Number+20*i+0)); INDL_Point_one->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(i, 1, INDL_Point_one); QTableWidgetItem *INDL_Point_two = new QTableWidgetItem; // 端子 2 INDL_Point_two->setTextAlignment(Qt::AlignCenter); INDL_Point_two->setText(Copy_INDL_List.at(INDL_init_Number+20*i+1)); INDL_Point_two->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(i, 2, INDL_Point_two); QTableWidgetItem *Down_Limit = new QTableWidgetItem; // 电感下限 Down_Limit->setTextAlignment(Qt::AlignCenter); Down_Limit->setText(Copy_INDL_List.at(INDL_init_Number+20*i+2)); ui->indlTab->setItem(i, 3, Down_Limit); QTableWidgetItem *Up_Limit = new QTableWidgetItem; // 电感上限 Up_Limit->setTextAlignment(Qt::AlignCenter); Up_Limit->setText(Copy_INDL_List.at(INDL_init_Number+20*i+3)); ui->indlTab->setItem(i, 4, Up_Limit); QTableWidgetItem *QDown_Limit = new QTableWidgetItem; // Q值下限 QDown_Limit->setTextAlignment(Qt::AlignCenter); QDown_Limit->setText(Copy_INDL_List.at(INDL_init_Number+20*i+4)); ui->indlTab->setItem(i, 5, QDown_Limit); QTableWidgetItem *QUp_Limit = new QTableWidgetItem; // Q值上限 QUp_Limit->setTextAlignment(Qt::AlignCenter); QUp_Limit->setText(Copy_INDL_List.at(INDL_init_Number+20*i+5)); ui->indlTab->setItem(i, 6, QUp_Limit); QTableWidgetItem *Stand_INDL = new QTableWidgetItem; // 标准电感 Stand_INDL->setTextAlignment(Qt::AlignCenter); Stand_INDL->setText(Copy_INDL_List.at(INDL_init_Number+20*i+6)); ui->indlTab->setItem(i, 7, Stand_INDL); QTableWidgetItem *UnitItem = new QTableWidgetItem; // UnitItem->setTextAlignment(Qt::AlignCenter); UnitItem->setText(INDL_Unit[Copy_INDL_List.at(INDL_init_Number+20*i+7).toInt()]); UnitItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(i, 10, UnitItem); Box_INDL_Grade_List.append(new QCheckBox); // 测试项目选择 勾选项目 Box_INDL_Grade_List[i]->setStyleSheet\ ("QCheckBox::indicator {image: url(:/image/053.png);"\ "width: 45px;height: 45px;}QCheckBox::indicator:checked "\ "{image: url(:/image/051.png);}"); ui->indlTab->setCellWidget(i, 11, Box_INDL_Grade_List[i]); if (Copy_INDL_List.at(INDL_init_Number + i*20 + 8).toInt() == 2) { // 档位 (高 中 低 微 超微 极微) Box_INDL_Grade_List.at(i)->setChecked(true); } QTableWidgetItem *Compensation = new QTableWidgetItem; // 补偿电感 Compensation->setTextAlignment(Qt::AlignCenter); Compensation->setText(Copy_INDL_List.at(INDL_init_Number + 20*i + 9)); ui->indlTab->setItem(i, 8, Compensation); QTableWidgetItem *R_Compensation = new QTableWidgetItem; // 右工位-补偿电感 R_Compensation->setTextAlignment(Qt::AlignCenter); R_Compensation->setText(Copy_INDL_List.at(INDL_init_Number + 20*i + 10)); ui->indlTab->setItem(i, 9, R_Compensation); } INDL_Init_Flag = false; } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: 电感参数进行快速设置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Quiky_Test_Parameter() { int i; INDL_TestItemsH = 0; INDL_TestItemsL = 0; INDL_TestNumber = 0; for (i = 0; i < 8; i++) { if (Box_INDL_Grade_List.at(i)->checkState() != 2) { continue; } frame.can_id = 0x26; frame.can_dlc = 0x07; frame.data[0] = 0x03; frame.data[1] = i; frame.data[2] = ui->indlTab->item(i, 1)->text().toInt(); // 抽头 frame.data[3] = ui->indlTab->item(i, 2)->text().toInt(); frame.data[4] = 1; frame.data[5] = 0x0b; frame.data[6] = (int)(0x00|0x09); if (i >= 8) { INDL_TestItemsH = INDL_TestItemsH + (1 << (i-8)); // 高字节 } else { INDL_TestItemsL = INDL_TestItemsL + (1 << i); // 低字节 } INDL_TestNumber++; // 测试总数 canSend(frame); usleep(1000); usleep(1000); usleep(1000); usleep(1000); usleep(1000); usleep(1000); } } /****************************************************************************** * version: 1.0 * author: sl * date: 2015.12.30 * brief: 保存 INDL 配置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Test_Parameter() { int i; i = 0; int Indl_Volt = 0; INDL_TestItemsH = 0; INDL_TestItemsL = 0; INDL_TestNumber = 0; if (ui->Com_volt->currentIndex() == 0) { Indl_Volt = 0x08; } else if (ui->Com_volt->currentIndex() == 1) { Indl_Volt = 0x00; } else if (ui->Com_volt->currentIndex() == 2) { Indl_Volt = 0x10; } else { Indl_Volt = 0x08; } for (i = 0; i < 8; i++) { if (Box_INDL_Grade_List.at(i)->checkState() != 2) { continue; } frame.can_id = 0x26; frame.can_dlc = 0x07; frame.data[0] = 0x03; frame.data[1] = i; frame.data[2] = ui->indlTab->item(i, 1)->text().toInt(); // 抽头 frame.data[3] = ui->indlTab->item(i, 2)->text().toInt(); frame.data[4] = ui->INDL_time->text().toInt(); if (ui->Com_fre->currentText() == "1K") { // frame.data[5] 频率 电压 档位 if (ui->indlTab->item(i, 10)->text() == "mH") { if (6.28*1*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 1) { frame.data[5] = 0x0b; } else if (6.28*1*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 10) { frame.data[5] = 0x2b; } else { frame.data[5] = 0x3b; } } else { frame.data[5] = 0x0b; } } else if (ui->Com_fre->currentText() == "10K") { if (ui->indlTab->item(i, 10)->text() == "mH") { if (6.28*10*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 1) { frame.data[5] = 0x0c; } else if (6.28*10*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 10) { frame.data[5] = 0x2c; } else { frame.data[5] = 0x3c; } } else { frame.data[5] = 0x0c; } } else if (ui->Com_fre->currentText() == "100") { if (ui->indlTab->item(i, 10)->text() == "mH") { if (6.28*0.1*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 1) { frame.data[5] = 0x09; } else if (6.28*0.1*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 10) { frame.data[5] = 0x29; } else { frame.data[5] = 0x39; } } else { frame.data[5] = 0x09; } } else if (ui->Com_fre->currentText() == "120") { if (ui->indlTab->item(i, 10)->text() == "mH") { if (6.28*0.12*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 1) { frame.data[5] = 0x0a; } else if (6.28*0.12*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 10) { frame.data[5] = 0x2a; } else { frame.data[5] = 0x3a; } } else { frame.data[5] = 0x0a; } } frame.data[5] = frame.data[5] & 0XE7; frame.data[5] = frame.data[5] | Indl_Volt ; qDebug() << "frame.data[5]------------------" << frame.data[5]; int connetct; // frame.data[6] 连接方式 电压增益 电流增益 if (ui->Com_connetct->currentText() == QString(tr("串联"))) { connetct = 0x00; } else { connetct = 0x40; } if (ui->indlTab->item(i, 10)->text() == "mH") { frame.data[6] = (int)(connetct|0x09); } else { if (ui->indlTab->item(i, 4)->text().toDouble() < 500) { frame.data[6] = (int)(connetct|0x0f); } else { frame.data[6] = (int)(connetct|0x09); } } qDebug() << "frame.data[6]" << frame.data[6]; if (i >= 8) { INDL_TestItemsH = INDL_TestItemsH + (1 << (i-8)); // 高字节 } else { INDL_TestItemsL = INDL_TestItemsL + (1 << i); // 低字节 } INDL_TestNumber++; // 测试总数 canSend(frame); usleep(1000); usleep(1000); usleep(1000); usleep(1000); usleep(1000); usleep(1000); } } /****************************************************************************** * version: 1.0 * author: sl * date: 2015.12.30 * brief: 保存 INDL 配置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Data_Save() { int i; Copy_INDL_List.replace(0, ui->INDL_time->text()); Copy_INDL_List.replace(1, ui->INDL_balance->text()); Copy_INDL_List.replace(2, QString::number(ui->Com_fre->currentIndex())); Copy_INDL_List.replace(3, QString::number(ui->Com_connetct->currentIndex())); Copy_INDL_List.replace(4, ui->INDL_Max->text()); Copy_INDL_List.replace(5, ui->INDL_Min->text()); Copy_INDL_List.replace(6, QString::number(ui->Com_test->currentIndex())); Copy_INDL_List.replace(7, ui->Q_balance->text()); Copy_INDL_List.replace(8,QString::number(ui->Com_volt->currentIndex())); for (i = 0; i < 8; i++) { Copy_INDL_List.replace(INDL_init_Number + 20*i + 0, ui->indlTab->item(i, 1)->text()); // 端子号 Copy_INDL_List.replace(INDL_init_Number + 20*i + 1, ui->indlTab->item(i, 2)->text()); Copy_INDL_List.replace(INDL_init_Number + 20*i + 2, ui->indlTab->item(i, 3)->text()); // 电感上限 下限 Copy_INDL_List.replace(INDL_init_Number + 20*i + 3, ui->indlTab->item(i, 4)->text()); Copy_INDL_List.replace(INDL_init_Number + 20*i + 4, ui->indlTab->item(i, 5)->text()); // Q值上限 下限 Copy_INDL_List.replace(INDL_init_Number + 20*i + 5, ui->indlTab->item(i, 6)->text()); Copy_INDL_List.replace(INDL_init_Number + 20*i + 6, ui->indlTab->item(i, 7)->text()); // 标准电感 Copy_INDL_List.replace(INDL_init_Number + 20*i + 9, ui->indlTab->item(i, 8)->text()); // 补偿 Copy_INDL_List.replace(INDL_init_Number + 20*i + 10, ui->indlTab->item(i, 9)->text()); // 补偿 Copy_INDL_List.replace(INDL_init_Number + 20*i + 8, \ QString::number(Box_INDL_Grade_List.at(i)->checkState())); } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.5.19 * brief: 设置警告弹出框 ******************************************************************************/ void Widget_INDL::Pri_Pwr_WMessage(QString Waring_Text) { QMessageBox *message = new QMessageBox(this); message->setWindowFlags(Qt::FramelessWindowHint); message->setStyleSheet\ ("QMessageBox{border: gray;border-radius: 10px;"\ "padding:2px 4px;background-color: gray;}"); message->setText("\n"+Waring_Text+"\n"); message->addButton(QMessageBox::Ok)->setStyleSheet\ ("height:39px;width:75px;border:5px groove;border:none;"\ "border-radius:10px;padding:2px 4px;"); message->setButtonText(QMessageBox::Ok, QString(tr("确 定"))); message->setIcon(QMessageBox::Warning); message->exec(); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: Conf 配置 INDL 界面 ******************************************************************************/ void Widget_INDL::Pub_Conf_Set_INDL(QString str, int value, int flag) { switch (flag) { case 1: Pri_INDL_Init(); break; case 2: Pri_INDL_Data_Save(); break; case 3: Pri_INDL_Test_Parameter(); break; case 4: Pri_INDL_Test_Start(); break; case 6: Pri_INDL_Default_value(str); break; case 7: Pri_INDL_Auto_Set(str, value); break; case 8: Pri_INDL_Quiky_Test_Parameter(); case 100: if (str.toInt()) { Init_Channel_6 = true; } else { Init_Channel_6 = false; } break; default: break; } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 单位自动设定 ******************************************************************************/ void Widget_INDL::Pri_INDL_Auto_Set(QString str, int value) { if ((str.toDouble() > 1000) && (str.toDouble() < 10000000)) { // 单位设置 mH if (ui->indlTab->item(value-1, 10)->text() != "mH") { on_indlTab_cellClicked(value-1, 10); } ui->indlTab->item(value - 1, 7)->setText(QString::number(str.toDouble()/1000)); on_Button_Auto_clicked(); } else if ((str.toDouble() < 1000)&&(str.toDouble() > 0)) { // 单位设置 uH if (ui->indlTab->item(value-1, 10)->text() != "uH") { on_indlTab_cellClicked(value-1, 10); } ui->indlTab->item(value-1, 7)->setText(str); on_Button_Auto_clicked(); } else { // } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 测试启动 ******************************************************************************/ void Widget_INDL::Pri_INDL_Test_Start() { frame.can_id = 0x26; frame.can_dlc = 0x08; frame.data[0] = 0x01; frame.data[1] = 0x00; frame.data[2] = 0x00; frame.data[3] = 0x13; frame.data[4] = INDL_TestItemsH; frame.data[5] = INDL_TestItemsL; frame.data[6] = 0x07; frame.data[7] = 0x08; canSend(frame); usleep(500); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感默认设置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Default_value(QString number) { int i; for (i = 0; i < 8; i++) { Box_INDL_Grade_List[i]->setChecked(false); } for (i = 0; i < number.size()/2; i++) { ui->indlTab->item(i, 1)->setText(number.mid(i*2, 1)); ui->indlTab->item(i, 2)->setText(number.mid(i*2 + 1, 1)); Box_INDL_Grade_List[i]->setChecked(true); } ui->INDL_time->setValue(1); ui->Com_fre->setCurrentIndex(2); ui->Com_connetct->setCurrentIndex(0); ui->Com_test->setCurrentIndex(0); ui->INDL_Min->setValue(5); ui->INDL_Max->setValue(5); // ui->INDL_balance->setValue(0); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: 端点的选择 ******************************************************************************/ void Widget_INDL::join_buttonJudge(int id) { ui->dockWidget->hide(); INDL_Labelhide->hide(); if (id != 9) { ui->indlTab->currentItem()->setText(QString::number(id)); } } void Widget_INDL::INDL_NetData(QStringList list, QString str) { INDL_Init_Flag = true; int i; if (str == QString(tr("test"))) { for (i = 0; i < 8; i++) { if (list.at(i).toInt() != 0) { Box_INDL_Grade_List[i]->setChecked(true); } else { Box_INDL_Grade_List[i]->setChecked(false); } } } else if (str == QString(tr("port1"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 1)->setText(list.at(i)); } } else if (str == QString(tr("port2"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 2)->setText(list.at(i)); } } else if (str == QString(tr("unit"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 10)->setText(INDL_Unit[list.at(i).toInt()]); Copy_INDL_List.replace(37+20*i, list.at(i)); } } else if (str == QString(tr("min"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 3)->setText(list.at(i)); } } else if (str == QString(tr("max"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 4)->setText(list.at(i)); } } else if (str == QString(tr("qmin"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 5)->setText(list.at(i)); } } else if (str == QString(tr("qmax"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 6)->setText(list.at(i)); } } else if (str == QString(tr("std"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 7)->setText(list.at(i)); } } else if (str == QString(tr("mode"))) { ui->INDL_time->setValue(list.at(0).toDouble()); ui->Com_fre->setCurrentIndex(list.at(1).toInt()); ui->Com_connetct->setCurrentIndex(list.at(2).toInt()); ui->Com_test->setCurrentIndex(list.at(3).toInt()); } else if (str == QString(tr("noun"))) { ui->INDL_balance->setValue(list.at(0).toDouble()); } else if (str == QString(tr("wire_comp1"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 8)->setText(list.at(i)); } } else if (str == QString(tr("wire_comp2"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 9)->setText(list.at(i)); } Pri_INDL_Data_Save(); } else { // } INDL_Init_Flag = false; } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感界面单击 ******************************************************************************/ void Widget_INDL::on_indlTab_cellClicked(int row, int column) { int number_column; ui->Key_1->show(); ui->Key_2->show(); ui->Key_3->show(); ui->Key_4->show(); ui->Key_5->show(); ui->Key_6->show(); ui->Key_7->show(); ui->Key_8->show(); if (Init_Channel_6) { ui->Key_7->hide(); ui->Key_8->hide(); } else { } if (column == 1 || column == 2) { if(column==1) { number_column = ui->indlTab->item(row,2)->text().toInt(); if ((number_column==1) || (number_column==4) || (number_column==7)) { ui->Key_1->hide(); ui->Key_4->hide(); ui->Key_7->hide(); } else if((number_column==2) || (number_column==5) || (number_column==8)) { ui->Key_2->hide(); ui->Key_5->hide(); ui->Key_8->hide(); } else if((number_column==3) || (number_column==6)) { ui->Key_3->hide(); ui->Key_6->hide(); } } else if(column==2) { number_column = ui->indlTab->item(row,1)->text().toInt(); if((number_column==1)||(number_column==4)||(number_column==7)) { ui->Key_1->hide(); ui->Key_4->hide(); ui->Key_7->hide(); } else if((number_column==2)||(number_column==5)||(number_column==8)) { ui->Key_2->hide(); ui->Key_5->hide(); ui->Key_8->hide(); } else if((number_column==3)||(number_column==6)) { ui->Key_3->hide(); ui->Key_6->hide(); } } else { // } INDL_Labelhide->show(); ui->dockWidget->show(); ui->dockWidget->raise(); } else if (column == 10) { INDL_Init_Flag = true; int indlId = (Copy_INDL_List.at(INDL_init_Number + 20*row + 7).toInt() \ + 1)%INDL_Unit.size(); Copy_INDL_List.replace(INDL_init_Number + 20*row + 7, QString::number(indlId)); QTableWidgetItem *UnitItem = new QTableWidgetItem(); // INDL_Unit[indlId] UnitItem->setTextAlignment(Qt::AlignCenter); UnitItem->setText(INDL_Unit[Copy_INDL_List.at(INDL_init_Number+20*row+7).toInt()]); UnitItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(row, 10, UnitItem); if (indlId == 0) { // uH ui->indlTab->item(row, 7)->setText("200.0"); ui->indlTab->item(row, 4)->setText("300.0"); ui->indlTab->item(row, 3)->setText("100.0"); } else if (indlId == 1) { // mH ui->indlTab->item(row, 7)->setText("200.0"); ui->indlTab->item(row, 4)->setText("300.0"); ui->indlTab->item(row, 3)->setText("100.0"); } else { // } // else if (indlId == 2) // H // { // ui->indlTab->item(row, 7)->setText("2.000"); // ui->indlTab->item(row, 4)->setText("3.000"); // ui->indlTab->item(row, 3)->setText("1.000"); // } INDL_Init_Flag = false; } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 输入完成规范设置 ******************************************************************************/ void Widget_INDL::on_indlTab_cellChanged(int row, int column) { QString str; int i, After_Point = 0; if (INDL_Init_Flag) { return; } INDL_Init_Flag = true; if ((column == 3) || (column == 4) || (column == 5) || \ (column == 6) || (column == 7) || (column == 8) || (column == 9)) { str = ui->indlTab->item(row, column)->text(); if (str == NULL) { ui->indlTab->item(row, column)->setText("0"); } for (i = 0; i < str.length(); i++) { // 判断输入是" 0-9 . " if (((str[i] >= '0') && (str[i] <= '9')) || \ (str[i] == '.') || (str[i] == '-')) { // } else { ui->indlTab->item(row, column)->setText("0"); break; } if (str[i] == '.') { // 判断是否规范 After_Point = str.length()-i-1; if ((i == 0)) { ui->indlTab->item(row, column)->setText("0"); } if (i == (str.length()-1)) { ui->indlTab->item(row, column)->setText(ui->indlTab->item\ (row, column)->text().left(i)); } } } if ((column == 3) || (column == 4) || (column == 7) || (column == 9)) { if (ui->indlTab->item(row, 10)->text() == "uH") { // 单位是uH if (ui->indlTab->item(row, column)->text().toDouble() < 1000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 1)); } else { ui->indlTab->item(row, column)->setText("999.9"); } } if (ui->indlTab->item(row, 10)->text() == "mH") { // 单位是mH if (ui->indlTab->item(row, column)->text().toDouble() < 10) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 3)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 100) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 2)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 1000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 1)); } else if (ui->indlTab->item(row, column)->text().toDouble() <= 10000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 0)); } else { ui->indlTab->item(row, column)->setText("10000"); } } } if ((column == 5) || (column == 6)) { if (ui->indlTab->item(row, column)->text().toDouble() == 0) { ui->indlTab->item(row, column)->setText("0.000"); } else if (ui->indlTab->item(row, column)->text().toDouble() < 10) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 3)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 100) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 2)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 1000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 1)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 10000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 0)); } else { ui->indlTab->item(row, column)->setText("9999"); } } if ((column == 3) || (column == 4)) { if ((ui->indlTab->item(row, 3)->text().toDouble()) > \ (ui->indlTab->item(row, 4)->text().toDouble())) { ui->indlTab->item(row, 3)->setText("0.0"); } } if ((column == 5) || (column == 6)) { if ((ui->indlTab->item(row, 5)->text().toDouble()) > \ (ui->indlTab->item(row, 6)->text().toDouble())) { ui->indlTab->item(row, 5)->setText("0.000"); } } if ((row == 0) && (column == 8)) { for (i = 1; i <= 7; i++) { ui->indlTab->item(i, column)->setText(ui->indlTab->item(0, column)->text()); } } // if ((row == 0) && (column == 9)) { // for (i = 1; i <= 7; i++) { // ui->indlTab->item(i, column)->setText(ui->indlTab->item(0, column)->text()); // } // } } INDL_Init_Flag = false; } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感自动计算 ******************************************************************************/ void Widget_INDL::on_Button_Auto_clicked() { int i; INDL_Init_Flag = true; for (i = 0; i < 8; i++) { // 电感测试项目 8项 if (Box_INDL_Grade_List[i]->checkState() != 2) { continue; } if (ui->indlTab->item(i, 10)->text() == "uH") { if (ui->indlTab->item(i, 7)->text().toDouble()*(100 + \ ui->INDL_Min->text().toInt())/100 > 1000) { ui->indlTab->item(i, 4)->setText("999.9"); } else { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble()*(100 + \ ui->INDL_Min->text().toInt())/100, 'f', 1)); } ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble()*(100 - \ ui->INDL_Max->text().toInt())/100, 'f', 1)); } else if (ui->indlTab->item(i, 10)->text() == "mH") { if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100 + ui->INDL_Min->text().toInt())/100 < 10) { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100, 'f', 3)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100 < 100) { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100, 'f', 2)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100 < 1000) { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100, 'f', 1)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100 <= 10000) { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100, 'f', 0)); } else { ui->indlTab->item(i, 4)->setText("10000"); } if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Min->text().toInt())/100 < 10) { ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Max->text().toInt())/100, 'f', 3)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Min->text().toInt())/100 < 100) { ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Max->text().toInt())/100, 'f', 2)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Min->text().toInt())/100 < 1000) { ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Max->text().toInt())/100, 'f', 1)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100- ui->INDL_Min->text().toInt())/100 <= 10000) { ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Max->text().toInt())/100, 'f', 0)); } else { ui->indlTab->item(i, 3)->setText("10000"); } } else { // } } INDL_Init_Flag = false; } void Widget_INDL::on_INDL_Min_editingFinished() { ui->INDL_Max->setValue(ui->INDL_Min->value()); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.5.19 * brief: 设置警告弹出框 电感 ******************************************************************************/ void Widget_INDL::Pri_INDL_WMessage(QString Waring_Text) { QMessageBox message; message.setWindowFlags(Qt::FramelessWindowHint); message.setStyleSheet\ ("QMessageBox{border: gray;border-radius: 10px;"\ "padding:2px 4px;background-color: gray;}"); message.setText("\n"+Waring_Text+"\n"); message.addButton(QMessageBox::Ok)->setStyleSheet\ ("height:39px;width:75px;border:5px groove;"\ "border:none;border-radius:10px;padding:2px 4px;"); message.setButtonText(QMessageBox::Ok, QString(tr("确 定"))); message.setIcon(QMessageBox::Warning); message.exec(); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感通道清零 ******************************************************************************/ void Widget_INDL::on_Button_Comp_clicked() { QMessageBox message; message.setWindowFlags(Qt::FramelessWindowHint); message.setStyleSheet\ ("QMessageBox{border:3px groove gray;}background-color: rgb(209, 209, 157);"); message.setText(tr(" 请将清零的端子短接 \n 然后继续操作 ")); message.addButton(QMessageBox::Ok)->setStyleSheet\ ("border:none;height:30px;width:65px;border:5px groove gray;"\ "border-radius:10px;padding:2px 4px;"); message.addButton(QMessageBox::Cancel)->setStyleSheet\ ("border:none;height:30px;width:65px;border:5px groove gray;"\ "border-radius:10px;padding:2px 4px;"); message.setButtonText(QMessageBox::Ok, QString(tr("确 定"))); message.setButtonText(QMessageBox::Cancel, QString(tr("取 消"))); message.setIcon(QMessageBox::Warning); int ret = message.exec(); if (ret == QMessageBox::Ok) { Pri_INDL_Calibration_clear(); Lable_Display(); } if (ret == QMessageBox::Cancel) { // } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感通道清零,下发参数 ******************************************************************************/ void Widget_INDL::Pri_INDL_Calibration_clear() { int i; int INDL_Zero_TestItemsL = 0; for (i = 0; i < 8; i++) { if (Box_INDL_Grade_List.at(i)->checkState() != 2) { continue; } frame.can_id = 0x26; frame.can_dlc = 0x07; frame.data[0] = 0x03; frame.data[1] = i; frame.data[2] = ui->indlTab->item(i, 1)->text().toInt(); // 抽头 frame.data[3] = ui->indlTab->item(i, 2)->text().toInt(); frame.data[4] = 0x01; if (ui->Com_fre->currentText() == "1K") { // frame.data[5] 频率 电压 档位 frame.data[5] = 0x0b; } else { frame.data[5] = 0x0c; } int connetct; // frame.data[6] 连接方式 电压增益 电流增益 if (ui->Com_connetct->currentText() == QString(tr("串联"))) { connetct = 0x00; } else { connetct = 0x40; } if (ui->indlTab->item(i, 10)->text() == "mH") { frame.data[6] = (int)(connetct|0x09); } else { if (ui->indlTab->item(i, 4)->text().toDouble() < 500) { frame.data[6] = (int)(connetct|0x0f); } else { frame.data[6] = (int)(connetct|0x09); } } INDL_Zero_TestItemsL = 1 << i; // 低字节 canSend(frame); usleep(500); break; // 勾选第一个进行 } if (INDL_Zero_TestItemsL != 0) { frame.can_id = 0x26; frame.can_dlc = 0x08; frame.data[0] = 0x01; frame.data[1] = 0x00; frame.data[2] = 0x01; frame.data[3] = 0x13; frame.data[4] = 0x00; frame.data[5] = INDL_Zero_TestItemsL; // 低字节 frame.data[6] = 0x07; frame.data[7] = 0x08; canSend(frame); usleep(500); } } QStringList Widget_INDL::INDL_Test_Param() { QString str; QStringList strSql; QStringList strParam, strTest; strTest.clear(); strParam.clear(); QStringList indl_unit; indl_unit.clear(); indl_unit << "u" << "m"; // << "H" for (int j = 0; j < 8; j++) { if (Box_INDL_Grade_List[j]->checkState() != 2) { // 电感 continue; } if (Copy_INDL_List[7] != "0.0") { str = QString(tr("电感")) + Copy_INDL_List.at(INDL_init_Number+20*j+0) + "-" \ + Copy_INDL_List.at(INDL_init_Number+20*j+1); // 电参 strTest.append(str); str.clear(); // indl_unit[Copy_INDL_List.at(INDL_init_Number+20*j+7).toInt()] + str = Copy_INDL_List.at(INDL_init_Number+20*j+2) + "-" + \ Copy_INDL_List.at(INDL_init_Number+20*j+3) + \ indl_unit[Copy_INDL_List.at(INDL_init_Number+20*j+7).toInt()] +", Q-"; str += Copy_INDL_List.at(INDL_init_Number+20*j+4) + "-" + \ Copy_INDL_List.at(INDL_init_Number+20*j+5); strParam.append(str); str.clear(); strSql.append(tr("电感")); } else { str = QString(tr("电感"))+ Copy_INDL_List.at(INDL_init_Number+20*j+0) + "-" + \ Copy_INDL_List.at(INDL_init_Number+20*j+1); // 电参 strTest.append(str); str.clear(); str = Copy_INDL_List.at(INDL_init_Number+20*j+2) + \ indl_unit[Copy_INDL_List.at(INDL_init_Number+20*j+7).toInt()] + "-" + \ Copy_INDL_List.at(INDL_init_Number+20*j+3) + \ indl_unit[Copy_INDL_List.at(INDL_init_Number+20*j+7).toInt()]; strParam.append(str); str.clear(); strSql.append(tr("电感")); } } if ((Copy_INDL_List[1] != "0.0") && (INDL_TestNumber >= 3)) { strTest.append(QString(tr("电感"))); strParam.append(QString(tr("不平衡度 ")) + Copy_INDL_List[1] + "%"); strSql.append(tr("电感")); } // -将(-电感-)修改为(电感) if ((Copy_INDL_List[7].toDouble() != 0.0)&&(INDL_TestNumber >= 3)) { strTest.append(QString(tr("Q值"))); strParam.append(QString(tr("不平衡度 ")) + Copy_INDL_List[7] + "%"); strSql.append(tr("电感")); } QStringList Back_List; Back_List.append(QString::number(strTest.size())); Back_List.append(QString::number(strParam.size())); Back_List.append(QString::number(strSql.size())); Back_List.append(strTest); Back_List.append(strParam); Back_List.append(strSql); return Back_List; }
41.782908
94
0.476619
Bluce-Song
c15610ad4f2b4e825c0d0a2764b50718b4973b32
7,560
cpp
C++
logview/mainwindow.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
8
2015-11-16T19:15:55.000Z
2021-02-17T23:58:33.000Z
logview/mainwindow.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
5
2015-11-12T00:19:59.000Z
2020-03-23T10:18:19.000Z
logview/mainwindow.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
11
2015-03-15T23:02:48.000Z
2021-09-05T14:17:13.000Z
/************************************************************************************ * EMStudio - Open Source ECU tuning software * * Copyright (C) 2020 Michael Carpenter (malcom2073@gmail.com) * * * * This file is a part of EMStudio is licensed MIT as * * defined in LICENSE.md at the top level of this repository * ************************************************************************************/ #include <QDebug> #include <QVBoxLayout> #include <QCheckBox> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include "mainwindow.h" #include "ui_mainwindow.h" #include "egraph.h" #include "qgraph.h" #include "graphview.h" #include "aboutdialog.h" #include "scatterplotview.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_progressDialog=0; // mapView = 0; connect(ui->actionOpen_Megasquirt_Log,SIGNAL(triggered()),this,SLOT(loadMegasquirtLog())); connect(ui->actionOpen_LibreEMS_Log,SIGNAL(triggered()),this,SLOT(loadLibreLog())); connect(ui->actionOpen_Embedded_Lockers_Log,SIGNAL(triggered()),this,SLOT(loadEBLLog())); connect(ui->actionClose_Log,SIGNAL(triggered()),this,SLOT(fileCloseClicked())); connect(ui->actionQuit,SIGNAL(triggered()),this,SLOT(fileQuitClicked())); connect(ui->actionAbout,SIGNAL(triggered()),this,SLOT(aboutMenuClicked())); connect(ui->actionExport_as_CSV,SIGNAL(triggered()),this,SLOT(exportCsvClicked())); //graph = new QGraph(this); //this->setCentralWidget(graph); //graph->setGeometry(100,100,800,600); //graph->show(); //dataSelectionScreen = new DataSelectionScreen(); //connect(dataSelectionScreen,SIGNAL(itemEnabled(QString)),this,SLOT(itemEnabled(QString))); //connect(dataSelectionScreen,SIGNAL(itemDisabled(QString)),this,SLOT(itemDisabled(QString))); //connect(ui->actionSelect_Dialog,SIGNAL(triggered()),this,SLOT(selectDialogClicked())); //dataSelectionScreen->setVisible(false); this->setAttribute(Qt::WA_DeleteOnClose,true); this->menuBar()->setNativeMenuBar(false); // connect(ui->addGraphButton,SIGNAL(clicked()),this,SLOT(addGraphButtonClicked())); // connect(ui->addMapButton,SIGNAL(clicked()),this,SLOT(addMapButtonClicked())); m_logLoaded = false; } void MainWindow::addGraphButtonClicked() { if (!m_logLoaded) { QMessageBox::information(0,"Error","Please load a log first"); return; } GraphView *view = new GraphView(); view->show(); view->passData(&variantList,m_logTypes); m_graphViewList.append(view); } void MainWindow::addMapButtonClicked() { ScatterPlotView *view = new ScatterPlotView(); view->setData(&variantList,m_logTypes); view->show(); return; if (!m_logLoaded) { QMessageBox::information(0,"Error","Please load a log first"); return; } MapView *mapView = new MapView(); mapView->show(); mapView->setGeometry(100,100,800,600); mapView->setData(&variantList,m_logTypes); m_mapViewList.append(mapView); } void MainWindow::logProgress(quint64 pos,quint64 total) { m_progressDialog->setValue(100.0 * ((double)pos / (double)total)); } MainWindow::~MainWindow() { //delete ui; //delete dataSelectionScreen; if (m_progressDialog) { delete m_progressDialog; } if (m_logLoaded) { //m_progressDialog = new QProgressDialog("Closing...","Cancel",0,100); //m_progressDialog->show(); //QApplication::instance()->processEvents(); //fileCloseClicked(); } } void MainWindow::payloadDecoded(QVariantMap map) { if (variantList.size() == 0) { //First incoming map. } variantList.append(map); } void MainWindow::threadDone() { m_progressDialog->hide(); delete m_progressDialog; m_progressDialog = 0; qDebug() << variantList.size() << "records loaded"; m_logLoaded = true; //sender()->deleteLater(); FEMSParser *parser = qobject_cast<FEMSParser*>(sender()); if (parser) { //It's a FEMS parser that sent this m_logTypes = parser->getLogTypes(); } } void MainWindow::loadMegasquirtLog () { QString filename = QFileDialog::getOpenFileName(this,"Select log file to open"); if (filename == "") { return; } fileCloseClicked(); MSParser *parser = new MSParser(this); connect(parser,SIGNAL(done()),this,SLOT(threadDone())); connect(parser,SIGNAL(loadProgress(quint64,quint64)),this,SLOT(logProgress(quint64,quint64))); connect(parser,SIGNAL(payloadDecoded(QVariantMap)),this,SLOT(payloadDecoded(QVariantMap))); connect(parser,SIGNAL(logData(QString,QString)),this,SLOT(logData(QString,QString))); m_progressDialog = new QProgressDialog("Loading file....","Cancel",0,100); m_progressDialog->show(); parser->loadLog(filename); } void MainWindow::loadLibreLog() { QString filename = QFileDialog::getOpenFileName(this,"Select log file to open",QString(),QString(),0,QFileDialog::DontUseCustomDirectoryIcons); if (filename == "") { return; } fileCloseClicked(); FEMSParser *parser = new FEMSParser(this); connect(parser,SIGNAL(done()),this,SLOT(threadDone())); connect(parser,SIGNAL(loadProgress(quint64,quint64)),this,SLOT(logProgress(quint64,quint64))); connect(parser,SIGNAL(payloadDecoded(QVariantMap)),this,SLOT(payloadDecoded(QVariantMap))); connect(parser,SIGNAL(logData(QString,QString)),this,SLOT(logData(QString,QString))); m_progressDialog = new QProgressDialog("Loading file....","Cancel",0,100); m_progressDialog->show(); parser->loadLog(filename); } void MainWindow::loadEBLLog() { QString filename = QFileDialog::getOpenFileName(this,"Select log file to open"); if (filename == "") { return; } fileCloseClicked(); EBLParser *parser = new EBLParser(this); connect(parser,SIGNAL(done()),this,SLOT(threadDone())); connect(parser,SIGNAL(loadProgress(quint64,quint64)),this,SLOT(logProgress(quint64,quint64))); connect(parser,SIGNAL(payloadDecoded(QVariantMap)),this,SLOT(payloadDecoded(QVariantMap))); connect(parser,SIGNAL(logData(QString,QString)),this,SLOT(logData(QString,QString))); m_progressDialog = new QProgressDialog("Loading file....","Cancel",0,100); m_progressDialog->show(); parser->loadLog(filename); } void MainWindow::fileCloseClicked() { variantList.clear(); for (int i=0;i<m_mapViewList.size();i++) { delete m_mapViewList.at(i); } m_mapViewList.clear(); for (int i=0;i<m_graphViewList.size();i++) { delete m_graphViewList.at(i); } m_graphViewList.clear(); m_logLoaded = false; } void MainWindow::fileQuitClicked() { this->close(); } void MainWindow::logData(QString key,QString val) { //ui->textBrowser->append(key + ": " + val); } void MainWindow::aboutMenuClicked() { AboutDialog *d = new AboutDialog(this); d->show(); } void MainWindow::exportCsvClicked() { QString filename = QFileDialog::getSaveFileName(this); if (filename == "") { return; } m_csvExporter = new Exporter_Csv(this); connect(m_csvExporter,SIGNAL(progress(int,int)),this,SLOT(exportProgress(int,int))); connect(m_csvExporter,SIGNAL(done()),this,SLOT(exportThreadDone())); m_csvExporter->startExport(filename,m_logTypes,variantList); m_progressDialog = new QProgressDialog("Exporting....","Cancel",0,100,this); m_progressDialog->show(); } void MainWindow::exportProgress(int pos,int total) { m_progressDialog->setValue(100.0 * ((double)pos / (double)total)); } void MainWindow::exportThreadDone() { m_progressDialog->hide(); delete m_progressDialog; m_progressDialog = 0; }
30.731707
144
0.693783
Hayesie88
c15af3d0e38be40e7776de8adf696eb86ee1f657
1,068
cpp
C++
UVa Online Judge/12247.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
1
2022-02-24T12:44:30.000Z
2022-02-24T12:44:30.000Z
UVa Online Judge/12247.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
null
null
null
UVa Online Judge/12247.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; const int INF = 1e9; const long long LLINF = 4e18; const double EPS = 1e-9; int order[6][3] = { 0, 1, 2, 0, 2, 1, 1, 0, 2, 1, 2, 0, 2, 0, 1, 2, 1, 0, }; int used[55]; int f(int P[], int X, int Y) { for (int i = 1; i <= 52; ++ i) { if (!used[i]) { int min = 3; for (int t = 0; t < 6; ++ t) { int count = 0; if (P[order[t][0]] < X) { count ++; } if (P[order[t][1]] < Y) { count ++; } if (P[order[t][2]] < i) { count ++; } if (min > count) { min = count; } } if (min >= 2) { return i; } } } return -1; } int main() { ios::sync_with_stdio(false); int P[3], X, Y; while (~scanf("%d%d%d%d%d",&P[0],&P[1],&P[2],&X,&Y) && P[0]+P[1]+P[2]+X+Y) { for (int i = 1; i <= 52; ++ i) { used[i] = 0; } used[P[0]] = 1; used[P[1]] = 1; used[P[2]] = 1; used[X] = 1; used[Y] = 1; printf("%d\n",f(P, X, Y)); } return 0; }
15.705882
77
0.450375
xiezeju
c15d3e2d6315e3a096157ac58b12433af73bfdda
3,086
cpp
C++
snake.cpp
billlin0904/QSnake
07375173d9597ba3149cba5989c9122e90bb9c44
[ "MIT" ]
null
null
null
snake.cpp
billlin0904/QSnake
07375173d9597ba3149cba5989c9122e90bb9c44
[ "MIT" ]
null
null
null
snake.cpp
billlin0904/QSnake
07375173d9597ba3149cba5989c9122e90bb9c44
[ "MIT" ]
1
2021-01-15T19:44:40.000Z
2021-01-15T19:44:40.000Z
#include <QPainter> #include "gamestage.h" #include "snake.h" Snake::Snake(GameStage *stage) : dir_(Direction::NoMove) , growing_(7) , stage_(stage) { } QPointF Snake::head() const { return head_; } void Snake::setPause(bool pause) { is_pause_ = pause; } QList<QPointF> const & Snake::tail() const { return tail_; } Direction Snake::direction() const noexcept { return dir_; } void Snake::setDirection(Direction dir) noexcept { if (dir_ == Direction::MoveLeft && dir == Direction::MoveRight) { return; } if (dir_ == Direction::MoveRight && dir == Direction::MoveLeft) { return; } if (dir_ == Direction::MoveUp && dir == Direction::MoveDown) { return; } if (dir_ == Direction::MoveDown && dir == Direction::MoveUp) { return; } dir_ = dir; } QRectF Snake::boundingRect() const { auto minX = head_.x(); auto minY = head_.y(); auto maxX = head_.x(); auto maxY = head_.y(); for (auto p : tail_) { maxX = p.x() > maxX ? p.x() : maxX; maxY = p.y() > maxY ? p.y() : maxY; minX = p.x() < minX ? p.x() : minX; minY = p.y() < minY ? p.y() : minY; } const auto tl = mapFromScene(QPointF(minX, minY)); const auto br = mapFromScene(QPointF(maxX, maxY)); return QRectF(tl.x(), tl.y(), br.x() - tl.x() + SNAKE_SIZE, br.y() - tl.y() + SNAKE_SIZE); } QPainterPath Snake::shape() const { QPainterPath path; path.setFillRule(Qt::WindingFill); path.addRect(QRectF(0, 0, SNAKE_SIZE, SNAKE_SIZE)); for (auto p : tail_) { QPointF itemp = mapFromScene(p); path.addRect(QRectF(itemp.x(), itemp.y(), SNAKE_SIZE, SNAKE_SIZE)); } return path; } void Snake::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { painter->fillPath(shape(), Qt::yellow); } void Snake::advance(int step) { if (dir_ == Direction::NoMove) { return; } if (is_pause_) { return; } if (growing_ > 0) { auto tail = head_; tail_ << tail; growing_ -= 1; } else { tail_.removeFirst(); tail_ << head_; } QPointF target; switch (dir_) { case Direction::MoveUp: target = moveUp(); break; case Direction::MoveDown: target = moveDown(); break; case Direction::MoveLeft: target = moveLeft(); break; case Direction::MoveRight: target = moveRight(); break; case Direction::NoMove: break; } head_ = target; setPos(head_); growing_ += stage_->collision(this, target); } QPointF Snake::moveLeft() { QPointF targe = head_; targe.rx() -= 2; return targe; } QPointF Snake::moveRight() { QPointF targe = head_; targe.rx() += 2; return targe; } QPointF Snake::moveUp() { QPointF targe = head_; targe.ry() -= 2; return targe; } QPointF Snake::moveDown() { QPointF targe = head_; targe.ry() += 2; return targe; }
20.711409
83
0.557032
billlin0904
c15e881205eb186e6a6c43d0908ccd95d480c91c
610
cpp
C++
apps/myApps/Doshi_u1212719/BehaviorAlgorithms/BehaviorTree/BT.cpp
wanted28496/AIForGames
8b958452ccf268ecd54990135a7a3dd154cab6d4
[ "MIT" ]
null
null
null
apps/myApps/Doshi_u1212719/BehaviorAlgorithms/BehaviorTree/BT.cpp
wanted28496/AIForGames
8b958452ccf268ecd54990135a7a3dd154cab6d4
[ "MIT" ]
null
null
null
apps/myApps/Doshi_u1212719/BehaviorAlgorithms/BehaviorTree/BT.cpp
wanted28496/AIForGames
8b958452ccf268ecd54990135a7a3dd154cab6d4
[ "MIT" ]
null
null
null
#include "BT.h" #include "BTTick.h" #include "BTAction.h" #include "BTBlackboard.h" BT::BT(unsigned int iNodeID, BTTaskBase * iRootNode, BTBlackboard * iBlackboard) : mNodeID(iNodeID), mRootNode(iRootNode), mBlackboard(iBlackboard) { unsigned int i = 0; SetTask(mRootNode, i); } void BT::SetTask(BTTaskBase * iTask, unsigned int & id) { iTask->SetNodeID(id); id++; auto& children = iTask->GetChildren(); for (int i = 0; i < children.size(); i++) { SetTask(children[i], id); } } void BT::Update(float dt) { BTTick* tick = new BTTick(this, mBlackboard); mRootNode->Run(tick); } BT::~BT() { }
17.428571
147
0.668852
wanted28496
c15fcc75e874ce6260fe6ffcba76d171fe94309c
43,778
cpp
C++
Samples/Win7Samples/winbase/rdc/client/RdcSdkTestClient.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/winbase/rdc/client/RdcSdkTestClient.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/winbase/rdc/client/RdcSdkTestClient.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "stdafx.h" #include <new> #include "msrdc.h" #include <string> #include <memory> #include <RdcSdkTestServer.h> #include "smartFileHandle.h" #include "sampleUnknownImpl.h" #include "rdcSdkTestClient.h" #include "simplefilenametable.h" using namespace std; // Size of the buffer used to copy data from source or seed file to the target file. static const size_t g_InputBufferSize = 8192; static const wchar_t g_similarityTableName[] = L"RdcSampleTraitsTable"; static const wchar_t g_filenameTableName[] = L"RdcSampleFilenameTable"; static const unsigned g_maxResults = 10; static BOOL g_deleteSignatures = TRUE; static BOOL g_reuse = FALSE; static BOOL g_createtarget = TRUE; static BOOL g_saveneeds = FALSE; static BOOL g_similarity = FALSE; static ULONG g_recursionDepth = 0; static ULONG g_horizonSize1 = MSRDC_DEFAULT_HORIZONSIZE_1; static ULONG g_horizonSizeN = MSRDC_DEFAULT_HORIZONSIZE_N; static ULONG g_hashWindowSize1 = MSRDC_DEFAULT_HASHWINDOWSIZE_1; static ULONG g_hashWindowSizeN = MSRDC_DEFAULT_HASHWINDOWSIZE_N; /*+--------------------------------------------------------------------------- Class: LocalRdcFileReader Purpose: Provide the IRdcFileReader interface necessary for the MSRDC comparator object. This class simply forwards the call on to the native interfaces. Notes: ----------------------------------------------------------------------------*/ class LocalRdcFileReader : public IRdcFileReader { public: LocalRdcFileReader() : m_Handle ( INVALID_HANDLE_VALUE ) {} virtual ~LocalRdcFileReader() {} void Set ( HANDLE h ) { RDCAssert ( !IsValid() ); m_Handle = h; } bool IsValid() const { return m_Handle != 0 && m_Handle != INVALID_HANDLE_VALUE; } STDMETHOD ( GetFileSize ) ( ULONGLONG * fileSize ) { RDCAssert ( IsValid() ); DebugHresult hr = S_OK; *fileSize = 0; LARGE_INTEGER position = {0}; if ( !GetFileSizeEx ( m_Handle, &position ) ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } else { *fileSize = position.QuadPart; } return hr; } STDMETHOD ( Read ) ( ULONGLONG offsetFileStart, ULONG bytesToRead, ULONG * bytesActuallyRead, BYTE * buffer, BOOL * eof ) { RDCAssert ( IsValid() ); DebugHresult hr = S_OK; *bytesActuallyRead = 0; *eof = FALSE; OVERLAPPED overlapped = {0}; overlapped.Offset = static_cast<DWORD> ( offsetFileStart & 0xffffffff ); overlapped.OffsetHigh = static_cast<DWORD> ( offsetFileStart >> 32 ); if ( ReadFile ( m_Handle, buffer, bytesToRead, bytesActuallyRead, &overlapped ) ) { if ( *bytesActuallyRead < bytesToRead ) { // we must be at EOF *eof = TRUE; } } else { *bytesActuallyRead = 0; hr = HRESULT_FROM_WIN32 ( GetLastError() ); } return hr; } STDMETHOD ( GetFilePosition ) ( ULONGLONG * offsetFromStart ) { RDCAssert ( false ); return E_NOTIMPL; } private: HANDLE m_Handle; }; /*+--------------------------------------------------------------------------- Class: MyFileTransferRdcFileReader Purpose: Provide the IRdcFileReader interface necessary for the MSRDC comparator object. This class simply forwards the call on to RdcSdkTestServer for reading the source and seed signatures. An instance of this object is created for each level of signatures to be read. Notes: ----------------------------------------------------------------------------*/ class MyFileTransferRdcFileReader : public IRdcFileReader { public: MyFileTransferRdcFileReader() : m_SignatureLevel ( ( ULONG ) - 1 ) {} virtual ~MyFileTransferRdcFileReader() {} void Set ( ULONG signatureLevel, IRdcFileTransfer *iRdcFileTransfer, RdcFileHandle rdcFileHandle ) { // Only allow a single initialization RDCAssert ( m_SignatureLevel == ( ULONG ) - 1 ); m_SignatureLevel = signatureLevel; m_RdcFileTransfer = iRdcFileTransfer; m_RdcFileHandle = rdcFileHandle; } STDMETHOD ( GetFileSize ) ( ULONGLONG * fileSize ) { // Assert that we have been initialized RDCAssert ( m_SignatureLevel != ( ULONG ) - 1 ); if ( m_SignatureLevel == ( ULONG ) - 1 ) { return E_FAIL; } DebugHresult hr = m_RdcFileTransfer->GetFileSize ( &m_RdcFileHandle, m_SignatureLevel, fileSize ); return hr; } STDMETHOD ( Read ) ( ULONGLONG offsetFileStart, ULONG bytesToRead, ULONG * bytesActuallyRead, BYTE * buffer, BOOL * eof ) { // Assert that we have been initialized RDCAssert ( m_SignatureLevel != ( ULONG ) - 1 ); if ( m_SignatureLevel == ( ULONG ) - 1 ) { return E_FAIL; } *eof = FALSE; DebugHresult hr = m_RdcFileTransfer->ReadData ( &m_RdcFileHandle, m_SignatureLevel, offsetFileStart, bytesToRead, bytesActuallyRead, buffer ); if ( SUCCEEDED ( hr ) ) { if ( *bytesActuallyRead < bytesToRead ) { *eof = TRUE; } } return hr; } STDMETHOD ( GetFilePosition ) ( ULONGLONG * offsetFromStart ) { RDCAssert ( false ); return E_NOTIMPL; } private: ULONG m_SignatureLevel; CComPtr<IRdcFileTransfer> m_RdcFileTransfer; RdcFileHandle m_RdcFileHandle; }; /*+--------------------------------------------------------------------------- Class: SignatureFileInfo Purpose: Used to call into the RdcSdkTestServer and maintain the state information necessary for each open file. In this sample, there are 2 open files: the source and the seed. Notes: ----------------------------------------------------------------------------*/ class SignatureFileInfo { public: SignatureFileInfo() { Clear(); } DebugHresult OpenRemoteFile ( wchar_t const *sourceMachineName, wchar_t const *sourceFileName, ULONG recursionDepth ); DebugHresult OpenLocalFile ( wchar_t const *sourceFileName, ULONG recursionDepth ) { return OpenRemoteFile ( 0, sourceFileName, recursionDepth ); } DebugHresult GetSimilarityData ( SimilarityData *similarityData ) { if ( m_RdcFileTransfer ) { return m_RdcFileTransfer->GetSimilarityData ( similarityData ); } return E_FAIL; } /*---------------------------------------------------------------------------- Name: CreateSignatureFileReader Create a MyFileTransferRdcFileReader() to provide the input to the MSRDC Comparator. Arguments: signatureLevel Which signature level will be read reader The resulting interface. Returns: ----------------------------------------------------------------------------*/ DebugHresult CreateSignatureFileReader ( ULONG signatureLevel, IRdcFileReader **reader ) { DebugHresult hr = S_OK; RDCAssert ( signatureLevel <= MSRDC_MAXIMUM_DEPTH ); *reader = 0; MyFileTransferRdcFileReader *p = new ( std::nothrow ) SampleUnknownImpl<MyFileTransferRdcFileReader, IRdcFileReader>(); if ( p ) { p->Set ( signatureLevel, m_RdcFileTransfer, m_RdcFileHandle ); *reader = p; p->AddRef(); } else { hr = E_OUTOFMEMORY; } return hr; } ULONG getRdcSignatureDepth() const { return m_RdcFileTransferInfo.m_SignatureDepth; } ULONGLONG GetFileSize() const { return m_RdcFileTransferInfo.m_FileSize; } private: wchar_t m_Filename[ MAX_PATH ]; RdcFileTransferInfo m_RdcFileTransferInfo; RdcFileHandle m_RdcFileHandle; CComPtr<IRdcFileTransfer> m_RdcFileTransfer; void Clear() { memset ( m_Filename, 0, sizeof ( m_Filename ) ); memset ( &m_RdcFileTransferInfo, 0, sizeof ( m_RdcFileTransferInfo ) ); memset ( &m_RdcFileHandle, 0, sizeof ( m_RdcFileHandle ) ); } }; /*--------------------------------------------------------------------------- Name: SignatureFileInfo::OpenRemoteFile Connect to RdcSdkTestServer remotely, or locally if the server name is not provided. Arguments: sourceMachineName The remote machine name, or NULL. sourceFileName The filename. Must be of the form C:\fullpath\filename recursionDepth The signature depth to generate. Returns: ----------------------------------------------------------------------------*/ DebugHresult SignatureFileInfo::OpenRemoteFile ( wchar_t const *sourceMachineName, wchar_t const *sourceFileName, ULONG recursionDepth ) { DebugHresult hr = S_OK; if ( wcslen ( sourceFileName ) >= ARRAYSIZE ( m_Filename ) ) { // Path is too long. return E_INVALIDARG; } wcsncpy_s ( m_Filename, ARRAYSIZE ( m_Filename ), sourceFileName, _TRUNCATE ); m_Filename[ ARRAYSIZE ( m_Filename ) - 1 ] = 0; COSERVERINFO serverInfo = { 0, ( LPWSTR ) sourceMachineName, 0, 0 }; MULTI_QI mQI = { &__uuidof ( IRdcFileTransfer ), 0, S_OK }; hr = CoCreateInstanceEx ( __uuidof ( RdcFileTransfer ), 0, sourceMachineName ? CLSCTX_REMOTE_SERVER : ( CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER ), &serverInfo, 1, &mQI ); if ( SUCCEEDED ( hr ) ) { m_RdcFileTransfer.Attach ( ( IRdcFileTransfer* ) mQI.pItf ); m_RdcFileTransferInfo.m_SignatureDepth = recursionDepth; hr = m_RdcFileTransfer->RdcOpenFile ( m_Filename, &m_RdcFileTransferInfo, &m_RdcFileHandle, g_deleteSignatures, g_horizonSize1, g_horizonSizeN, g_hashWindowSize1, g_hashWindowSizeN ); } return hr; } /*---------------------------------------------------------------------------- Name: CopyDataToTarget Copy data from either the source or seed file to the target file. Arguments: fromFile file reader for the source or seed file. fileOffset Offset into the source or seed file. blockLength Length of the block to be copied targetFile Handle to the target file. ----------------------------------------------------------------------------*/ DebugHresult CopyDataToTarget ( IRdcFileReader *fromFile, ULONGLONG fileOffset, ULONGLONG blockLength, HANDLE targetFile ) { DebugHresult hr = S_OK; if ( targetFile == INVALID_HANDLE_VALUE || targetFile == 0 ) { return hr; } // Copy a buffer full of data at a time. BYTE buffer[ g_InputBufferSize ]; BOOL eof = FALSE; while ( blockLength && !eof && SUCCEEDED ( hr ) ) { ULONG length = static_cast<ULONG> ( min ( blockLength, sizeof ( buffer ) ) ); ULONG bytesActuallyRead = 0; hr = fromFile->Read ( fileOffset, length, &bytesActuallyRead, buffer, &eof ); if ( length != bytesActuallyRead ) { printf ( "Read failed x%x, length=%d, bytesActuallyRead=%d\n", hr, length, bytesActuallyRead ); } if ( SUCCEEDED ( hr ) ) { ULONG bytesActuallyWritten = 0; if ( !WriteFile ( targetFile, buffer, bytesActuallyRead, &bytesActuallyWritten, 0 ) ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } if ( bytesActuallyRead != bytesActuallyWritten ) { printf ( "Oops, write failed, error = x%x, bytesActuallyRead=%d, bytesActuallyWritten=%d\n", hr, bytesActuallyRead, bytesActuallyWritten ); } fileOffset += bytesActuallyRead; blockLength -= bytesActuallyRead; RDCAssert ( eof || bytesActuallyRead == length ); } } if ( eof ) { printf ( "FAILED: EOF reached\n" ); } return hr; } void CheckPosition ( ULONGLONG offset, HANDLE file ) { LARGE_INTEGER zero = {0}; LARGE_INTEGER newPos; if ( SetFilePointerEx ( file, zero, &newPos, FILE_CURRENT ) ) { if ( static_cast<ULONGLONG> ( newPos.QuadPart ) != offset ) { printf ( "Target file position incorrect, is %I64d, should be %I64d, diff=%I64d\n", newPos.QuadPart, offset, offset - newPos.QuadPart ); } } } void sPrintTraits ( string &str, const SimilarityData & traits ) { static const int bufferSize = 100; char hexBuffer[ bufferSize ]; str.clear(); for ( int i = 0; i < ARRAYSIZE ( traits.m_Data ); ++i ) { if ( i != 0 ) str.append ( "-" ); sprintf_s ( hexBuffer, ARRAYSIZE ( hexBuffer ), "%02X", traits.m_Data[ i ] ); str.append ( hexBuffer ); } } void MakeSignatureFileName ( ULONG level, wchar_t ( &sigFileName ) [ MAX_PATH ], wchar_t const *sourceFileName ) { RDCAssert ( level <= MSRDC_MAXIMUM_DEPTH ); if ( level > 0 ) { int n = _snwprintf_s ( sigFileName, ARRAYSIZE ( sigFileName ), _TRUNCATE, L"%s_%d.sig", sourceFileName, level ); RDCAssert ( n != -1 ); UNREFERENCED_PARAMETER ( n ); } else { wcsncpy_s ( sigFileName, ARRAYSIZE ( sigFileName ), sourceFileName, _TRUNCATE ); } sigFileName[ ARRAYSIZE ( sigFileName ) - 1 ] = 0; } /*---------------------------------------------------------------------------- Name: CompareFiles Creates and uses an MSRDC Comparator object to compare the given signature files and constructs the target file. On error, the target file should be deleted by the caller. Arguments: seedSignatures file reader for the seed signatures. (Connected to local RdcSdkTestServer) seedFile file reader for the seed file. (Connected to local RdcSdkTestServer) sourceSignatures file reader for the source signatures. (Connected to remote RdcSdkTestServer) sourceFile file reader for the source file. (Connected to remote RdcSdkTestServer) targetFile NT file handle for the target. bytesFromSource bytesFromSeed ----------------------------------------------------------------------------*/ DebugHresult CompareFiles ( IRdcFileReader *seedSignatures, IRdcFileReader *seedFile, IRdcFileReader *sourceSignatures, IRdcFileReader *sourceFile, HANDLE targetFile, HANDLE needsFile, ULONGLONG *bytesFromSource, ULONGLONG *bytesToTarget, ULONGLONG *bytesFromSeed ) { ULONGLONG totalSeedData = 0; ULONGLONG totalSourceData = 0; ULONGLONG totalSourceSignature = 0; ULONGLONG targetOffset = 0; ULONG needsCount = 0; CComQIPtr<IRdcLibrary> rdcLibrary; CComPtr<IRdcComparator> rdcComparator; // Load the MSRDC inproc DebugHresult hr = rdcLibrary.CoCreateInstance ( __uuidof ( RdcLibrary ), 0, CLSCTX_INPROC_SERVER ); if ( SUCCEEDED ( hr ) ) { hr = rdcLibrary->CreateComparator ( seedSignatures, 1000000 /*MSRDC_MINIMUM_COMPAREBUFFER */, &rdcComparator ); } if ( SUCCEEDED ( hr ) ) { RDC_ErrorCode rdc_ErrorCode = RDC_NoError; BOOL eof = false; BOOL eofOutput = false; DebugHresult hr = S_OK; // Buffer for streaming remote signatures into the comparator. BYTE inputBuffer[ g_InputBufferSize ]; RdcNeed needsArray[ 256 ]; RdcBufferPointer inputPointer = {0}; RdcNeedPointer outputPointer = {0}; ULONGLONG signatureFileOffset = 0; while ( SUCCEEDED ( hr ) && !eofOutput ) { // When the inputPointer is empty, (or first time in this loop) // fill it from the source signature file reader. if ( inputPointer.m_Size == inputPointer.m_Used && !eof ) { ULONG bytesActuallyRead = 0; hr = sourceSignatures->Read ( signatureFileOffset, sizeof ( inputBuffer ), &bytesActuallyRead, inputBuffer, &eof ); // eof is set to true when Read() has read the last byte of // the source signatures. We pass this flag along to the // Comparator. The comparitor will never set eofOutput until // after eof has been set. if ( SUCCEEDED ( hr ) ) { inputPointer.m_Data = inputBuffer; inputPointer.m_Size = bytesActuallyRead; inputPointer.m_Used = 0; signatureFileOffset += bytesActuallyRead; totalSourceSignature += bytesActuallyRead; } } // Initialize the output needs array outputPointer.m_Size = ARRAYSIZE ( needsArray ); outputPointer.m_Used = 0; outputPointer.m_Data = needsArray; if ( SUCCEEDED ( hr ) ) { // Do the comparison operation. // This function may not produce needs output every time. // Also, it may not use all available input each time either. // You may call it with any number of input bytes // and output needs array entries. Obviously, it is more // efficient to given it reasonably sized buffers for each. // This sample waits until Process() consumes an entire input // buffer before reading more data from the source signatures file. // Continue calling this function until it sets "eofOutput" to true. hr = rdcComparator->Process ( eof, &eofOutput, &inputPointer, &outputPointer, &rdc_ErrorCode ); } if ( SUCCEEDED ( hr ) ) { // Empty the needs array completely. for ( ULONG i = 0; i < outputPointer.m_Used; ++i ) { switch ( needsArray[ i ].m_BlockType ) { case RDCNEED_SOURCE: totalSourceData += needsArray[ i ].m_BlockLength; hr = CopyDataToTarget ( sourceFile, needsArray[ i ].m_FileOffset, needsArray[ i ].m_BlockLength, targetFile ); break; case RDCNEED_SEED: totalSeedData += needsArray[ i ].m_BlockLength; hr = CopyDataToTarget ( seedFile, needsArray[ i ].m_FileOffset, needsArray[ i ].m_BlockLength, targetFile ); break; default: hr = E_FAIL; } char needsBuffer[ 256 ]; int n = _snprintf_s ( needsBuffer, ARRAYSIZE ( needsBuffer ), ARRAYSIZE ( needsBuffer ), "NEED: length:%12I64d" "\toffset:%12I64d" "\tsource:%12I64d" "\tblock type:%s\n", needsArray[ i ].m_BlockLength, needsArray[ i ].m_FileOffset, targetOffset, needsArray[ i ].m_BlockType == RDCNEED_SOURCE ? "source" : "seed" ); needsBuffer[ ARRAYSIZE ( needsBuffer ) - 1 ] = 0; if ( needsFile != INVALID_HANDLE_VALUE && needsFile != 0 ) { DWORD written; WriteFile ( needsFile, needsBuffer, n, &written, 0 ); } else { fputs ( needsBuffer, stdout ); } targetOffset += needsArray[ i ].m_BlockLength; CheckPosition ( targetOffset, targetFile ); ++needsCount; } } } } if ( FAILED ( hr ) ) { printf ( "Comparison FAILED, error = x%x\n", hr ); } *bytesFromSource = totalSourceData + totalSourceSignature; *bytesToTarget = totalSourceData + totalSeedData; *bytesFromSeed = totalSeedData; printf ( "Compare: Total Seed Bytes: %I64d, Total Source Bytes: %I64d\n", totalSeedData, *bytesFromSource ); return hr; } void openTraitsTable ( CComQIPtr<ISimilarityTraitsTable> &similarityTraitsTable ) { DebugHresult hr; BYTE *securityDescriptor = 0; RdcCreatedTables tableState; hr = similarityTraitsTable.CoCreateInstance ( __uuidof ( SimilarityTraitsTable ) ); similarityTraitsTable->CreateTable ( const_cast<wchar_t*> ( g_similarityTableName ), FALSE, securityDescriptor, &tableState ); string tableStateString; if ( RDCTABLE_New == tableState ) { tableStateString = "new"; } else if ( RDCTABLE_Existing == tableState ) { tableStateString = "existing"; } else { tableStateString = "unknown or invalid"; RDCAssert ( false ); } printf ( "similarity traits table \"%S\" state is: %s\n", g_similarityTableName, tableStateString.c_str() ); } void printSimilarityResults ( FindSimilarFileIndexResults *results, const DWORD &used, SimpleFilenameTable &t ) { printf ( "%u similarity results were found:\n\n", used ); for ( UINT i = 0; i < used; ++i ) { wstring s; t.lookup ( results[ i ].m_FileIndex, s ); printf ( "\t%u traits matches\t\"%S\"\n", results[ i ].m_MatchCount, s.c_str() ); } printf ( "\n", used ); } /*---------------------------------------------------------------------------- Name: Transfer Transfer a file from a remote host to the local machine. Arguments: remoteMachineName remoteFilename localFilename targetFilename ----------------------------------------------------------------------------*/ DebugHresult Transfer ( wchar_t const *remoteMachineName, wchar_t const *remoteFilename, wchar_t const *localFilename, wchar_t const *targetFilename ) { DebugHresult hr = S_OK; SignatureFileInfo remoteFile; // Connect to RDCSDKTestServer on the remote host hr = remoteFile.OpenRemoteFile ( remoteMachineName, remoteFilename, g_recursionDepth ); ULONG remoteDepth = 0; if ( SUCCEEDED ( hr ) ) { remoteDepth = remoteFile.getRdcSignatureDepth(); } SimilarityData sourceTraits; remoteFile.GetSimilarityData ( &sourceTraits ); SignatureFileInfo localFile; CComQIPtr<ISimilarityTraitsTable> similarityTraitsTable; auto_ptr<SimpleFilenameTable> filenameTable; wstring localFilenameStr; if ( g_similarity ) { openTraitsTable ( similarityTraitsTable ); filenameTable.reset ( new SimpleFilenameTable() ); filenameTable->deserialize ( const_cast<wchar_t*> ( g_filenameTableName ) ); FindSimilarFileIndexResults results[ g_maxResults ] = {0}; DWORD used = 0; hr = similarityTraitsTable->FindSimilarFileIndex ( &sourceTraits, MSRDC_MINIMUM_MATCHESREQUIRED, results, ARRAYSIZE ( results ), &used ); if ( used > 0 ) { printSimilarityResults ( results, used, *filenameTable ); filenameTable->lookup ( results[ 0 ].m_FileIndex, localFilenameStr ); printf ( "Using first entry for similarity.\n" ); localFilename = localFilenameStr.c_str(); } else { printf ( "Similarity was requested, but no matches were found.\n" ); } } printf ( "\nseed name is \"%S\"\n", localFilename ); if ( SUCCEEDED ( hr ) ) { // Connect to RDCSDKTestServer on the local host hr = localFile.OpenLocalFile ( localFilename, remoteDepth ); } ULONG localDepth = 0; if ( SUCCEEDED ( hr ) ) { localDepth = localFile.getRdcSignatureDepth(); } SmartFileHandle localSourceSHandle; SmartFileHandle targetFile; wchar_t sourceSigName[ MAX_PATH ] = {0}; wchar_t needsName[ MAX_PATH + 6 ] = {0}; // +".Needs" CComPtr<IRdcFileReader> seedSignatures; CComPtr<IRdcFileReader> sourceSignatures; CComPtr<IRdcFileReader> seedFile; CComPtr<IRdcFileReader> sourceFile; if ( SUCCEEDED ( hr ) ) { hr = remoteFile.CreateSignatureFileReader ( remoteDepth, &sourceSignatures ); } ULONGLONG bytesFromSourceTotal = 0; ULONGLONG bytesToTargetTotal = 0; for ( ULONG i = remoteDepth; i > 0 && SUCCEEDED ( hr ); --i ) { MakeSignatureFileName ( i - 1, sourceSigName, targetFilename ); wcsncpy_s ( needsName, ARRAYSIZE ( needsName ), sourceSigName, _TRUNCATE ); wcscat_s ( needsName, ARRAYSIZE ( needsName ), L".needs" ); if ( g_createtarget || i > 1 ) { // always create target if target is signature file targetFile.Set ( CreateFile ( sourceSigName, GENERIC_WRITE, FILE_SHARE_DELETE, 0, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 ) ); if ( !targetFile.IsValid() ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } } SmartFileHandle needsFile; if ( g_saveneeds ) { // always create target if target is signature file needsFile.Set ( CreateFile ( needsName, GENERIC_WRITE, FILE_SHARE_DELETE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 ) ); if ( !needsFile.IsValid() ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } } if ( SUCCEEDED ( hr ) ) { hr = localFile.CreateSignatureFileReader ( i, &seedSignatures ); } if ( SUCCEEDED ( hr ) ) { hr = localFile.CreateSignatureFileReader ( i - 1, &seedFile ); } if ( SUCCEEDED ( hr ) ) { hr = remoteFile.CreateSignatureFileReader ( i - 1, &sourceFile ); } if ( SUCCEEDED ( hr ) ) { wprintf ( L"\n\n----------\nTransferring: %s\n----------\n\n", sourceSigName ); ULONGLONG bytesFromSource = 0; ULONGLONG bytesToTarget = 0; ULONGLONG bytesFromSeed = 0; hr = CompareFiles ( seedSignatures, seedFile, sourceSignatures, sourceFile, targetFile.GetHandle(), needsFile.GetHandle(), &bytesFromSource, &bytesToTarget, &bytesFromSeed ); bytesFromSourceTotal += bytesFromSource; bytesToTargetTotal += bytesToTarget; if ( targetFile.IsValid() ) { if ( FAILED ( hr ) ) { DeleteFile ( sourceSigName ); } } } targetFile.Close(); localSourceSHandle.Close(); if ( i > 1 ) { localSourceSHandle.Set ( CreateFile ( sourceSigName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ) ); if ( !localSourceSHandle.IsValid() ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } if ( SUCCEEDED ( hr ) ) { sourceSignatures.Release(); LocalRdcFileReader *r = new ( std::nothrow ) SampleUnknownImpl<LocalRdcFileReader, IRdcFileReader>(); r->Set ( localSourceSHandle.GetHandle() ); r->AddRef(); sourceSignatures.Attach ( r ); } } if ( g_deleteSignatures ) { MakeSignatureFileName ( i, sourceSigName, targetFilename ); DeleteFile ( sourceSigName ); } sourceFile.Release(); seedSignatures.Release(); seedFile.Release(); } if ( SUCCEEDED ( hr ) ) { ULONGLONG fileSize = remoteFile.GetFileSize(); double savings = 0; if ( bytesFromSourceTotal > fileSize || fileSize == 0 ) { savings = 0; } else { savings = ( double ) ( fileSize - bytesFromSourceTotal ) / fileSize * 100; } printf ( "\n\n----------------------------------------" ); printf ( "\nTransfer : %I64d bytes from source, file size: %I64d, RDC Savings: %2.2f%%, toTargetTotal=%I64d bytes\n", bytesFromSourceTotal, fileSize, savings, bytesToTargetTotal ); printf ( "\n\n----------------------------------------\n\n" ); } if ( SUCCEEDED ( hr ) ) { string traitsStr; sPrintTraits ( traitsStr, sourceTraits ); printf ( "target trait: %s\n", traitsStr.c_str() ); if ( !similarityTraitsTable ) { openTraitsTable ( similarityTraitsTable ); } SimilarityFileIndexT last; hr = similarityTraitsTable->GetLastIndex ( &last ); hr = similarityTraitsTable->Append ( &sourceTraits, ++last ); hr = similarityTraitsTable->CloseTable ( TRUE ); if ( !filenameTable.get() ) { filenameTable.reset ( new SimpleFilenameTable() ); filenameTable->deserialize ( const_cast<wchar_t*> ( g_filenameTableName ) ); } filenameTable->insert ( last, targetFilename ); filenameTable->serialize ( const_cast<wchar_t*> ( g_filenameTableName ) ); } return hr; } DebugHresult CheckVersion() { CComQIPtr<IRdcLibrary> rdcLibrary; ULONG currentVersion = 0; ULONG minimumCompatibleAppVersion = 0; // Load the MSRDC inproc DebugHresult hr = rdcLibrary.CoCreateInstance ( __uuidof ( RdcLibrary ), 0, CLSCTX_INPROC_SERVER ); if ( SUCCEEDED ( hr ) ) { hr = rdcLibrary->GetRDCVersion ( &currentVersion, &minimumCompatibleAppVersion ); } if ( SUCCEEDED ( hr ) ) { if ( currentVersion < MSRDC_MINIMUM_COMPATIBLE_APP_VERSION ) { printf ( "The library is older (%d.%d) that I can accept (%d.%d)\n", HIWORD ( currentVersion ), LOWORD ( currentVersion ), HIWORD ( MSRDC_MINIMUM_COMPATIBLE_APP_VERSION ), LOWORD ( MSRDC_MINIMUM_COMPATIBLE_APP_VERSION ) ); hr = E_FAIL; } else if ( minimumCompatibleAppVersion > MSRDC_VERSION ) { printf ( "The library is newer (%d.%d) that I can accept (%d.%d)\n", HIWORD ( minimumCompatibleAppVersion ), LOWORD ( minimumCompatibleAppVersion ), HIWORD ( MSRDC_VERSION ), LOWORD ( MSRDC_VERSION ) ); hr = E_FAIL; } } return hr; } void Usage ( int argc, wchar_t * argv[] ) { const wchar_t * p = wcschr ( argv[ 0 ], L'\\' ); if ( p ) { ++p; } else { p = argv[ 0 ]; } char const str[] = "Usage: %ws <optional parameters> -c remoteMachine remoteFile(source) localFile(seed) targetfile\n\n" "\t-k\t\tkeep signature files.\n" // "\t-reuse\t\tkeep re-use signature files.\n" "\t-notarget\tdon't build the target -- compare only\n" "\t-saveneeds\tsave the needs information to targetfile.needs\n" "\t-similarity\tuse similarity to override seed selection\n" "\t-r <depth>\trecursion depth\n" "\t-hs1 <size>\t1st recursion level horizon size min=%d max=%d default=%d\n" "\t-hsn <size>\t2+ recursion level horizon size min=%d max=%d default=%d\n" "\t-hws1 <size>\t1st recursion level hash window size min=%d max=%d default=%d\n" "\t-hwsn <size>\t2+ recursion level hash window size min=%d max=%d default=%d\n"; printf ( str, p, MSRDC_MINIMUM_HORIZONSIZE, MSRDC_MAXIMUM_HORIZONSIZE, MSRDC_DEFAULT_HORIZONSIZE_1, MSRDC_MINIMUM_HORIZONSIZE, MSRDC_MAXIMUM_HORIZONSIZE, MSRDC_DEFAULT_HORIZONSIZE_N, MSRDC_MINIMUM_HASHWINDOWSIZE, MSRDC_MAXIMUM_HASHWINDOWSIZE, MSRDC_DEFAULT_HASHWINDOWSIZE_1, MSRDC_MINIMUM_HASHWINDOWSIZE, MSRDC_MAXIMUM_HASHWINDOWSIZE, MSRDC_DEFAULT_HASHWINDOWSIZE_N ); } int __cdecl wmain ( int argc, wchar_t * argv[] ) { wchar_t const * args[ 4 ]; CoInitWrapper coInit; DebugHresult hr = S_OK; int i; for ( i = 1; i < argc; ++i ) { if ( argv[ i ][ 0 ] != L'-' ) { Usage ( argc, argv ); exit ( 1 ); } else if ( argv[ i ][ 1 ] == L'k' ) { g_deleteSignatures = FALSE; } else if ( _wcsicmp ( &argv[ i ][ 1 ], L"reuse" ) == 0 ) { g_reuse = TRUE; } else if ( _wcsicmp ( &argv[ i ][ 1 ], L"notarget" ) == 0 ) { g_createtarget = FALSE; } else if ( _wcsicmp ( &argv[ i ][ 1 ], L"saveneeds" ) == 0 ) { g_saveneeds = TRUE; } else if ( _wcsicmp ( &argv[ i ][ 1 ], L"similarity" ) == 0 ) { g_similarity = TRUE; } else if ( argv[ i ][ 1 ] == L'c' ) { ++i; break; } else if ( argv[ i ][ 1 ] == L'r' ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_DEPTH ) { printf ( "\n\nRequested recursion depth -- \"%i\" is greater than the maximum MSRDC recursion depth (%i).\n\n", t, MSRDC_MAXIMUM_DEPTH ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_DEPTH ) { printf ( "\nRequested recursion depth -- \"%i\" is less than the minimum MSRDC recursion depth (%i).\n\n", t, MSRDC_MINIMUM_DEPTH ); Usage ( argc, argv ); exit ( 1 ); } else { g_recursionDepth = t; } } else if ( wcscmp ( argv[ i ] + 1, L"hs1" ) == 0 ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_HORIZONSIZE ) { printf ( "\n\nRequested horizon size -- \"%i\" is greater than the maximum MSRDC horizon size (%i).\n\n", t, MSRDC_MAXIMUM_HORIZONSIZE ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_HORIZONSIZE ) { printf ( "\n\nRequested horizon size -- \"%i\" is less than the minimum MSRDC horizon size (%i).\n\n", t, MSRDC_MINIMUM_HORIZONSIZE ); Usage ( argc, argv ); exit ( 1 ); } else { g_horizonSize1 = t; } } else if ( wcscmp ( argv[ i ] + 1, L"hsn" ) == 0 ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_HORIZONSIZE ) { printf ( "\n\nRequested horizon size -- \"%i\" is greater than the maximum MSRDC horizon size (%i).\n\n", t, MSRDC_MAXIMUM_HORIZONSIZE ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_HORIZONSIZE ) { printf ( "\n\nRequested horizon size -- \"%i\" is less than the minimum MSRDC horizon size (%i).\n\n", t, MSRDC_MINIMUM_HORIZONSIZE ); Usage ( argc, argv ); exit ( 1 ); } else { g_horizonSizeN = t; } } else if ( wcscmp ( argv[ i ] + 1, L"hws1" ) == 0 ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_HASHWINDOWSIZE ) { printf ( "\n\nRequested hash window size -- \"%i\" is greater than the maximum MSRDC hash window size (%i).\n\n", t, MSRDC_MAXIMUM_HASHWINDOWSIZE ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_HASHWINDOWSIZE ) { printf ( "\n\nRequested hash window size -- \"%i\" is less than the maximinimummum MSRDC hash window size (%i).\n\n", t, MSRDC_MINIMUM_HASHWINDOWSIZE ); Usage ( argc, argv ); exit ( 1 ); } else { g_hashWindowSize1 = t; } } else if ( wcscmp ( argv[ i ] + 1, L"hwsn" ) == 0 ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_HASHWINDOWSIZE ) { printf ( "\n\nRequested hash window size -- \"%i\" is greater than the maximum MSRDC hash window size (%i).\n\n", t, MSRDC_MAXIMUM_HASHWINDOWSIZE ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_HASHWINDOWSIZE ) { printf ( "\n\nRequested hash window size -- \"%i\" is less than the minimum MSRDC hash window size (%i).\n\n", t, MSRDC_MINIMUM_HASHWINDOWSIZE ); Usage ( argc, argv ); exit ( 1 ); } else { g_hashWindowSizeN = t; } } else { printf ( "\nInvalid parameter: %ws\n\n", argv[ i ] ); Usage ( argc, argv ); exit ( 1 ); } } char *argPurpose [] = {"Remote machine", "Remote file (source)", "Local file (seed)", "Target file"}; int argCount = 0; while ( i < argc ) { args[ argCount++ ] = argv[ i++ ]; } if ( argCount < ARRAYSIZE ( argPurpose ) ) { printf ( "\n%s must be specified.\n\n", argPurpose[ argCount ] ); Usage ( argc, argv ); exit ( 1 ); } hr = coInit.GetHRESULT(); if ( SUCCEEDED ( hr ) ) { hr = CheckVersion(); } if ( SUCCEEDED ( hr ) ) { hr = Transfer ( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] ); } LPVOID lpMsgBuf; FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hr, 0, // Default language ( LPTSTR ) & lpMsgBuf, 0, NULL ); _tprintf ( _T ( "Error code: x%08x :: %s" ), hr, lpMsgBuf ); LocalFree ( lpMsgBuf ); if ( FAILED ( hr ) ) { exit ( 1 ); } return 0; }
33.015083
169
0.49036
windows-development
c16422c107ccc84451d2b236f67c3d92592738ff
1,158
cpp
C++
vislib/src/sys/COMException.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
vislib/src/sys/COMException.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
vislib/src/sys/COMException.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * COMException.cpp * * Copyright (C) 2006 - 2012 by Visualisierungsinstitut Universitaet Stuttgart. * Alle Rechte vorbehalten. */ #include "vislib/sys/COMException.h" /* * vislib::sys::COMException::COMException */ #ifdef _WIN32 vislib::sys::COMException::COMException(const HRESULT hr, const char* file, const int line) : Super(file, line) { _com_error ce(hr); this->setMsg(ce.ErrorMessage()); } #else /* _WIN32 */ vislib::sys::COMException::COMException(const char* file, const int line) : Super("COMException", file, line) { // Nothing to do. } #endif /* _WIN32 */ /* * vislib::sys::COMException::COMException */ vislib::sys::COMException::COMException(const COMException& rhs) : Super(rhs) { // Nothing to do. } /* * vislib::sys::COMException::~COMException */ vislib::sys::COMException::~COMException(void) { // Nothing to do. } /* * vislib::sys::COMException::operator = */ vislib::sys::COMException& vislib::sys::COMException::operator=(const COMException& rhs) { if (this != &rhs) { Super::operator=(rhs); #ifdef _WIN32 this->hr = rhs.hr; #endif /* _WIN32 */ } return *this; }
21.849057
113
0.659758
masrice
c16757cb4d61960300b92eb5ef4bb4dc01c83568
800
hpp
C++
include/x_copy_paste.hpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
include/x_copy_paste.hpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
include/x_copy_paste.hpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
/* Utility functions for easy reading from and writing to the x window system clipboard. Use the external utility `xclip` rather than implemting clipboard capabilities for the X application. This serves 2 purposes. First, avoid the necessity for the caller to implement an x11 application and avoid the complex setup for clipboard capabilities in x window applications. Second, allow access to the clipboard after the calling process terminated. author: andreasl */ #pragma once #include <string> namespace barn { namespace x11 { namespace cp { /*Write the given string to the x window clipboard.*/ void write_to_clipboard(const std::string& str); /*Return a string from the x window clipboard.*/ std::string get_text_from_clipboard(); } // namespace cp } // namespace x11 } // namespace barn
29.62963
100
0.77875
langenhagen
c167f118ba97e7ff21871be25ee3cc62b2574dcf
784
cpp
C++
src/main/cpp/ByteReader.cpp
alexnsouza6/JavaVirtualMachine
d0e1702cc7f68f2a71a6b139326fcd13685e44de
[ "MIT" ]
null
null
null
src/main/cpp/ByteReader.cpp
alexnsouza6/JavaVirtualMachine
d0e1702cc7f68f2a71a6b139326fcd13685e44de
[ "MIT" ]
1
2018-09-24T00:08:56.000Z
2018-09-24T00:08:56.000Z
src/main/cpp/ByteReader.cpp
alexnsouza6/JavaVirtualMachine
d0e1702cc7f68f2a71a6b139326fcd13685e44de
[ "MIT" ]
2
2018-12-09T17:44:49.000Z
2018-12-10T16:41:40.000Z
#ifndef ___BYTEREADER_H___ #define ___BYTEREADER_H___ #define NEUTRAL_BYTE_FOR_OR 0x00; /** * @brief Classe ByteReader. No momento da instanciação define-se qual tipo deseja-se buscar * E assim quando acionado o método byteCatch(FILE * fp) o arquivo busca o binário correspondente. */ template <class T> class ByteReader { public: T byteCatch(FILE * fp); }; /** * @brief byteCatch(FILE * fp) busca o binário correspondendo ao tipo T. * @param FILE * fp : arquivo de acesso. */ template <class T> T ByteReader<T>::byteCatch(FILE * fp) { int num_of_bytes = sizeof(T); T toReturn = NEUTRAL_BYTE_FOR_OR; for(int i = 0; i < num_of_bytes; i++) { toReturn = ((toReturn << 8) | getc(fp)); } return toReturn; } #endif // ___BYTEREADER_H___
23.058824
98
0.678571
alexnsouza6
c169629e883214292d37f58709924011cbd1456d
2,156
cpp
C++
A.cpp
MaowMan/cpp-sprout
64c261a49f02d3070d5c97480f3b71c0ac102f0e
[ "MIT" ]
null
null
null
A.cpp
MaowMan/cpp-sprout
64c261a49f02d3070d5c97480f3b71c0ac102f0e
[ "MIT" ]
null
null
null
A.cpp
MaowMan/cpp-sprout
64c261a49f02d3070d5c97480f3b71c0ac102f0e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cstdio> #include <set> int main(){ long long n; std::cin>>n; if (n==2){ long long nxt; std::cin>>nxt; if (nxt==1){ putchar('2'); putchar('\n'); } else{ putchar('1'); putchar('\n'); } } else if (n==3){ long long a,b; std::cin>>a>>b; if (a-(b-a)>0){ std::cout<<a-(b-a)<<std::endl; } else{ if((b-a)%2==0){ std::cout<<a+(b-a)/2<<std::endl; } else{ std::cout<<b+(b-a)<<std::endl; } } } else if(n==4){ long long a,b,c; std::cin>>a>>b>>c; if((b-a)==(c-b)){ if (a-(b-a)>0){ std::cout<<a-(b-a)<<std::endl; } else{ std::cout<<c+(b-a)<<std::endl; } } else{ if((b-a)>(c-b)){ std::cout<<a+(b-a)/2<<std::endl; } else{ std::cout<<b+(c-b)/2<<std::endl; } } } else{ long long a,b,c,d; std::cin>>a>>b>>c>>d; if(((b-a)==(c-b))&&((d-c)==(c-b))){ long long log=(b-a); long long prev,next,cache; prev=c; next=d; while(std::cin>>cache){ prev=next; next=cache; if ((next-prev)!=log){ std::cout<<prev+(next-prev)/2<<std::endl; return 0; } } if ((a-log)>0){ std::cout<<(a-log)<<std::endl; } else{ std::cout<<(next+log)<<std::endl; } } else{ if((b-a)==(c-b)){ std::cout<<c+(d-c)/2<<std::endl; } else if((b-a)==(d-c)){ std::cout<<b+(c-b)/2<<std::endl; } else{ std::cout<<a+(b-a)/2<<std::endl; } return 0; } } }
23.182796
61
0.306586
MaowMan
c17311fe4d62f2041e8a6d68bdedc80b5266f9cd
833
cpp
C++
src/pan.cpp
Dam-0/grid
5a522de1383c55c199804176d9591abeb3a04d41
[ "MIT" ]
null
null
null
src/pan.cpp
Dam-0/grid
5a522de1383c55c199804176d9591abeb3a04d41
[ "MIT" ]
null
null
null
src/pan.cpp
Dam-0/grid
5a522de1383c55c199804176d9591abeb3a04d41
[ "MIT" ]
null
null
null
#include "grid.h" void Grid::pan(float x, float y) { _cam_x_decimal += x; _cam_y_decimal += y; int cell_pan = floor(_cam_x_decimal); _cam_x += cell_pan; _cam_x_decimal -= cell_pan; cell_pan = floor(_cam_y_decimal); _cam_y += cell_pan; _cam_y_decimal -= cell_pan; _grid_moved = true; } void Grid::applyPanVel(float delta_time) { if (!_pan_vel_x && !_pan_vel_y) return; pan(_pan_vel_x * delta_time / _scale, _pan_vel_y * delta_time / _scale); _pan_vel_x -= _pan_vel_x * _pan_friction * delta_time; _pan_vel_y -= _pan_vel_y * _pan_friction * delta_time; if (abs(_pan_vel_x) < _min_pan_vel && abs(_pan_vel_y) < _min_pan_vel) { _pan_vel_x = 0; _pan_vel_y = 0; } onMouseMotion(_mouse_x, _mouse_y); }
23.8
76
0.618247
Dam-0
c1771e6362c0c0e415e7b4cdc8a55465a3e8dc3c
390
hpp
C++
TGEngine/util/Debug.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/util/Debug.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/util/Debug.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
#pragma once #include "..\Stdbase.hpp" SINCE(0, 0, 1) #define printExtend(x) cout << "width:" << x.width << " height:" << x.height << endl; SINCE(0, 0, 1) #define printOffset(v) cout << "x:" << v.x << " y:" << v.y << endl; /* * Prints a version with the Format MAJOR.MINOR.VERSION e.g. 1.0.0 * You can built it with VK_MAKE_VERSION */ SINCE(0, 0, 1) void printVersion(int version);
24.375
86
0.615385
ThePixly
c178696be3dae369267c571130a2a46f475aed5c
654
hpp
C++
supervisor/src/network/websocket/wrapper/events/Disconnection.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
1
2018-11-12T02:48:46.000Z
2018-11-12T02:48:46.000Z
supervisor/src/network/websocket/wrapper/events/Disconnection.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
null
null
null
supervisor/src/network/websocket/wrapper/events/Disconnection.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
null
null
null
#ifndef TIN_NETWORK_WEBSOCKET_WRAPPER_EVENTS_DISCONNECTION_HPP #define TIN_NETWORK_WEBSOCKET_WRAPPER_EVENTS_DISCONNECTION_HPP #include <websocketpp/server.hpp> #include "../Event.hpp" namespace tin { namespace network { namespace websocket { namespace wrapper { namespace events { struct Disconnection: public tin::network::websocket::wrapper::Event { websocketpp::connection_hdl connectionHandler; Disconnection(websocketpp::connection_hdl& connectionHandler); virtual void accept(tin::network::websocket::wrapper::ServerVisitor& i); }; }}}}} #endif /* TIN_NETWORK_WEBSOCKET_WRAPPER_EVENTS_DISCONNECTION_HPP */
31.142857
94
0.776758
mdziekon
c1812d08d9d03987552ec67444543443d73ad5ea
2,137
cpp
C++
C++/cat-and-mouse.cpp
black-shadows/LeetCode-Solutions
b1692583f7b710943ffb19b392b8bf64845b5d7a
[ "Fair", "Unlicense" ]
1
2020-04-16T08:38:14.000Z
2020-04-16T08:38:14.000Z
cat-and-mouse.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
null
null
null
cat-and-mouse.cpp
Jeevan-kumar-Raj/LeetCode-Solutions-Topicwise
f1111b4edd401a3fc47111993bd7250cf4dc76da
[ "MIT" ]
1
2021-12-25T14:48:56.000Z
2021-12-25T14:48:56.000Z
// Time: O(n^3) // Space: O(n^2) class Solution { private: template <typename A, typename B, typename C> struct TupleHash { size_t operator()(const tuple<A, B, C>& p) const { size_t seed = 0; A a; B b; C c; tie(a, b, c) = p; seed ^= std::hash<A>{}(a) + 0x9e3779b9 + (seed<<6) + (seed>>2); seed ^= std::hash<B>{}(b) + 0x9e3779b9 + (seed<<6) + (seed>>2); seed ^= std::hash<C>{}(c) + 0x9e3779b9 + (seed<<6) + (seed>>2); return seed; } }; using Lookup = unordered_map<tuple<int, int, bool>, int, TupleHash<int, int, bool>>; public: int catMouseGame(vector<vector<int>>& graph) { Lookup lookup; return move(graph, &lookup, MOUSE_START, CAT_START, true); } private: enum Location {HOLE, MOUSE_START, CAT_START}; enum Result {DRAW, MOUSE, CAT}; int move(const vector<vector<int>>& graph, Lookup *lookup, int i, int other_i, bool is_mouse_turn) { const auto& key = make_tuple(i, other_i, is_mouse_turn); if (lookup->count(key)) { return (*lookup)[key]; } (*lookup)[key] = DRAW; int skip, target, win, lose; if (is_mouse_turn) { tie(skip, target, win, lose) = make_tuple(other_i, HOLE, MOUSE, CAT); } else { tie(skip, target, win, lose) = make_tuple(HOLE, other_i, CAT, MOUSE); } for (const auto& nei : graph[i]) { if (nei == target) { (*lookup)[key] = win; return win; } } int result = lose; for (const auto& nei : graph[i]) { if (nei == skip) { continue; } auto tmp = move(graph, lookup, other_i, nei, !is_mouse_turn); if (tmp == win) { result = win; break; } if (tmp == DRAW) { result = DRAW; } } (*lookup)[key] = result; return result; } };
31.895522
105
0.463734
black-shadows
c184369c50700cd126a7f04f0e0b682b146c1330
143
cpp
C++
building_cpp_with_sfml_wave_01/main.cpp
michaelgautier/codeexpo
f10a38d41cfbea521fc5938360d4481f966593ae
[ "Apache-2.0" ]
1
2019-05-14T15:13:42.000Z
2019-05-14T15:13:42.000Z
building_cpp_with_sfml_wave_01/main.cpp
michaelgautier/codeexpo
f10a38d41cfbea521fc5938360d4481f966593ae
[ "Apache-2.0" ]
null
null
null
building_cpp_with_sfml_wave_01/main.cpp
michaelgautier/codeexpo
f10a38d41cfbea521fc5938360d4481f966593ae
[ "Apache-2.0" ]
null
null
null
#include "program.h" using namespace Gautier::SFMLApp; int main() { Program SFMLAppProgram; SFMLAppProgram.Execute(); return 0; }
14.3
34
0.692308
michaelgautier
c1868d48624a8a26e01e0810da3e31770a8091d1
2,957
cc
C++
src/heap/finalization-registry-cleanup-task.cc
gilanghamidy/DifferentialFuzzingWASM-v8
28a546d241027a5fb715cacd26fd31d06b4bb0c1
[ "BSD-3-Clause" ]
1
2020-12-25T00:58:59.000Z
2020-12-25T00:58:59.000Z
src/heap/finalization-registry-cleanup-task.cc
gilanghamidy/DifferentialFuzzingWASM-v8
28a546d241027a5fb715cacd26fd31d06b4bb0c1
[ "BSD-3-Clause" ]
2
2020-02-29T08:38:40.000Z
2020-03-03T04:15:40.000Z
src/heap/finalization-registry-cleanup-task.cc
gilanghamidy/DifferentialFuzzingWASM-v8
28a546d241027a5fb715cacd26fd31d06b4bb0c1
[ "BSD-3-Clause" ]
1
2020-09-05T18:28:16.000Z
2020-09-05T18:28:16.000Z
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/heap/finalization-registry-cleanup-task.h" #include "src/execution/frames.h" #include "src/execution/interrupts-scope.h" #include "src/execution/stack-guard.h" #include "src/execution/v8threads.h" #include "src/heap/heap-inl.h" #include "src/objects/js-weak-refs-inl.h" #include "src/tracing/trace-event.h" namespace v8 { namespace internal { FinalizationRegistryCleanupTask::FinalizationRegistryCleanupTask(Heap* heap) : CancelableTask(heap->isolate()), heap_(heap) {} void FinalizationRegistryCleanupTask::SlowAssertNoActiveJavaScript() { #ifdef ENABLE_SLOW_DCHECKS class NoActiveJavaScript : public ThreadVisitor { public: void VisitThread(Isolate* isolate, ThreadLocalTop* top) override { for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) { DCHECK(!it.frame()->is_java_script()); } } }; NoActiveJavaScript no_active_js_visitor; Isolate* isolate = heap_->isolate(); no_active_js_visitor.VisitThread(isolate, isolate->thread_local_top()); isolate->thread_manager()->IterateArchivedThreads(&no_active_js_visitor); #endif // ENABLE_SLOW_DCHECKS } void FinalizationRegistryCleanupTask::RunInternal() { Isolate* isolate = heap_->isolate(); DCHECK(!isolate->host_cleanup_finalization_group_callback()); SlowAssertNoActiveJavaScript(); TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.FinalizationRegistryCleanupTask"); HandleScope handle_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry; // There could be no dirty FinalizationRegistries. When a context is disposed // by the embedder, its FinalizationRegistries are removed from the dirty // list. if (!heap_->DequeueDirtyJSFinalizationRegistry().ToHandle( &finalization_registry)) { return; } finalization_registry->set_scheduled_for_cleanup(false); // Since FinalizationRegistry cleanup callbacks are scheduled by V8, enter the // FinalizationRegistry's context. Handle<Context> context( Context::cast(finalization_registry->native_context()), isolate); Handle<Object> callback(finalization_registry->cleanup(), isolate); v8::Context::Scope context_scope(v8::Utils::ToLocal(context)); v8::TryCatch catcher(reinterpret_cast<v8::Isolate*>(isolate)); catcher.SetVerbose(true); // Exceptions are reported via the message handler. This is ensured by the // verbose TryCatch. InvokeFinalizationRegistryCleanupFromTask(context, finalization_registry, callback); // Repost if there are remaining dirty FinalizationRegistries. heap_->set_is_finalization_registry_cleanup_task_posted(false); heap_->PostFinalizationRegistryCleanupTaskIfNeeded(); } } // namespace internal } // namespace v8
37.910256
80
0.748732
gilanghamidy
c18879c2f0c496713cb539480a752414bebb9ea4
270
cpp
C++
OSE Resources Mesh ASSIMP/Resources/Mesh/MeshLoaderFactoryASSIMP.cpp
rexapex/OSE-V2-Game-Engine-
cbf8040d4b017275c073373f8438b227e691858d
[ "MIT" ]
1
2019-09-29T17:45:11.000Z
2019-09-29T17:45:11.000Z
OSE Resources Mesh ASSIMP/Resources/Mesh/MeshLoaderFactoryASSIMP.cpp
rexapex/OSE-V2-Game-Engine-
cbf8040d4b017275c073373f8438b227e691858d
[ "MIT" ]
10
2020-11-13T13:41:26.000Z
2020-11-16T18:46:57.000Z
OSE Resources Mesh ASSIMP/Resources/Mesh/MeshLoaderFactoryASSIMP.cpp
rexapex/OSE-Game-Engine
cbf8040d4b017275c073373f8438b227e691858d
[ "MIT" ]
null
null
null
#include "pch.h" #include "MeshLoaderFactoryASSIMP.h" #include "MeshLoaderASSIMP.h" namespace ose::resources { uptr<MeshLoader> MeshLoaderFactoryASSIMP::NewMeshLoader(std::string const & project_path) { return ose::make_unique<MeshLoaderASSIMP>(project_path); } }
22.5
90
0.781481
rexapex
c1916fcbacd55009a99677cac0d6f078e316d7c4
14,367
cpp
C++
1 course/lab_6_dyn_array/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
1 course/lab_6_dyn_array/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
1 course/lab_6_dyn_array/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
// ver 1.2 - 08.04.19 #include <iostream> #include <fstream> #include <ctime> #include <cmath> using namespace std; void filling_array_from_keyboard (short int *A, int N) { cout << "*** Осуществляется заполнение динамического массива значениями с клавиатуры ***" << endl; cout << "Задайте значения элементов динамического массива: " << endl; int chislo; for (int i = 0; i < N; i++) { cout << "Для " << i+1 << "-го: "; cin >> chislo; A[i] = chislo; } } void filling_array_random (short int *A, int N, int min, int max) { cout << "*** Осуществляется заполнение динамического массива случайными целыми числами ***" << endl; int chislo; int ostatok = (max - min) + 1; for (int i = 0; i < N; i++) { chislo = min + rand() % ( ostatok ); A[i] = chislo; } } void filling_array_from_file (short int *A, int N, string filename) { cout << "*** Осуществляется заполнение динамического массива из файла " << filename << " ***" << endl; int chislo; ifstream input(filename); if (input) // проверка открытия { for (int i = 0; i < N; i++) { input >> chislo; A[i] = chislo; } input.close(); } else cout << endl << "error! Не удалось открыть файл " << filename << endl; } void print_array (const short int *A, int N) { for (int i = 0; i < N; i++) cout << A[i] << " "; cout << endl; } void diapazon_rand (int &min, int& max) { cout << "Задайте диапазон генерирования случайных чисел." << endl; cout << "Нижняя граница: "; cin >> min; cout << "Верхняя граница: "; cin >> max; while (min >= max) { cout << "error!" << endl; cout << "Верхняя граница: "; cin >> max; } } void sposob_zapolneniya (short int *A, int N) { int choice; cout << "*** Выбор способа заполнения ***" << endl; cout << "1. Заполнение с клавиатуры." << endl; cout << "2. Заполнение случайными числами." << endl; cout << "3. Заполнение из файла." << endl; cout << "Выберите способ заполнения: "; cin >> choice; while (choice < 1 || choice > 3) { cout << "error!" << endl; cout << "Выберите способ заполнения: "; cin >> choice; } switch (choice) { case 1: { filling_array_from_keyboard(A, N); break; } case 2: { int min, max; diapazon_rand(min,max); filling_array_random(A,N,min,max); break; } case 3: string filename; cout << "Введите название файла: "; cin >> filename; filling_array_from_file(A,N,filename); break; } } //Проверка на полный квадрат (если корень double числа равен корню приведенному к int, то число - полный квадрат) bool full_square (short int chislo) { double sqrt_chislo = sqrt(chislo); if (chislo >= 0 && sqrt_chislo == static_cast<short int> (sqrt_chislo)) return true; else return false; } // Поиск первого квадрата в массиве short int first_full_square (const short int *A, int N) { for(int i = 0; i < N; i++) { if (full_square( A[i] )) return A[i]; } return -1; // значит полных квадратов в массиве нет } // Является ли число числом Фибоначчи bool is_fibonachi (short int chislo) { int summa(0), a1 (0), a2(1); while (summa < chislo) { summa = a1 + a2; a1 = a2; a2 = summa; } if (chislo == summa) return true; else return false; } //Поиск var - числа, в котором нет заданной цифры bool find_var (short int chislo, short int zadannaya_cifra) { if (chislo < 0) chislo = -chislo; short int ostatok; if (chislo == zadannaya_cifra) return false; while (chislo > 0) { ostatok = chislo % 10; if (ostatok == zadannaya_cifra) return false; chislo /= 10; } return true; } //Копирование массивов (из temp в A) void Copy(const short int *temp, short int *A, int N) { for (int i = 0; i < N; ++i) A[i] = temp[i]; } //Выясняем размер массива после добавления элементов int insert_future_size_of_array (const short int *A, int N, short int zadannaya_cifra) { int N_out = N; for (int i = 0; i < N; i++) { if (find_var(A[i],zadannaya_cifra)) N_out++; } return N_out; } // Добавление первого полного квадрата после числа, в котором нет заданной цифры void insert_after_var (const short int *A, short int *temp, int N, short int fullsquare, short int zadannaya_cifra) { int i_temp = 0; for (int i = 0; i < N; i++) { temp[i_temp] = A[i]; if (find_var(A[i],zadannaya_cifra)) { i_temp++; temp[i_temp] = fullsquare; } i_temp++; } } // Добавление до числа, в котором нет заданной цифры void insert_before_var (const short int *A, short int *temp, int N, short int fullsquare, short int zadannaya_cifra) { int i_temp = 0; for (int i = 0; i < N; i++) { if (find_var(A[i],zadannaya_cifra)) { temp[i_temp] = fullsquare; i_temp++; temp[i_temp] = A[i]; } else temp[i_temp] = A[i]; i_temp++; } } //Выясняем размер массива после удаления элементов int delete_future_size_of_array (const short int *A, int N) { int N_out = N; for (int i = 0; i < N; i++) { if (is_fibonachi(A[i])) { N_out--; } } return N_out; } // Удаление чисел Фибоначчи void delete_fibonachi (const short int *A, short int *temp, int N) { int i_temp = 0; for (int i = 0; i < N; i++) { if (!is_fibonachi(A[i])) { temp[i_temp] = A[i]; i_temp++; } } } void display_menu () { cout << "*** Меню ***" << endl; cout << "1. Задание 1.1 - Добавить первый элемент, являющийся полным квадратом после числа, в которых нет заданной цифры." << endl; cout << "2. Задание 1.2 - Добавить первый элемент, являющийся полным квадратом перед числом, в котором нет заданной цифры." << endl; cout << "3. Задание 2 - Удалить все числа Фибоначчи." << endl; cout << "4. Завершить работу программы." << endl; } int main() { srand((unsigned)time(0)); system("chcp 1251 > nul"); cout << "Лабораторная работа №6 Вариант 13.\nАвтор: Катунин Сергей. ДИПРБ-11.\n" << endl; // Первый вывод условий меню display_menu(); // Ввод размера массива int N; cout << endl << "Задайте размер динамического массива: "; cin >> N; // Проверка на дурака while (N < 1) { cout << "error!" << endl; cout << "Задайте размер динамического массива: "; cin >> N; } // Конец ввода short int *A = new short int[N]; // объявляю указатель на рабочий массив и выделяю для него размер N short int *temp; // объявляю указатель на временный массив // Список (массив, вектор) заполняется один раз sposob_zapolneniya(A,N); cout << "Полученный динамический массив: "; print_array(A,N); int menu; while (menu != 4 && N > 0) { //пока пользователь хочет продолжать работу или размер > 0 - работа продолжается display_menu(); // меню cout << "Выберите пункт меню: "; cin >> menu; // выбираем пункт меню и запоминаем номер //проверка на дурака while (menu < 0 || menu > 4) { cout << "error!" << endl; cout << "Выберите пункт меню: "; cin >> menu; } if (menu != 4) // завершает работу если пользователь выбрал 4 пункт меню { switch (menu) // переходим непосредственно к выполнению заданий { case 1: { cout << "Выполнение задания 1.1 - Добавить первый элемент, являющийся полным квадратом после числа, в которых нет заданной цифры." << endl; short int add_elem = first_full_square(A,N); // нахожу первый полный квадрат if (add_elem == -1) // проверяю, нашлось ли оно { cout << "*** В динамическом массиве отсутствуют полные квадраты! ***" << endl; cout << "Задайте число, которое необходимо добавить: "; cin >> add_elem; // задаю вручную, если числа не нашлось } short int zadannaya_cifra; cout << "Введите заданную цифру: "; cin >> zadannaya_cifra; // ввожу заданную цифру while (zadannaya_cifra < 0 || zadannaya_cifra > 9) { cout << "error!" << endl; cout << "Введите заданную цифру: "; cin >> zadannaya_cifra; } cout << " Динамический массив до изменений: "; print_array(A,N); int N_temp = insert_future_size_of_array(A,N,zadannaya_cifra); // вычисляю размер массива после добавления элемента if (N_temp == N) { cout << "Динамический не подвергся изменениям, так как не было найдено числа, в котором нет заданной цифры." << endl; } else { temp = new short int[N_temp]; // выделяю память под массив temp insert_after_var(A,temp,N,add_elem,zadannaya_cifra); // переписываю все элементы массива A в массив Temp и заодно добавляю нужные элементы delete[] A; // очищаю память выделенную для A N = N_temp; // переопределяю размер N для A A = new short int[N]; // выделяю память под уже новый массив A Copy(temp,A,N); // копирую элементы из массива temp в массив A delete[] temp; // очищаю память выделенную под temp cout << " Динамический массив после изменений: "; print_array(A,N); } cout << "Задание 1.1 выполнено!" << endl; break; } case 2: { cout << "Выполнение задания 1.2 - Добавить первый элемент, являющийся полным квадратом перед числом, в котором нет заданной цифры." << endl; short int add_elem = first_full_square(A,N); // нахожу первый полный квадрат if (add_elem == -1) // проверяю, нашлось ли оно { cout << "*** В динамическом массиве отсутствуют полные квадраты! ***" << endl; cout << "Задайте число, которое необходимо добавить: "; cin >> add_elem; // задаю вручную, если числа не нашлось } short int zadannaya_cifra; cout << "Введите заданную цифру: "; cin >> zadannaya_cifra; // ввожу заданную цифру while (zadannaya_cifra < 0 || zadannaya_cifra > 9) { cout << "error!" << endl; cout << "Введите заданную цифру: "; cin >> zadannaya_cifra; } cout << " Динамический массив до изменений: "; print_array(A,N); int N_temp = insert_future_size_of_array(A,N,zadannaya_cifra); // вычисляю размер массива после добавления элемента if (N_temp == N) { cout << "Динамический не подвергся изменениям, так как не было найдено числа, в котором нет заданной цифры." << endl; } else { temp = new short int[N_temp]; // выделяю память под массив temp insert_before_var(A,temp,N,add_elem,zadannaya_cifra); // переписываю все элементы массива A в массив Temp и заодно добавляю нужные элементы delete[] A; // очищаю память выделенную для A N = N_temp; // переопределяю размер N для A A = new short int[N]; // выделяю память под уже новый массив A Copy(temp,A,N); // копирую элементы из массива temp в массив A delete[] temp; // очищаю память выделенную под temp cout << " Динамический массив после изменений: "; print_array(A,N); } cout << "Задание 1.2 выполнено!" << endl; break; } case 3: { cout << " Динамический массив до изменений: "; print_array(A,N); int N_temp = delete_future_size_of_array(A,N); // вычисляю размер массива после удаления чисел фибоначчи if (N_temp == N) { cout << "Динамический массив не подвергся изменениям, так как не были найдены числа Фибоначчи." << endl; } else { temp = new short int[N_temp]; // выделяю память под массив temp delete_fibonachi(A,temp,N); // переписываю все элементы массива А в массив temp, кроме чисел фибоначчи delete[] A; // очищаю память выделенную для A N = N_temp; // переопределяю размер N для A A = new short int[N]; // выделяю память под уже новый массив A Copy(temp,A,N); // копирую элементы из массива temp в массив A delete[] temp; // очищаю память выделенную под temp cout << " Динамический массив после изменений: "; print_array(A,N); } cout << "Задание 2 выполнено!" << endl; break; } } } } if (N == 0) cout << "Динамический массив опустел в результате удаления элементов."; else cout << "Программа была завершена по желанию пользователя."; return 0; }
35.299754
163
0.523839
SgAkErRu
c1951e2242d124f3a46fb98ab36a1ea7db5fdf95
1,314
hpp
C++
include/ShishGL/Core/EventSystem/EventManager.hpp
Shishqa/ShishGL
36a3273aecb4b87d040616059ed9487d18abac1a
[ "MIT" ]
null
null
null
include/ShishGL/Core/EventSystem/EventManager.hpp
Shishqa/ShishGL
36a3273aecb4b87d040616059ed9487d18abac1a
[ "MIT" ]
null
null
null
include/ShishGL/Core/EventSystem/EventManager.hpp
Shishqa/ShishGL
36a3273aecb4b87d040616059ed9487d18abac1a
[ "MIT" ]
null
null
null
/*============================================================================*/ #ifndef SHISHGL_EVENT_MANAGER_HPP #define SHISHGL_EVENT_MANAGER_HPP /*============================================================================*/ #include <type_traits> #include <queue> #include "Event.hpp" /*============================================================================*/ namespace Sh { class EventManager { private: template <typename SomeEvent, typename T> using Helper = std::enable_if_t<std::is_base_of<Event, SomeEvent>::value, T>; public: template <typename SomeEvent, typename... Args> static Helper<SomeEvent, void> postEvent(Args&&... args); virtual ~EventManager() = default; private: EventManager() = default; using EventQueue = std::queue<Event*>; static EventQueue& Events(); static void flush(); friend class EventSystem; friend class CoreApplication; }; } /*============================================================================*/ #include "EventManager.ipp" /*============================================================================*/ #endif //SHISHGL_EVENT_MANAGER_HPP /*============================================================================*/
28.565217
80
0.407915
Shishqa
c19b51b3fe764224c02028a55ff9196d04646bc6
130
cc
C++
build/ARM/arch/arm/pmu.cc
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
5
2019-12-12T16:26:09.000Z
2022-03-17T03:23:33.000Z
build/ARM/arch/arm/pmu.cc
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
build/ARM/arch/arm/pmu.cc
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:debc68e4dbb38b0effed848d9297d632f5013185a2fedb77865d89d6d835e1e3 size 20574
32.5
75
0.884615
zhoushuxin
c19b84e57de39631c337542cc5c6e7a9c4d57b19
1,439
cpp
C++
src/module.cpp
CrendKing/proxy-copy-handler
06e00839ef84c596a41851030f35530d79f3a7cd
[ "MIT" ]
4
2020-04-18T04:01:06.000Z
2022-03-06T09:24:15.000Z
src/module.cpp
CrendKing/proxy-copy-handler
06e00839ef84c596a41851030f35530d79f3a7cd
[ "MIT" ]
null
null
null
src/module.cpp
CrendKing/proxy-copy-handler
06e00839ef84c596a41851030f35530d79f3a7cd
[ "MIT" ]
null
null
null
class ProxyCopyHandlerModule : public ATL::CAtlDllModuleT<ProxyCopyHandlerModule> { } g_module; extern "C" auto WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) -> BOOL { return g_module.DllMain(dwReason, lpReserved); } _Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllCanUnloadNow() -> HRESULT { return g_module.DllCanUnloadNow(); } _Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllGetClassObject(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ LPVOID FAR *ppv) -> HRESULT { return g_module.DllGetClassObject(rclsid, riid, ppv); } _Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllRegisterServer() -> HRESULT { return g_module.DllRegisterServer(FALSE); } _Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllUnregisterServer() -> HRESULT { return g_module.DllUnregisterServer(FALSE); } _Use_decl_annotations_ extern "C" auto STDAPICALLTYPE DllInstall(BOOL bInstall, _In_opt_ PCWSTR pszCmdLine) -> HRESULT { HRESULT hr = E_FAIL; static const wchar_t szUserSwitch[] = L"user"; if (pszCmdLine != nullptr) { if (_wcsnicmp(pszCmdLine, szUserSwitch, _countof(szUserSwitch)) == 0) { ATL::AtlSetPerUserRegistration(true); } } if (bInstall) { hr = DllRegisterServer(); if (FAILED(hr)) { DllUnregisterServer(); } } else { hr = DllUnregisterServer(); } return hr; }
31.977778
150
0.71091
CrendKing
c19d9250d7067d3e1874ebc8316af9643769da00
1,090
hpp
C++
src/shader.hpp
BujakiAttila/GPGPU-GameOfLife
6fd13fe5f7a6a21c7820822df54d737f750177d2
[ "MIT" ]
null
null
null
src/shader.hpp
BujakiAttila/GPGPU-GameOfLife
6fd13fe5f7a6a21c7820822df54d737f750177d2
[ "MIT" ]
null
null
null
src/shader.hpp
BujakiAttila/GPGPU-GameOfLife
6fd13fe5f7a6a21c7820822df54d737f750177d2
[ "MIT" ]
null
null
null
#ifndef _SHADER_ #define _SHADER_ #include <string> #include <GL/glew.h> class Shader{ private: GLuint shaderProgram; Shader(); bool fileToString(const char* path, char* &out, int& len); public: Shader(const char* vertexShaderPath, const char* fragmentShaderPath); virtual ~Shader(); void shaderFromFile(const char* shaderPath, GLenum shaderType, GLuint& handle); void linkShaders(GLuint& vertexShader, GLuint& fragmentShader, GLuint& handle); std::string getShaderInfoLog(GLuint& object); std::string getProgramInfoLog(GLuint& object); void enable(); void disable(); GLuint getHandle(){ return shaderProgram; } void bindUniformInt(const char* name, int i); void bindUniformInt2(const char* name, int i1, int i2); void bindUniformFloat(const char* name, float f); void bindUniformFloat2(const char* name, float f1, float f2); void bindUniformFloat3(const char* name, float f1, float f2, float f3); void bindUniformTexture(const char* name, GLuint texture, GLuint unit); void bindAttribLocation(GLuint id, const char* name); }; #endif
25.348837
81
0.73578
BujakiAttila
c19fab504630ceb5e28c641dab3be61995a3dbf6
589
cpp
C++
kattis_numbertree.cpp
dylanashley/programming-problems
aeba99daaaade1071ed3ab8d51d6f36e84493ef6
[ "MIT" ]
null
null
null
kattis_numbertree.cpp
dylanashley/programming-problems
aeba99daaaade1071ed3ab8d51d6f36e84493ef6
[ "MIT" ]
null
null
null
kattis_numbertree.cpp
dylanashley/programming-problems
aeba99daaaade1071ed3ab8d51d6f36e84493ef6
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { int height; int label = 1; string path; cin >> height; if (cin.eof()) { label = (1 << (height + 1)) - 1; } else { cin >> path; for (int i = 0; i < path.length(); ++i) { if (path[i] == 'L') { label = label << 1; } else { label = (label << 1) + 1; } } label = (1 << (height + 1)) - label; } cout << label << endl; }
15.102564
47
0.353141
dylanashley
c1a4c73501006f4f9b893b09820d43af00459514
2,343
cpp
C++
Sandbox/src/Sandbox3D/Model/Billboard.cpp
cyandestructor/Sandbox3D
de19e962aeb69f7e6f28fe07263f95920332287a
[ "MIT" ]
null
null
null
Sandbox/src/Sandbox3D/Model/Billboard.cpp
cyandestructor/Sandbox3D
de19e962aeb69f7e6f28fe07263f95920332287a
[ "MIT" ]
null
null
null
Sandbox/src/Sandbox3D/Model/Billboard.cpp
cyandestructor/Sandbox3D
de19e962aeb69f7e6f28fe07263f95920332287a
[ "MIT" ]
null
null
null
#include "Billboard.h" Billboard::Billboard() { static const float vertices[] = { -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f }; m_vertexArray = Jass::VertexArray::Create(); auto vbo = Jass::VertexBuffer::Create({ vertices, sizeof(vertices), Jass::DataUsage::StaticDraw }); vbo->SetLayout({ Jass::BufferElement(Jass::ShaderDataType::Float3, "a_position"), Jass::BufferElement(Jass::ShaderDataType::Float2, "a_texCoords") }); m_vertexArray->AddVertexBuffer(vbo); unsigned int indices[] = { 0, 1, 2, 2, 1, 3 }; auto ibo = Jass::IndexBuffer::Create({ indices, 6, Jass::DataUsage::StaticDraw }); m_vertexArray->SetIndexBuffer(ibo); } Billboard::Billboard(const Jass::JVec3& position, const Jass::JVec3& scale) :m_position(position), m_scale(scale) { static const float vertices[] = { -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f }; m_vertexArray = Jass::VertexArray::Create(); auto vbo = Jass::VertexBuffer::Create({ vertices, sizeof(vertices), Jass::DataUsage::StaticDraw }); vbo->SetLayout({ Jass::BufferElement(Jass::ShaderDataType::Float3, "a_position"), Jass::BufferElement(Jass::ShaderDataType::Float2, "a_texCoords") }); m_vertexArray->AddVertexBuffer(vbo); unsigned int indices[] = { 0, 1, 2, 2, 1, 3 }; auto ibo = Jass::IndexBuffer::Create({ indices, 6, Jass::DataUsage::StaticDraw }); m_vertexArray->SetIndexBuffer(ibo); } void Billboard::Render(Jass::Ref<Jass::Shader>& shader, const Light& light, const Jass::Camera& camera) { shader->Bind(); const auto& viewMatrix = camera.GetView(); Jass::JVec3 cameraRightWS = { viewMatrix[0][0], viewMatrix[1][0], viewMatrix[2][0] }; Jass::JVec3 cameraUpWS = { viewMatrix[0][1], viewMatrix[1][1], viewMatrix[2][1] }; shader->SetFloat3("u_cameraRightWS", cameraRightWS); shader->SetFloat3("u_cameraUpWS", cameraUpWS); shader->SetFloat3("u_billboardPosition", m_position); shader->SetFloat3("u_billboardScale", m_scale); shader->SetMat4("u_viewProjection", camera.GetViewProjection()); m_material.Prepare(shader, light); Jass::RenderCommand::DrawIndexed(m_vertexArray); //Jass::Renderer::Submit(shader, m_vertexArray); }
26.033333
103
0.673922
cyandestructor
c1a772fac95cff54fc9ab0a09ae37a05490478ca
537
cpp
C++
lintcode/rotatestring.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
lintcode/rotatestring.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
lintcode/rotatestring.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: /** * param A: A string * param offset: Rotate string with offset. * return: Rotated string. */ string rotateString(string A, int offset) { // wirte your code here int len=A.size(); if(len==0){ return ""; } offset%=len; string res=A; reverse(res.begin(),res.end()); reverse(res.begin(),res.begin()+offset); reverse(res.begin()+offset,res.end()); return res; } };
21.48
48
0.489758
WIZARD-CXY
c1a857079e4988789cdbca79dddf135c1f093773
2,306
hpp
C++
Graphics/ShaderTools/include/DXCompilerBaseUWP.hpp
AndreyMlashkin/DiligentCore
20d5d7d2866e831a73437db2dec16bdc61413eb0
[ "Apache-2.0" ]
null
null
null
Graphics/ShaderTools/include/DXCompilerBaseUWP.hpp
AndreyMlashkin/DiligentCore
20d5d7d2866e831a73437db2dec16bdc61413eb0
[ "Apache-2.0" ]
null
null
null
Graphics/ShaderTools/include/DXCompilerBaseUWP.hpp
AndreyMlashkin/DiligentCore
20d5d7d2866e831a73437db2dec16bdc61413eb0
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2021 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include <Unknwn.h> #include <guiddef.h> #include <atlbase.h> #include <atlcom.h> #include "dxc/dxcapi.h" #include "DXCompiler.hpp" namespace Diligent { namespace { class DXCompilerBase : public IDXCompiler { public: ~DXCompilerBase() override { if (Module) FreeLibrary(Module); } protected: DxcCreateInstanceProc Load(DXCompilerTarget, const String& LibName) { if (LibName.size()) { std::wstring wname{LibName.begin(), LibName.end()}; wname += L".dll"; Module = LoadPackagedLibrary(wname.c_str(), 0); } if (Module == nullptr) Module = LoadPackagedLibrary(L"dxcompiler.dll", 0); return Module ? reinterpret_cast<DxcCreateInstanceProc>(GetProcAddress(Module, "DxcCreateInstance")) : nullptr; } private: HMODULE Module = nullptr; }; } // namespace } // namespace Diligent
29.948052
119
0.694276
AndreyMlashkin
c1af627d759e58563bb83352b9dc2d6045ef4db2
49,547
cpp
C++
src/energyplus/ForwardTranslator/ForwardTranslatePlantLoop.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
354
2015-01-10T17:46:11.000Z
2022-03-29T10:00:00.000Z
src/energyplus/ForwardTranslator/ForwardTranslatePlantLoop.cpp
muehleisen/OpenStudio
3bfe89f6c441d1e61e50b8e94e92e7218b4555a0
[ "blessing" ]
3,243
2015-01-02T04:54:45.000Z
2022-03-31T17:22:22.000Z
src/energyplus/ForwardTranslator/ForwardTranslatePlantLoop.cpp
jmarrec/OpenStudio
5276feff0d8dbd6c8ef4e87eed626bc270a19b14
[ "blessing" ]
157
2015-01-07T15:59:55.000Z
2022-03-30T07:46:09.000Z
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 "../ForwardTranslator.hpp" #include "../../model/Model.hpp" #include "../../model/PlantLoop.hpp" #include "../../model/PlantLoop_Impl.hpp" #include "../../model/AvailabilityManagerAssignmentList.hpp" #include "../../model/AvailabilityManagerAssignmentList_Impl.hpp" #include "../../model/AvailabilityManager.hpp" #include "../../model/AvailabilityManager_Impl.hpp" #include "../../model/AirLoopHVACOutdoorAirSystem.hpp" #include "../../model/AirLoopHVACOutdoorAirSystem_Impl.hpp" #include "../../model/SizingPlant.hpp" #include "../../model/SizingPlant_Impl.hpp" #include "../../model/Node.hpp" #include "../../model/Node_Impl.hpp" #include "../../model/Splitter.hpp" #include "../../model/Splitter_Impl.hpp" #include "../../model/Mixer.hpp" #include "../../model/Mixer_Impl.hpp" #include "../../model/PumpVariableSpeed.hpp" #include "../../model/Schedule.hpp" #include "../../model/Schedule_Impl.hpp" #include "../../model/BoilerHotWater.hpp" #include "../../model/BoilerHotWater_Impl.hpp" #include "../../model/CentralHeatPumpSystem.hpp" #include "../../model/CentralHeatPumpSystem_Impl.hpp" #include "../../model/ChillerElectricEIR.hpp" #include "../../model/ChillerElectricEIR_Impl.hpp" #include "../../model/ChillerElectricReformulatedEIR.hpp" #include "../../model/ChillerElectricReformulatedEIR_Impl.hpp" #include "../../model/ChillerAbsorption.hpp" #include "../../model/ChillerAbsorption_Impl.hpp" #include "../../model/ChillerAbsorptionIndirect.hpp" #include "../../model/ChillerAbsorptionIndirect_Impl.hpp" #include "../../model/WaterHeaterMixed.hpp" #include "../../model/WaterHeaterMixed_Impl.hpp" #include "../../model/WaterHeaterHeatPump.hpp" #include "../../model/WaterHeaterHeatPump_Impl.hpp" #include "../../model/WaterHeaterStratified.hpp" #include "../../model/WaterHeaterStratified_Impl.hpp" #include "../../model/CoolingTowerVariableSpeed.hpp" #include "../../model/CoolingTowerVariableSpeed_Impl.hpp" #include "../../model/CoolingTowerSingleSpeed.hpp" #include "../../model/CoolingTowerSingleSpeed_Impl.hpp" #include "../../model/CoolingTowerTwoSpeed.hpp" #include "../../model/CoolingTowerTwoSpeed_Impl.hpp" #include "../../model/GeneratorMicroTurbine.hpp" #include "../../model/GeneratorMicroTurbine_Impl.hpp" #include "../../model/GeneratorMicroTurbineHeatRecovery.hpp" #include "../../model/GeneratorMicroTurbineHeatRecovery_Impl.hpp" #include "../../model/GroundHeatExchangerVertical.hpp" #include "../../model/GroundHeatExchangerVertical_Impl.hpp" #include "../../model/GroundHeatExchangerHorizontalTrench.hpp" #include "../../model/GroundHeatExchangerHorizontalTrench_Impl.hpp" #include "../../model/HeatExchangerFluidToFluid.hpp" #include "../../model/HeatExchangerFluidToFluid_Impl.hpp" #include "../../model/WaterToAirComponent.hpp" #include "../../model/WaterToAirComponent_Impl.hpp" #include "../../model/WaterToWaterComponent.hpp" #include "../../model/WaterToWaterComponent_Impl.hpp" #include "../../model/CoilHeatingWaterBaseboard.hpp" #include "../../model/CoilHeatingWaterBaseboard_Impl.hpp" #include "../../model/CoilHeatingWaterBaseboardRadiant.hpp" #include "../../model/CoilHeatingWaterBaseboardRadiant_Impl.hpp" #include "../../model/CoilCoolingWaterPanelRadiant.hpp" #include "../../model/CoilCoolingWaterPanelRadiant_Impl.hpp" #include "../../model/CoilCoolingCooledBeam.hpp" #include "../../model/CoilCoolingCooledBeam_Impl.hpp" #include "../../model/CoilCoolingFourPipeBeam.hpp" #include "../../model/CoilCoolingFourPipeBeam_Impl.hpp" #include "../../model/CoilHeatingFourPipeBeam.hpp" #include "../../model/CoilHeatingFourPipeBeam_Impl.hpp" #include "../../model/StraightComponent.hpp" #include "../../model/StraightComponent_Impl.hpp" #include "../../model/CoilHeatingLowTempRadiantConstFlow.hpp" #include "../../model/CoilHeatingLowTempRadiantConstFlow_Impl.hpp" #include "../../model/CoilCoolingLowTempRadiantConstFlow.hpp" #include "../../model/CoilCoolingLowTempRadiantConstFlow_Impl.hpp" #include "../../model/CoilHeatingLowTempRadiantVarFlow.hpp" #include "../../model/CoilHeatingLowTempRadiantVarFlow_Impl.hpp" #include "../../model/CoilCoolingLowTempRadiantVarFlow.hpp" #include "../../model/CoilCoolingLowTempRadiantVarFlow_Impl.hpp" #include "../../model/ZoneHVACComponent.hpp" #include "../../model/ZoneHVACComponent_Impl.hpp" #include "../../model/SetpointManager.hpp" #include "../../model/SetpointManagerScheduledDualSetpoint.hpp" #include "../../model/SetpointManagerScheduledDualSetpoint_Impl.hpp" #include "../../model/LifeCycleCost.hpp" #include "../../utilities/idf/IdfExtensibleGroup.hpp" #include <utilities/idd/IddEnums.hxx> #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/PlantLoop_FieldEnums.hxx> #include <utilities/idd/BranchList_FieldEnums.hxx> #include <utilities/idd/Branch_FieldEnums.hxx> #include <utilities/idd/ConnectorList_FieldEnums.hxx> #include <utilities/idd/Connector_Splitter_FieldEnums.hxx> #include <utilities/idd/Connector_Mixer_FieldEnums.hxx> #include <utilities/idd/Pipe_Adiabatic_FieldEnums.hxx> #include <utilities/idd/PlantEquipmentOperationSchemes_FieldEnums.hxx> #include <utilities/idd/PlantEquipmentOperation_HeatingLoad_FieldEnums.hxx> #include <utilities/idd/PlantEquipmentOperation_CoolingLoad_FieldEnums.hxx> #include <utilities/idd/PlantEquipmentOperation_ComponentSetpoint_FieldEnums.hxx> #include <utilities/idd/PlantEquipmentOperation_Uncontrolled_FieldEnums.hxx> #include <utilities/idd/PlantEquipmentList_FieldEnums.hxx> #include <utilities/idd/Sizing_Plant_FieldEnums.hxx> #include <utilities/idd/AirTerminal_SingleDuct_ConstantVolume_CooledBeam_FieldEnums.hxx> #include <utilities/idd/AirTerminal_SingleDuct_ConstantVolume_FourPipeBeam_FieldEnums.hxx> #include <utilities/idd/ZoneHVAC_AirDistributionUnit_FieldEnums.hxx> #include <utilities/idd/FluidProperties_Name_FieldEnums.hxx> #include <utilities/idd/AvailabilityManagerAssignmentList_FieldEnums.hxx> #include "../../utilities/core/Assert.hpp" using namespace openstudio::model; using namespace std; namespace openstudio { namespace energyplus { IdfObject ForwardTranslator::populateBranch(IdfObject& branchIdfObject, std::vector<ModelObject>& modelObjects, Loop& loop, bool isSupplyBranch) { if (modelObjects.size() > 0) { int i = 0; for (auto& modelObject : modelObjects) { boost::optional<Node> inletNode; boost::optional<Node> outletNode; std::string objectName; std::string iddType; //translate and map each model object //in most cases, the name and idd object type come directly from the resulting idfObject if (boost::optional<IdfObject> idfObject = this->translateAndMapModelObject(modelObject)) { objectName = idfObject->name().get(); iddType = idfObject->iddObject().name(); } if (modelObject.optionalCast<Node>()) { // Skip nodes we don't want them showing up on branches continue; } if (auto straightComponent = modelObject.optionalCast<StraightComponent>()) { inletNode = straightComponent->inletModelObject()->optionalCast<Node>(); outletNode = straightComponent->outletModelObject()->optionalCast<Node>(); //special case for ZoneHVAC:Baseboard:Convective:Water. In E+, this object appears on both the //zonehvac:equipmentlist and the branch. In OpenStudio, this object was broken into 2 objects: //ZoneHVACBaseboardConvectiveWater and CoilHeatingWaterBaseboard. The ZoneHVAC goes onto the zone and //has a child coil that goes onto the plantloop. In order to get the correct translation to E+, we need //to put the name of the containing ZoneHVACBaseboardConvectiveWater onto the branch. if (boost::optional<CoilHeatingWaterBaseboard> coilBB = modelObject.optionalCast<CoilHeatingWaterBaseboard>()) { if (boost::optional<ZoneHVACComponent> contZnBB = coilBB->containingZoneHVACComponent()) { //translate and map containingZoneHVACBBConvWater if (boost::optional<IdfObject> idfContZnBB = this->translateAndMapModelObject(*contZnBB)) { //Get the name and the idd object from the idf object version of this objectName = idfContZnBB->name().get(); iddType = idfContZnBB->iddObject().name(); } } } //special case for ZoneHVAC:Baseboard:RadiantConvective:Water. In E+, this object appears on both the //zonehvac:equipmentlist and the branch. In OpenStudio, this object was broken into 2 objects: //ZoneHVACBaseboardRadiantConvectiveWater and CoilHeatingWaterBaseboardRadiant. The ZoneHVAC goes onto the zone and //has a child coil that goes onto the plantloop. In order to get the correct translation to E+, we need //to put the name of the containing ZoneHVACBaseboardRadiantConvectiveWater onto the branch. if (auto coilBBRad = modelObject.optionalCast<CoilHeatingWaterBaseboardRadiant>()) { if (auto contZnBBRad = coilBBRad->containingZoneHVACComponent()) { //translate and map containingZoneHVACBBRadConvWater if (auto idfContZnBBRad = this->translateAndMapModelObject(*contZnBBRad)) { //Get the name and the idd object from the idf object version of this objectName = idfContZnBBRad->name().get(); iddType = idfContZnBBRad->iddObject().name(); } } } //special case for ZoneHVAC:CoolingPanel:RadiantConvective:Water. In E+, this object appears on both the //zonehvac:equipmentlist and the branch. In OpenStudio, this object was broken into 2 objects: //ZoneHVACCoolingPanelRadiantConvectiveWater and CoilCoolingWaterPanelRadiant. The ZoneHVAC goes onto the zone and //has a child coil that goes onto the plantloop. In order to get the correct translation to E+, we need //to put the name of the containing ZoneHVACCoolingPanelRadiantConvectiveWater onto the branch. if (auto coilCPRad = modelObject.optionalCast<CoilCoolingWaterPanelRadiant>()) { if (auto contZnCPRad = coilCPRad->containingZoneHVACComponent()) { //translate and map containingZoneHVACBBRadConvWater if (auto idfContZnCPRad = this->translateAndMapModelObject(*contZnCPRad)) { //Get the name and the idd object from the idf object version of this objectName = idfContZnCPRad->name().get(); iddType = idfContZnCPRad->iddObject().name(); } } } //special case for AirTerminalSingleDuctConstantVolumeChilledBeam if (boost::optional<CoilCoolingCooledBeam> coilCB = modelObject.optionalCast<CoilCoolingCooledBeam>()) { if (boost::optional<StraightComponent> airTerm = coilCB->containingStraightComponent()) { boost::optional<IdfObject> idfAirDistUnit = this->translateAndMapModelObject(*airTerm); //translate and map containingStraightComponent if (idfAirDistUnit) { //Get the name and idd type of the air terminal inside the air distribution unit objectName = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalName).get(); iddType = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalObjectType).get(); } } } //special case for AirTerminalSingleDuctConstantVolumeFourPipeBeam: Cooling Side if (boost::optional<CoilCoolingFourPipeBeam> coilFPB = modelObject.optionalCast<CoilCoolingFourPipeBeam>()) { if (boost::optional<StraightComponent> airTerm = coilFPB->containingStraightComponent()) { boost::optional<IdfObject> idfAirDistUnit = this->translateAndMapModelObject(*airTerm); //translate and map containingStraightComponent if (idfAirDistUnit) { //Get the name and idd type of the air terminal inside the air distribution unit objectName = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalName).get(); iddType = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalObjectType).get(); } } } //special case for AirTerminalSingleDuctConstantVolumeFourPipeBeam: Cooling Side if (boost::optional<CoilHeatingFourPipeBeam> coilFPB = modelObject.optionalCast<CoilHeatingFourPipeBeam>()) { if (boost::optional<StraightComponent> airTerm = coilFPB->containingStraightComponent()) { boost::optional<IdfObject> idfAirDistUnit = this->translateAndMapModelObject(*airTerm); //translate and map containingStraightComponent if (idfAirDistUnit) { //Get the name and idd type of the air terminal inside the air distribution unit objectName = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalName).get(); iddType = idfAirDistUnit->getString(ZoneHVAC_AirDistributionUnitFields::AirTerminalObjectType).get(); } } } //special case for ZoneHVAC:LowTemperatureRadiant:ConstantFlow and ZoneHVAC:LowTemperatureRadiant:VariableFlow. In E+, this object appears on both the //zonehvac:equipmentlist and the branch. In OpenStudio, this object was broken into 2 objects: //ZoneHVACBaseboardConvectiveWater and CoilHeatingWaterBaseboard. The ZoneHVAC goes onto the zone and //has a child coil that goes onto the plantloop. In order to get the correct translation to E+, we need //to put the name of the containing ZoneHVACBaseboardConvectiveWater onto the branch. if (boost::optional<CoilHeatingLowTempRadiantConstFlow> coilHLRC = modelObject.optionalCast<CoilHeatingLowTempRadiantConstFlow>()) { if (boost::optional<ZoneHVACComponent> znLowTempRadConst = coilHLRC->containingZoneHVACComponent()) { //translate and map containingZoneHVACBBConvWater if (boost::optional<IdfObject> idfZnLowTempRadConst = this->translateAndMapModelObject(*znLowTempRadConst)) { //Get the name and the idd object from the idf object version of this objectName = idfZnLowTempRadConst->name().get(); iddType = idfZnLowTempRadConst->iddObject().name(); } } } if (boost::optional<CoilCoolingLowTempRadiantConstFlow> coilCLRC = modelObject.optionalCast<CoilCoolingLowTempRadiantConstFlow>()) { if (boost::optional<ZoneHVACComponent> znLowTempRadConst = coilCLRC->containingZoneHVACComponent()) { //translate and map containingZoneHVACBBConvWater if (boost::optional<IdfObject> idfZnLowTempRadConst = this->translateAndMapModelObject(*znLowTempRadConst)) { //Get the name and the idd object from the idf object version of this objectName = idfZnLowTempRadConst->name().get(); iddType = idfZnLowTempRadConst->iddObject().name(); } } } if (boost::optional<CoilHeatingLowTempRadiantVarFlow> coilHLRC = modelObject.optionalCast<CoilHeatingLowTempRadiantVarFlow>()) { if (boost::optional<ZoneHVACComponent> znLowTempRadVar = coilHLRC->containingZoneHVACComponent()) { //translate and map containingZoneHVACBBConvWater if (boost::optional<IdfObject> idfZnLowTempRadVar = this->translateAndMapModelObject(*znLowTempRadVar)) { //Get the name and the idd object from the idf object version of this objectName = idfZnLowTempRadVar->name().get(); iddType = idfZnLowTempRadVar->iddObject().name(); } } } if (boost::optional<CoilCoolingLowTempRadiantVarFlow> coilCLRC = modelObject.optionalCast<CoilCoolingLowTempRadiantVarFlow>()) { if (boost::optional<ZoneHVACComponent> znLowTempRadVar = coilCLRC->containingZoneHVACComponent()) { //translate and map containingZoneHVACBBConvWater if (boost::optional<IdfObject> idfZnLowTempRadVar = this->translateAndMapModelObject(*znLowTempRadVar)) { //Get the name and the idd object from the idf object version of this objectName = idfZnLowTempRadVar->name().get(); iddType = idfZnLowTempRadVar->iddObject().name(); } } } //special case for Generator:MicroTurbine. //In OpenStudio, this object was broken into 2 objects: //GeneratorMicroTurbine and GeneratorMicroTurbineHeatRecovery. //The GeneratorMicroTurbineHeatRecovery goes onto the plantloop. In order to get the correct translation to E+, we need //to put the name of the linked GeneratorMicroTurbine onto the branch. if (boost::optional<GeneratorMicroTurbineHeatRecovery> mchpHR = modelObject.optionalCast<GeneratorMicroTurbineHeatRecovery>()) { if (boost::optional<GeneratorMicroTurbine> mchp = mchpHR->generatorMicroTurbine()) { //translate and map containingZoneHVACBBConvWater if (boost::optional<IdfObject> idfmchp = this->translateAndMapModelObject(*mchp)) { //Get the name and the idd object from the idf object version of this objectName = idfmchp->name().get(); iddType = idfmchp->iddObject().name(); } } } } else if (auto waterToAirComponent = modelObject.optionalCast<WaterToAirComponent>()) { if (loop.optionalCast<PlantLoop>()) { inletNode = waterToAirComponent->waterInletModelObject()->optionalCast<Node>(); outletNode = waterToAirComponent->waterOutletModelObject()->optionalCast<Node>(); } else { inletNode = waterToAirComponent->airInletModelObject()->optionalCast<Node>(); outletNode = waterToAirComponent->airOutletModelObject()->optionalCast<Node>(); } } else if (auto waterToWaterComponent = modelObject.optionalCast<WaterToWaterComponent>()) { // Special case for CentralHeatPump. // Unlike other WaterToWaterComponent with a tertiary loop (ChillerAbsorption, ChillerAbsorptionIndirect, ChillerElectricEIR, ChillerElectricReformulatedEIR) which all have // tertiary loop = demand side (so 2 demand side loops and one supply), CentralHeatPumpSystem has tertiary = supply (2 supply side and 1 // demand side loops) if (auto central_hp = modelObject.optionalCast<CentralHeatPumpSystem>()) { auto coolingLoop = central_hp->coolingPlantLoop(); auto heatingLoop = central_hp->heatingPlantLoop(); auto sourceLoop = central_hp->sourcePlantLoop(); // supply = cooling Loop if (loop.handle() == coolingLoop->handle()) { inletNode = waterToWaterComponent->supplyInletModelObject()->optionalCast<Node>(); outletNode = waterToWaterComponent->supplyOutletModelObject()->optionalCast<Node>(); // tertiary = heating loop } else if (loop.handle() == heatingLoop->handle()) { inletNode = waterToWaterComponent->tertiaryInletModelObject()->optionalCast<Node>(); outletNode = waterToWaterComponent->tertiaryOutletModelObject()->optionalCast<Node>(); // demand = source loop } else if (loop.handle() == sourceLoop->handle()) { inletNode = waterToWaterComponent->demandInletModelObject()->optionalCast<Node>(); outletNode = waterToWaterComponent->demandOutletModelObject()->optionalCast<Node>(); } // Regular case } else if (isSupplyBranch) { inletNode = waterToWaterComponent->supplyInletModelObject()->optionalCast<Node>(); outletNode = waterToWaterComponent->supplyOutletModelObject()->optionalCast<Node>(); } else { if (auto tertiaryInletModelObject = waterToWaterComponent->tertiaryInletModelObject()) { if (auto tertiaryInletNode = tertiaryInletModelObject->optionalCast<Node>()) { if (loop.demandComponent(tertiaryInletNode->handle())) { inletNode = tertiaryInletNode; if (auto tertiaryOutletModelObject = waterToWaterComponent->tertiaryOutletModelObject()) { outletNode = tertiaryOutletModelObject->optionalCast<Node>(); } } } } if (!inletNode) { inletNode = waterToWaterComponent->demandInletModelObject()->optionalCast<Node>(); outletNode = waterToWaterComponent->demandOutletModelObject()->optionalCast<Node>(); } } //special case for WaterHeater:HeatPump. In E+, this object appears on both the //zonehvac:equipmentlist and the branch. In OpenStudio the tank (WaterHeater:Mixed) //is attached to the plant and the WaterHeaterHeatPump is connected to the zone and zonehvac equipment list. //Here we resolve all of that since it is the WaterHeaterHeatPump that must show up on both if (auto tank = modelObject.optionalCast<WaterHeaterMixed>()) { // containingZoneHVACComponent can be WaterHeaterHeatPump if (auto hpwh = tank->containingZoneHVACComponent()) { //translate and map containingZoneHVAC if (auto hpwhIDF = translateAndMapModelObject(hpwh.get())) { //Get the name and the idd object from the idf object version of this objectName = hpwhIDF->name().get(); iddType = hpwhIDF->iddObject().name(); } } } if (auto tank = modelObject.optionalCast<WaterHeaterStratified>()) { // containingZoneHVACComponent can be WaterHeaterHeatPump if (auto hpwh = tank->containingZoneHVACComponent()) { //translate and map containingZoneHVAC if (auto hpwhIDF = translateAndMapModelObject(hpwh.get())) { //Get the name and the idd object from the idf object version of this objectName = hpwhIDF->name().get(); iddType = hpwhIDF->iddObject().name(); } } } } else if (auto oaSystem = modelObject.optionalCast<AirLoopHVACOutdoorAirSystem>()) { inletNode = oaSystem->returnAirModelObject()->optionalCast<Node>(); outletNode = oaSystem->mixedAirModelObject()->optionalCast<Node>(); } else if (auto unitary = modelObject.optionalCast<ZoneHVACComponent>()) { inletNode = unitary->inletNode()->optionalCast<Node>(); outletNode = unitary->outletNode()->optionalCast<Node>(); } if (inletNode && outletNode) { IdfExtensibleGroup eg = branchIdfObject.pushExtensibleGroup(); eg.setString(BranchExtensibleFields::ComponentObjectType, iddType); eg.setString(BranchExtensibleFields::ComponentName, objectName); eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNode->name().get()); eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNode->name().get()); } i++; } } return branchIdfObject; } boost::optional<IdfObject> ForwardTranslator::translatePlantLoop(PlantLoop& plantLoop) { // Create a new IddObjectType::PlantLoop IdfObject idfObject(IddObjectType::PlantLoop); m_idfObjects.push_back(idfObject); for (LifeCycleCost lifeCycleCost : plantLoop.lifeCycleCosts()) { translateAndMapModelObject(lifeCycleCost); } OptionalModelObject temp; boost::optional<std::string> s; boost::optional<double> value; // Name if ((s = plantLoop.name())) { idfObject.setName(s.get()); } // Fluid Type if ((s = plantLoop.fluidType())) { if (istringEqual(s.get(), "PropyleneGlycol") || istringEqual(s.get(), "EthyleneGlycol")) { idfObject.setString(PlantLoopFields::FluidType, "UserDefinedFluidType"); boost::optional<int> gc = plantLoop.glycolConcentration(); if (gc) { boost::optional<IdfObject> fluidProperties = createFluidProperties(s.get(), gc.get()); if (fluidProperties) { boost::optional<std::string> fluidPropertiesName = fluidProperties->getString(FluidProperties_NameFields::FluidName, true); if (fluidPropertiesName) { idfObject.setString(PlantLoopFields::UserDefinedFluidType, fluidPropertiesName.get()); } } } } else { idfObject.setString(PlantLoopFields::FluidType, s.get()); } } // Loop Temperature Setpoint Node Name if (boost::optional<Node> node = plantLoop.loopTemperatureSetpointNode()) { idfObject.setString(PlantLoopFields::LoopTemperatureSetpointNodeName, node->name().get()); } // Maximum Loop Temperature if ((value = plantLoop.maximumLoopTemperature())) { idfObject.setDouble(PlantLoopFields::MaximumLoopTemperature, value.get()); } // Minimum Loop Temperature if ((value = plantLoop.minimumLoopTemperature())) { idfObject.setDouble(PlantLoopFields::MinimumLoopTemperature, value.get()); } // Maximum Loop Flow Rate if (plantLoop.isMaximumLoopFlowRateAutosized()) { idfObject.setString(PlantLoopFields::MaximumLoopFlowRate, "Autosize"); } else if ((value = plantLoop.maximumLoopFlowRate())) { idfObject.setDouble(PlantLoopFields::MaximumLoopFlowRate, value.get()); } // Minimum Loop Flow Rate if (plantLoop.isMinimumLoopFlowRateAutosized()) { idfObject.setString(PlantLoopFields::MinimumLoopFlowRate, "Autosize"); } else if ((value = plantLoop.minimumLoopFlowRate())) { idfObject.setDouble(PlantLoopFields::MinimumLoopFlowRate, value.get()); } // LoadDistributionScheme { auto scheme = plantLoop.loadDistributionScheme(); idfObject.setString(PlantLoopFields::LoadDistributionScheme, scheme); } // AvailabilityManagerAssignmentList { // The AvailabilityManagerAssignment list is translated by itself, we just need to set its name on the right IDF field AvailabilityManagerAssignmentList avmList = plantLoop.getImpl<openstudio::model::detail::PlantLoop_Impl>()->availabilityManagerAssignmentList(); // If the avmList isn't empty of just with an HybridVentilation, it should have been translated if (boost::optional<IdfObject> _avmList = this->translateAndMapModelObject(avmList)) { idfObject.setString(PlantLoopFields::AvailabilityManagerListName, _avmList->name().get()); } } // PlantLoopDemandCalculationScheme { auto spms = plantLoop.supplyOutletNode().setpointManagers(); if (subsetCastVector<model::SetpointManagerScheduledDualSetpoint>(spms).empty()) { idfObject.setString(PlantLoopFields::PlantLoopDemandCalculationScheme, "SingleSetpoint"); } else { idfObject.setString(PlantLoopFields::PlantLoopDemandCalculationScheme, "DualSetpointDeadband"); } } // Plant Loop Volume if (plantLoop.isPlantLoopVolumeAutocalculated()) { idfObject.setString(PlantLoopFields::PlantLoopVolume, "Autocalculate"); } else if ((value = plantLoop.plantLoopVolume())) { idfObject.setDouble(PlantLoopFields::PlantLoopVolume, value.get()); } // Common Pipe Simulation if ((s = plantLoop.commonPipeSimulation())) { idfObject.setString(PlantLoopFields::CommonPipeSimulation, s.get()); } // Inlet/Outlet Nodes idfObject.setString(PlantLoopFields::PlantSideInletNodeName, plantLoop.supplyInletNode().name().get()); idfObject.setString(PlantLoopFields::PlantSideOutletNodeName, plantLoop.supplyOutletNode().name().get()); idfObject.setString(PlantLoopFields::DemandSideInletNodeName, plantLoop.demandInletNode().name().get()); idfObject.setString(PlantLoopFields::DemandSideOutletNodeName, plantLoop.demandOutletNode().name().get()); auto supplyComponents = plantLoop.supplyComponents(); SizingPlant sizingPlant = plantLoop.sizingPlant(); translateAndMapModelObject(sizingPlant); // Mark where we want the plant operation schemes to go // Don't actually translate yet because we don't want the components to show up yet // auto operationSchemeLocation = std::distance(m_idfObjects.begin(),m_idfObjects.end()); // Supply Side IdfObject _supplyBranchList(IddObjectType::BranchList); _supplyBranchList.setName(plantLoop.name().get() + " Supply Branches"); _supplyBranchList.clearExtensibleGroups(); m_idfObjects.push_back(_supplyBranchList); idfObject.setString(PlantLoopFields::PlantSideBranchListName, _supplyBranchList.name().get()); IdfObject _supplyConnectorList(IddObjectType::ConnectorList); _supplyConnectorList.setName(plantLoop.name().get() + " Supply Connector List"); m_idfObjects.push_back(_supplyConnectorList); idfObject.setString(PlantLoopFields::PlantSideConnectorListName, _supplyConnectorList.name().get()); Splitter supplySplitter = plantLoop.supplySplitter(); Mixer supplyMixer = plantLoop.supplyMixer(); Node supplyInletNode = plantLoop.supplyInletNode(); Node supplyOutletNode = plantLoop.supplyOutletNode(); IdfObject _supplySplitter(IddObjectType::Connector_Splitter); _supplySplitter.clearExtensibleGroups(); _supplySplitter.setName(plantLoop.name().get() + " Supply Splitter"); m_idfObjects.push_back(_supplySplitter); ExtensibleIndex ei2(0, 0); ei2.group = 0; ei2.field = ConnectorListExtensibleFields::ConnectorObjectType; _supplyConnectorList.setString(_supplyConnectorList.iddObject().index(ei2), _supplySplitter.iddObject().name()); ei2.field = ConnectorListExtensibleFields::ConnectorName; _supplyConnectorList.setString(_supplyConnectorList.iddObject().index(ei2), _supplySplitter.name().get()); IdfObject _supplyMixer(IddObjectType::Connector_Mixer); _supplyMixer.clearExtensibleGroups(); _supplyMixer.setName(plantLoop.name().get() + " Supply Mixer"); m_idfObjects.push_back(_supplyMixer); ei2.group = 1; ei2.field = ConnectorListExtensibleFields::ConnectorObjectType; _supplyConnectorList.setString(_supplyConnectorList.iddObject().index(ei2), _supplyMixer.iddObject().name()); ei2.field = ConnectorListExtensibleFields::ConnectorName; _supplyConnectorList.setString(_supplyConnectorList.iddObject().index(ei2), _supplyMixer.name().get()); // Supply inlet branch IdfObject _supplyInletBranch(IddObjectType::Branch); _supplyInletBranch.setName(plantLoop.name().get() + " Supply Inlet Branch"); _supplyInletBranch.clearExtensibleGroups(); IdfExtensibleGroup eg = _supplyBranchList.pushExtensibleGroup(); eg.setString(BranchListExtensibleFields::BranchName, _supplyInletBranch.name().get()); _supplySplitter.setString(Connector_SplitterFields::InletBranchName, _supplyInletBranch.name().get()); m_idfObjects.push_back(_supplyInletBranch); std::vector<ModelObject> supplyInletModelObjects; supplyInletModelObjects = plantLoop.supplyComponents(supplyInletNode, supplySplitter); OS_ASSERT(supplyInletModelObjects.size() >= 2); if (supplyInletModelObjects.size() > 2u) { populateBranch(_supplyInletBranch, supplyInletModelObjects, plantLoop, true); } else { IdfObject pipe(IddObjectType::Pipe_Adiabatic); pipe.setName(plantLoop.name().get() + " Supply Inlet Pipe"); m_idfObjects.push_back(pipe); std::string inletNodeName = plantLoop.supplyInletNode().name().get(); std::string outletNodeName = plantLoop.name().get() + " Supply Inlet Pipe Node"; pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName); pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName); IdfExtensibleGroup eg = _supplyInletBranch.pushExtensibleGroup(); eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name()); eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get()); eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName); eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName); } // Populate supply equipment branches std::vector<model::ModelObject> splitterOutletObjects = supplySplitter.outletModelObjects(); std::vector<model::ModelObject> mixerInletObjects = supplyMixer.inletModelObjects(); auto it2 = mixerInletObjects.begin(); unsigned i = 0; for (auto& splitterOutletObject : splitterOutletObjects) { i++; std::stringstream ss; ss << i; std::string istring = ss.str(); model::HVACComponent comp1 = splitterOutletObject.optionalCast<model::HVACComponent>().get(); model::HVACComponent comp2 = it2->optionalCast<model::HVACComponent>().get(); std::vector<model::ModelObject> allComponents = plantLoop.supplyComponents(comp1, comp2); IdfObject _equipmentBranch(IddObjectType::Branch); _equipmentBranch.clearExtensibleGroups(); _equipmentBranch.setName(plantLoop.name().get() + " Supply Branch " + istring); m_idfObjects.push_back(_equipmentBranch); eg = _supplySplitter.pushExtensibleGroup(); eg.setString(Connector_SplitterExtensibleFields::OutletBranchName, _equipmentBranch.name().get()); eg = _supplyMixer.pushExtensibleGroup(); eg.setString(Connector_MixerExtensibleFields::InletBranchName, _equipmentBranch.name().get()); eg = _supplyBranchList.pushExtensibleGroup(); eg.setString(BranchListExtensibleFields::BranchName, _equipmentBranch.name().get()); if (allComponents.size() > 2u) { populateBranch(_equipmentBranch, allComponents, plantLoop, true); } else { IdfObject pipe(IddObjectType::Pipe_Adiabatic); pipe.setName(plantLoop.name().get() + " Supply Branch " + istring + " Pipe"); m_idfObjects.push_back(pipe); std::string inletNodeName = pipe.name().get() + " Inlet Node"; std::string outletNodeName = pipe.name().get() + " Outlet Node"; pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName); pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName); IdfExtensibleGroup eg = _equipmentBranch.pushExtensibleGroup(); eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name()); eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get()); eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName); eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName); } ++it2; } // Populate supply outlet branch IdfObject _supplyOutletBranch(IddObjectType::Branch); _supplyOutletBranch.setName(plantLoop.name().get() + " Supply Outlet Branch"); _supplyOutletBranch.clearExtensibleGroups(); eg = _supplyBranchList.pushExtensibleGroup(); eg.setString(BranchListExtensibleFields::BranchName, _supplyOutletBranch.name().get()); _supplyMixer.setString(Connector_MixerFields::OutletBranchName, _supplyOutletBranch.name().get()); m_idfObjects.push_back(_supplyOutletBranch); std::vector<ModelObject> supplyOutletModelObjects; supplyOutletModelObjects = plantLoop.supplyComponents(supplyMixer, supplyOutletNode); OS_ASSERT(supplyOutletModelObjects.size() >= 2); if (supplyOutletModelObjects.size() > 2u) { populateBranch(_supplyOutletBranch, supplyOutletModelObjects, plantLoop, true); } else { IdfObject pipe(IddObjectType::Pipe_Adiabatic); pipe.setName(plantLoop.name().get() + " Supply Outlet Pipe"); m_idfObjects.push_back(pipe); std::string inletNodeName = plantLoop.name().get() + " Supply Outlet Pipe Node"; std::string outletNodeName = plantLoop.supplyOutletNode().name().get(); pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName); pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName); IdfExtensibleGroup eg = _supplyOutletBranch.pushExtensibleGroup(); eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name()); eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get()); eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName); eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName); } // Demand Side IdfObject _demandBranchList(IddObjectType::BranchList); _demandBranchList.setName(plantLoop.name().get() + " Demand Branches"); _demandBranchList.clearExtensibleGroups(); m_idfObjects.push_back(_demandBranchList); idfObject.setString(PlantLoopFields::DemandSideBranchListName, _demandBranchList.name().get()); IdfObject _demandConnectorList(IddObjectType::ConnectorList); _demandConnectorList.setName(plantLoop.name().get() + " Demand Connector List"); m_idfObjects.push_back(_demandConnectorList); idfObject.setString(PlantLoopFields::DemandSideConnectorListName, _demandConnectorList.name().get()); Splitter demandSplitter = plantLoop.demandSplitter(); Mixer demandMixer = plantLoop.demandMixer(); Node demandInletNode = plantLoop.demandInletNode(); Node demandOutletNode = plantLoop.demandOutletNode(); IdfObject _demandSplitter(IddObjectType::Connector_Splitter); _demandSplitter.clearExtensibleGroups(); _demandSplitter.setName(plantLoop.name().get() + " Demand Splitter"); m_idfObjects.push_back(_demandSplitter); ExtensibleIndex ei(0, 0); ei.group = 0; ei.field = ConnectorListExtensibleFields::ConnectorObjectType; _demandConnectorList.setString(_demandConnectorList.iddObject().index(ei), _demandSplitter.iddObject().name()); ei.field = ConnectorListExtensibleFields::ConnectorName; _demandConnectorList.setString(_demandConnectorList.iddObject().index(ei), _demandSplitter.name().get()); IdfObject _demandMixer(IddObjectType::Connector_Mixer); _demandMixer.clearExtensibleGroups(); _demandMixer.setName(plantLoop.name().get() + " Demand Mixer"); m_idfObjects.push_back(_demandMixer); ei.group = 1; ei.field = ConnectorListExtensibleFields::ConnectorObjectType; _demandConnectorList.setString(_demandConnectorList.iddObject().index(ei), _demandMixer.iddObject().name()); ei.field = ConnectorListExtensibleFields::ConnectorName; _demandConnectorList.setString(_demandConnectorList.iddObject().index(ei), _demandMixer.name().get()); // Demand inlet branch IdfObject _demandInletBranch(IddObjectType::Branch); _demandInletBranch.setName(plantLoop.name().get() + " Demand Inlet Branch"); _demandInletBranch.clearExtensibleGroups(); eg = _demandBranchList.pushExtensibleGroup(); eg.setString(BranchListExtensibleFields::BranchName, _demandInletBranch.name().get()); _demandSplitter.setString(Connector_SplitterFields::InletBranchName, _demandInletBranch.name().get()); m_idfObjects.push_back(_demandInletBranch); std::vector<ModelObject> demandInletModelObjects; demandInletModelObjects = plantLoop.demandComponents(demandInletNode, demandSplitter); OS_ASSERT(demandInletModelObjects.size() >= 2u); if (demandInletModelObjects.size() > 2u) { populateBranch(_demandInletBranch, demandInletModelObjects, plantLoop, false); } else { IdfObject pipe(IddObjectType::Pipe_Adiabatic); pipe.setName(plantLoop.name().get() + " Demand Inlet Pipe"); m_idfObjects.push_back(pipe); std::string inletNodeName = plantLoop.demandInletNode().name().get(); std::string outletNodeName = plantLoop.name().get() + " Demand Inlet Pipe Node"; pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName); pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName); IdfExtensibleGroup eg = _demandInletBranch.pushExtensibleGroup(); eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name()); eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get()); eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName); eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName); } // Populate equipment branches splitterOutletObjects = demandSplitter.outletModelObjects(); mixerInletObjects = demandMixer.inletModelObjects(); it2 = mixerInletObjects.begin(); i = 0; for (auto& splitterOutletObject : splitterOutletObjects) { i++; std::stringstream ss; ss << i; std::string istring = ss.str(); model::HVACComponent comp1 = splitterOutletObject.optionalCast<model::HVACComponent>().get(); model::HVACComponent comp2 = it2->optionalCast<model::HVACComponent>().get(); std::vector<model::ModelObject> allComponents = plantLoop.demandComponents(comp1, comp2); IdfObject _equipmentBranch(IddObjectType::Branch); _equipmentBranch.clearExtensibleGroups(); _equipmentBranch.setName(plantLoop.name().get() + " Demand Branch " + istring); m_idfObjects.push_back(_equipmentBranch); eg = _demandSplitter.pushExtensibleGroup(); eg.setString(Connector_SplitterExtensibleFields::OutletBranchName, _equipmentBranch.name().get()); eg = _demandMixer.pushExtensibleGroup(); eg.setString(Connector_MixerExtensibleFields::InletBranchName, _equipmentBranch.name().get()); eg = _demandBranchList.pushExtensibleGroup(); eg.setString(BranchListExtensibleFields::BranchName, _equipmentBranch.name().get()); if (allComponents.size() > 2u) { populateBranch(_equipmentBranch, allComponents, plantLoop, false); } else { IdfObject pipe(IddObjectType::Pipe_Adiabatic); pipe.setName(plantLoop.name().get() + " Demand Branch " + istring + " Pipe"); m_idfObjects.push_back(pipe); std::string inletNodeName = pipe.name().get() + " Inlet Node"; std::string outletNodeName = pipe.name().get() + " Outlet Node"; pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName); pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName); IdfExtensibleGroup eg = _equipmentBranch.pushExtensibleGroup(); eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name()); eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get()); eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName); eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName); } ++it2; } // Install a bypass branch with a pipe if (splitterOutletObjects.size() > 0u) { IdfObject _equipmentBranch(IddObjectType::Branch); _equipmentBranch.clearExtensibleGroups(); _equipmentBranch.setName(plantLoop.name().get() + " Demand Bypass Branch"); m_idfObjects.push_back(_equipmentBranch); eg = _demandSplitter.pushExtensibleGroup(); eg.setString(Connector_SplitterExtensibleFields::OutletBranchName, _equipmentBranch.name().get()); eg = _demandMixer.pushExtensibleGroup(); eg.setString(Connector_MixerExtensibleFields::InletBranchName, _equipmentBranch.name().get()); eg = _demandBranchList.pushExtensibleGroup(); eg.setString(BranchListExtensibleFields::BranchName, _equipmentBranch.name().get()); IdfObject pipe(IddObjectType::Pipe_Adiabatic); pipe.setName(plantLoop.name().get() + " Demand Bypass Pipe"); m_idfObjects.push_back(pipe); std::string inletNodeName = pipe.name().get() + " Inlet Node"; std::string outletNodeName = pipe.name().get() + " Outlet Node"; pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName); pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName); IdfExtensibleGroup eg = _equipmentBranch.pushExtensibleGroup(); eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name()); eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get()); eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName); eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName); } // Populate demand outlet branch IdfObject _demandOutletBranch(IddObjectType::Branch); _demandOutletBranch.setName(plantLoop.name().get() + " Demand Outlet Branch"); _demandOutletBranch.clearExtensibleGroups(); eg = _demandBranchList.pushExtensibleGroup(); eg.setString(BranchListExtensibleFields::BranchName, _demandOutletBranch.name().get()); _demandMixer.setString(Connector_MixerFields::OutletBranchName, _demandOutletBranch.name().get()); m_idfObjects.push_back(_demandOutletBranch); std::vector<ModelObject> demandOutletModelObjects; demandOutletModelObjects = plantLoop.demandComponents(demandMixer, demandOutletNode); OS_ASSERT(demandOutletModelObjects.size() >= 2u); if (demandOutletModelObjects.size() > 2u) { populateBranch(_demandOutletBranch, demandOutletModelObjects, plantLoop, false); } else { IdfObject pipe(IddObjectType::Pipe_Adiabatic); pipe.setName(plantLoop.name().get() + " Demand Outlet Pipe"); m_idfObjects.push_back(pipe); std::string inletNodeName = plantLoop.name().get() + " Demand Outlet Pipe Node"; std::string outletNodeName = plantLoop.demandOutletNode().name().get(); pipe.setString(Pipe_AdiabaticFields::InletNodeName, inletNodeName); pipe.setString(Pipe_AdiabaticFields::OutletNodeName, outletNodeName); IdfExtensibleGroup eg = _demandOutletBranch.pushExtensibleGroup(); eg.setString(BranchExtensibleFields::ComponentObjectType, pipe.iddObject().name()); eg.setString(BranchExtensibleFields::ComponentName, pipe.name().get()); eg.setString(BranchExtensibleFields::ComponentInletNodeName, inletNodeName); eg.setString(BranchExtensibleFields::ComponentOutletNodeName, outletNodeName); } // Operation Scheme // auto opSchemeStart = m_idfObjects.end(); const auto& operationSchemes = translatePlantEquipmentOperationSchemes(plantLoop); OS_ASSERT(operationSchemes); idfObject.setString(PlantLoopFields::PlantEquipmentOperationSchemeName, operationSchemes->name().get()); // auto opSchemeEnd = m_idfObjects.end(); //std::vector<IdfObject> opSchemeObjects(opSchemeStart,opSchemeEnd); //m_idfObjects.erase(opSchemeStart,opSchemeEnd); //m_idfObjects.insert(m_idfObjects.begin() + operationSchemeLocation,opSchemeObjects.begin(),opSchemeObjects.end()); return boost::optional<IdfObject>(idfObject); } } // namespace energyplus } // namespace openstudio
52.597665
182
0.71306
muehleisen
c1b1b4df493e9cec2f39abd06ab30bd1b5f951d8
1,146
cpp
C++
codeground/8. 블럭 없애기.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
null
null
null
codeground/8. 블럭 없애기.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
null
null
null
codeground/8. 블럭 없애기.cpp
Jeongseo21/Algorithm-1
1bce4f3d2328c3b3e24b9d7772fca43090a285e1
[ "MIT" ]
null
null
null
/* * codeground - Practice - 연습문제 - 8. 블럭 없애기 * 문제 : https://www.codeground.org/practice/practiceProblemList * 시간복잡도 : O(N) * 알고리즘 : DP */ #include <iostream> #include <vector> #include <algorithm> #define inf 1e9 using namespace std; int solve() { int n; cin >> n; vector<int> arr(n + 2, 0); for (int i = 1; i <= n; i++) scanf("%d", &arr[i]); vector<int> d(n + 2, inf);//d[i] = i번째가 없어질 때까지 걸리는 시간 d[0] = d[n + 1] = 0; //없어질 때까지 걸리는 시간은 양쪽의 영향을 받지만 한 번에 이를 탐색하긴 어려우므로 //왼쪽과 자신, 자신과 오른쪽을 탐색 두 번으로 각각 구해서 d배열을 채운다. for (int i = 1; i <= n; i++)//(왼쪽, 자신) 비교 d[i] = min(d[i - 1] + 1, arr[i]);//d[i] = min(왼쪽이 없어지는데 걸리는 시간 + 1, 높이가 없어지는데 걸리는 시간) for (int i = n; i >= 1; i--) //(자신, 오른쪽) 비교 d[i] = min(d[i], min(d[i + 1] + 1, arr[i])); int ans = 0; //d배열의 최대값 for (int i = 1; i <= n; i++) ans = max(ans, d[i]); return ans; } int main(int argc, char** argv) { int T, test_case; int Answer; cin >> T; for (test_case = 0; test_case < T; test_case++) { Answer = solve(); cout << "Case #" << test_case + 1 << endl; cout << Answer << endl; } return 0;//Your program should return 0 on normal termination. }
21.222222
87
0.557592
Jeongseo21
c1b7f7dd34eb8411c40fb30e8c598d2f394af34f
16,940
cpp
C++
LibUIDK/WLText.cpp
swjsky/sktminest
42fa47d9ffb0f50a5727e42811e949fff920bec9
[ "MIT" ]
3
2019-12-03T09:04:04.000Z
2021-01-29T02:03:30.000Z
LibUIDK/WLText.cpp
dushulife/LibUIDK
04e79e64eaadfaa29641c24e9cddd9abde544aac
[ "MIT" ]
null
null
null
LibUIDK/WLText.cpp
dushulife/LibUIDK
04e79e64eaadfaa29641c24e9cddd9abde544aac
[ "MIT" ]
2
2019-09-12T07:49:42.000Z
2019-12-24T22:28:49.000Z
// WLText.cpp : implementation file // #include "stdafx.h" #include "ResourceMgr.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif struct WLTXTMEMBER { WLTXTMEMBER() { int i = 0; for (i = 0; i < 2; ++i) { m_himgBk[i] = NULL; } m_ptBkImageResize.x = m_ptBkImageResize.y = 3; for (i = 0; i < 2; ++i) { m_himgFg[i] = NULL; } m_ptFkImageResize.x = m_ptFkImageResize.y = 3; m_eForegroundAlignHor = FAH_LEFT; m_eForegroundAlignVer = FAV_CENTER; m_rcForegroundMargin.SetRect(0, 0, 0, 0); m_crForegroundMask = RGB(255, 0, 255); for (i = 0; i < 2; ++i) { m_eHorAlignMode[i] = TAH_LEFT; m_eVerAlignMode[i] = TAV_CENTER; } m_uTextFormat = DT_WORDBREAK; m_rcPadding4Text.SetRect(0, 0, 0, 0); // for font and color for (i = 0; i < 2; ++i) { m_hIUIFont[i] = NULL; m_cr[i] = RGB(0, 0, 0); } // for shadow text m_bShadowText = FALSE; m_crTextShadow = RGB(192, 192, 192); m_ptTextShadowOffset = CPoint(1, 1); } int Release() { int i = 0; for (i = 0; i < 2; ++i) { ReleaseIUIImage(m_himgBk[i]); m_himgBk[i] = NULL; } m_ptBkImageResize.x = m_ptBkImageResize.y = 3; for (i = 0; i < 2; ++i) { ReleaseIUIImage(m_himgFg[i]); m_himgFg[i] = NULL; } m_ptFkImageResize.x = m_ptFkImageResize.y = 3; m_eForegroundAlignHor = FAH_LEFT; m_eForegroundAlignVer = FAV_CENTER; m_rcForegroundMargin.SetRect(0, 0, 0, 0); m_crForegroundMask = RGB(255, 0, 255); for (i = 0; i < 2; ++i) { m_eHorAlignMode[i] = TAH_LEFT; m_eVerAlignMode[i] = TAV_CENTER; } m_uTextFormat = DT_WORDBREAK; m_rcPadding4Text.SetRect(0, 0, 0, 0); // for font and color for (i = 0; i < 2; ++i) { ReleaseIUIFontInternal(m_hIUIFont[i]); m_hIUIFont[i] = NULL; m_cr[i] = RGB(0, 0, 0); } // for shadow text m_bShadowText = FALSE; m_crTextShadow = RGB(192, 192, 192); m_ptTextShadowOffset = CPoint(1, 1); return 0; } HIUIIMAGE m_himgBk[2]; CPoint m_ptBkImageResize; HIUIIMAGE m_himgFg[2]; CPoint m_ptFkImageResize; FOREGROUND_ALIGN_HOR m_eForegroundAlignHor; FOREGROUND_ALIGN_VER m_eForegroundAlignVer; CRect m_rcForegroundMargin; COLORREF m_crForegroundMask; TEXT_ALIGN_HOR m_eHorAlignMode[2]; TEXT_ALIGN_VER m_eVerAlignMode[2]; UINT m_uTextFormat; CRect m_rcPadding4Text; // for font HIUIFONT m_hIUIFont[2]; // for color COLORREF m_cr[2]; CToolTipCtrl m_wndToolTip; // for shadow text BOOL m_bShadowText; COLORREF m_crTextShadow; CPoint m_ptTextShadowOffset; }; ////////////////////////////////////////////////////////////////////////// // CWLText CWLText::CWLText() { m_pMember = new WLTXTMEMBER; WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; } CWLText::~CWLText() { if (m_pMember != NULL) { delete (WLTXTMEMBER *)m_pMember; m_pMember = NULL; } } BOOL CWLText::Create(LPCTSTR lpszControlName, DWORD dwStyle, const RECT &rect, CWnd *pParentWnd, UINT nID, CWLWnd *pVirtualParent) { BOOL bRet = CRectCtrl::Create(lpszControlName, dwStyle, rect, pParentWnd, nID, pVirtualParent); if (!bRet) { return FALSE; } return TRUE; } int CWLText::BindStyle(LPCTSTR lpszStyleID) { if (!IsCreated()) { ASSERT(FALSE); return -1; } if (lpszStyleID == NULL) { return -2; } CTRLPROPERTIES *pCtrlProp = CUIMgr::GetStyleItem(STYLET_STATIC, lpszStyleID); return BindStyle(pCtrlProp); } int CWLText::BindStyle(const CTRLPROPERTIES *pCtrlProp) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (!IsCreated()) { ASSERT(FALSE); return -1; } if (pCtrlProp == NULL) { return -2; } CONTROL_TYPE ect = (CONTROL_TYPE)pCtrlProp->m_eControlType; if (ect != CT_STYLE_STATIC && ect != CT_WL_TEXT) { return -3; } TXTPROPERTIES *pWLTxtProp = (TXTPROPERTIES *)pCtrlProp; bool bSpecifyBackgroundImages = pCtrlProp->m_bSpecifyBackgroundImages; if (bSpecifyBackgroundImages) { CString strImageName[1 + COMBINEIMAGESIZE2]; BOOL bCombineImage = TRUE; CTRLPROPERTIES::IUIGetBackground2(pCtrlProp, &bCombineImage, strImageName); if (bCombineImage) { SetBkCombineImage(strImageName[0]); } else { SetBitmap(CONTROL_STATE_UNCHECKED_ND, strImageName[1], strImageName[2]); } for (int i = 0; i < 1 + COMBINEIMAGESIZE2; ++i) { ReleaseIUIImage(strImageName[i]); } SetBkImageResizeMode(pCtrlProp->m_eBkImageResizeMode); SetBkImageResizePoint(pCtrlProp->m_ptImageResize); } // Set foreground if (pWLTxtProp->m_bSpecifyForegroundImages) { CString strImageName[1 + COMBINEIMAGESIZE2]; BOOL bCombineImage = TRUE; CTRLPROPERTIES::IUIGetStaticForeground2(pWLTxtProp, &bCombineImage, strImageName); if (bCombineImage) { SetFgCombineImage(strImageName[0]); } else SetForegroundBitmap(CONTROL_STATE_CHECKED_NORMAL | CONTROL_STATE_CHECKED_DISABLED, strImageName[1], strImageName[2], pWLTxtProp->m_rcPadding4Foreground, pWLTxtProp->m_eForegroundHorAlignMode, pWLTxtProp->m_eForegroundVerAlignMode); } SetTextMultiline(!(bool)pWLTxtProp->m_bNoWrap); SetPathEllipsis(pWLTxtProp->m_bPathEllipsis); SetEndEllipsis(pWLTxtProp->m_bEndEllipsis); SetTextAlignHor(pWLTxtProp->m_eTextHorAlignMode, pWLTxtProp->m_eTextHorAlignMode); SetTextAlignVer(pWLTxtProp->m_eTextVerAlignMode, pWLTxtProp->m_eTextVerAlignMode); COLORREF crN, crD; CTRLPROPERTIES::IUIGetControlColor4(pWLTxtProp, &crN, NULL, NULL, &crD); SetTextColor(crN, crD); // font CString strResFontID[2]; CTRLPROPERTIES::IUIGetControlFont2(pCtrlProp, strResFontID); SetTextFont(CONTROL_STATE_NORMAL | CONTROL_STATE_DISABLED, strResFontID[0], strResFontID[1]); // Use tool tip if (pWLTxtProp->m_bUseToolTip) { SetToolTips(pWLTxtProp->m_strToolTip); } RECT rcMargin = pWLTxtProp->m_rcPadding4Text; SetTextMargin(&rcMargin); // Shadow text if (pWLTxtProp->m_bShadowText) { ShadowText(TRUE); SetTextShadowColor(pWLTxtProp->m_crTextShadow); POINT ptOffset = pWLTxtProp->m_ptTextShadowOffset; SetTextShadowOffset(&ptOffset); } return 0; } int CWLText::ReleaseObject() { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; for (int i = 0; i < 2; ++i) { ReleaseIUIFontInternal(pMember->m_hIUIFont[i]); pMember->m_hIUIFont[i] = NULL; ReleaseIUIImage(pMember->m_himgBk[i]); pMember->m_himgBk[i] = NULL; } return CControlBase::ReleaseObject(); } ////////////////////////////////////////////////////////////////////////// // virtual int CWLText::OnDraw(CDC *pMemDCParent) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (!IsWindowVisible()) { return 1; } if (pMemDCParent == NULL) { return -1; } CRect rcWin; GetWindowRect(rcWin); GetParent()->ScreenToClient(rcWin); POINT ptDrawOffset = {0}; GetDrawOffset(&ptDrawOffset); rcWin.OffsetRect(ptDrawOffset); // Don't draw this control if it's out of the parent CRect rcParent; GetParent()->GetClientRect(rcParent); CRect rcIntersect; rcIntersect.IntersectRect(rcWin, rcParent); if (rcIntersect.IsRectEmpty()) { return 0; } BOOL bEnabled = IsWindowEnabled(); int nImageState = 0; if (!bEnabled) { nImageState = 1; } // Draw background image. if (m_bBkCombine) { if (m_eBkImageResizeMode == IRM_9GRID) { IUIPartNineGridBlt(pMemDCParent->GetSafeHdc(), rcWin, m_himgCombineBk, m_ptBkImageResize, m_lBkImageRepeatX, m_lBkImageRepeatY, 2, nImageState); } else if (m_eBkImageResizeMode == IRM_STRETCH || m_eBkImageResizeMode == IRM_STRETCH_HIGH_QUALITY) { IUIPartStretchBlt(pMemDCParent->GetSafeHdc(), rcWin, m_himgCombineBk, 2, nImageState, m_eBkImageResizeMode); } } else { IUIDrawImage(pMemDCParent->GetSafeHdc(), rcWin, pMember->m_himgBk[nImageState], m_eBkImageResizeMode, m_ptBkImageResize, m_lBkImageRepeatX, m_lBkImageRepeatY); } // Draw foreground image. IUIDrawForeground(pMemDCParent->GetSafeHdc(), rcWin, pMember->m_rcForegroundMargin, pMember->m_himgFg[nImageState], pMember->m_eForegroundAlignHor, pMember->m_eForegroundAlignVer, pMember->m_crForegroundMask, 255); // Draw window's text to background DC. pMemDCParent->SetBkMode(TRANSPARENT); CString strText; GetWindowText(strText); pMember->m_hIUIFont[nImageState]->SafeLoadSavedFont(); DrawFormatText(pMemDCParent->GetSafeHdc(), strText, strText.GetLength(), rcWin, pMember->m_rcPadding4Text, pMember->m_eHorAlignMode[nImageState], pMember->m_eVerAlignMode[nImageState], pMember->m_uTextFormat, pMember->m_hIUIFont[nImageState]->GetSafeHFont(), pMember->m_cr[nImageState], CT_WL_TEXT); return 0; } ////////////////////////////////////////////////////////////////////////// // public int CWLText::SetBitmap(UINT uMask, LPCTSTR lpszImageNameN, LPCTSTR lpszImageNameD, BOOL bRedraw/* = TRUE*/) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; m_bBkCombine = false; IUISetControlImage2(uMask, pMember->m_himgBk, lpszImageNameN, lpszImageNameD); if (bRedraw) { Invalidate(); } return 0; } int CWLText::GetBitmap(UINT uMask, BOOL *pbCombineImage, CString *pstrCombineImageName, CString *pstrImageNameN, CString *pstrImageNameD) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (pstrImageNameN != NULL) { GetImageFileName(pMember->m_himgBk[0], pstrImageNameN); } if (pstrImageNameD != NULL) { GetImageFileName(pMember->m_himgBk[1], pstrImageNameD); } return 0; } void CWLText::SetForegroundBitmap(UINT uMask, LPCTSTR lpszImageNameForegroundN, LPCTSTR lpszImageNameForegroundD, const CRect &rcForegroundMargin, FOREGROUND_ALIGN_HOR eAlignModeHor/* = FAH_LEFT*/, FOREGROUND_ALIGN_VER eAlignModeVer/* = FAV_CENTER*/, COLORREF crMask/* = RGB(255, 0, 255)*/, BOOL bReDraw/* = TRUE*/) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; IUISetControlImage2(uMask, pMember->m_himgFg, lpszImageNameForegroundN, lpszImageNameForegroundD); pMember->m_rcForegroundMargin = rcForegroundMargin; pMember->m_eForegroundAlignHor = eAlignModeHor; pMember->m_eForegroundAlignVer = eAlignModeVer; pMember->m_crForegroundMask = crMask; if (bReDraw) { Invalidate(); } } void CWLText::GetForegroundBitmap(UINT uMask, BOOL *pbCombineImage, CString *pstrCombineImageName, CString *pstrImageNameN, CString *pstrImageNameD, LPRECT lprcForegroundMargin, int *pnAlignModeHor, int *pnAlignModeVer, COLORREF *pcrMask) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (pstrImageNameN != NULL) { GetImageFileName(pMember->m_himgFg[0], pstrImageNameN); } if (pstrImageNameD != NULL) { GetImageFileName(pMember->m_himgFg[1], pstrImageNameD); } if (lprcForegroundMargin != NULL) { *lprcForegroundMargin = pMember->m_rcForegroundMargin; } if (pnAlignModeHor != NULL) { *pnAlignModeHor = pMember->m_eForegroundAlignHor; } if (pnAlignModeVer != NULL) { *pnAlignModeVer = pMember->m_eForegroundAlignVer; } if (pcrMask != NULL) { *pcrMask = pMember->m_crForegroundMask; } } int CWLText::SetTextMultiline(BOOL bMultiline) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (bMultiline) { pMember->m_uTextFormat &= ~DT_SINGLELINE; pMember->m_uTextFormat |= DT_WORDBREAK; } else { pMember->m_uTextFormat &= ~DT_WORDBREAK; pMember->m_uTextFormat |= DT_SINGLELINE; } return 0; } BOOL CWLText::IsTextMultiline() { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; return IsIncludeFlag(pMember->m_uTextFormat, DT_WORDBREAK); } int CWLText::SetPathEllipsis(BOOL bPathEllipsis) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (bPathEllipsis) { pMember->m_uTextFormat |= DT_PATH_ELLIPSIS; } else { pMember->m_uTextFormat &= ~DT_PATH_ELLIPSIS; } return 0; } BOOL CWLText::IsPathEllipsis() const { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; return IsIncludeFlag(pMember->m_uTextFormat, DT_PATH_ELLIPSIS); } int CWLText::SetEndEllipsis(BOOL bEndEllipsis) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (bEndEllipsis) { pMember->m_uTextFormat |= DT_END_ELLIPSIS; } else { pMember->m_uTextFormat &= ~DT_END_ELLIPSIS; } return 0; } BOOL CWLText::IsEndEllipsis() const { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; return IsIncludeFlag(pMember->m_uTextFormat, DT_END_ELLIPSIS); } int CWLText::SetTextAlignHor(TEXT_ALIGN_HOR eHorAlignModeN, TEXT_ALIGN_HOR eHorAlignModeD) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; pMember->m_eHorAlignMode[0] = eHorAlignModeN; pMember->m_eHorAlignMode[1] = eHorAlignModeD; return 0; } int CWLText::GetTextAlignHor(TEXT_ALIGN_HOR *peHorAlignModeN, TEXT_ALIGN_HOR *peHorAlignModeD) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (peHorAlignModeN != NULL) { *peHorAlignModeN = pMember->m_eHorAlignMode[0]; } if (peHorAlignModeD != NULL) { *peHorAlignModeD = pMember->m_eHorAlignMode[1]; } return 0; } int CWLText::SetTextAlignVer(TEXT_ALIGN_VER eVerAlignModeN, TEXT_ALIGN_VER eVerAlignModeD) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; pMember->m_eVerAlignMode[0] = eVerAlignModeN; pMember->m_eVerAlignMode[1] = eVerAlignModeD; return 0; } int CWLText::GetTextAlignVer(TEXT_ALIGN_VER *peVerAlignModeN, TEXT_ALIGN_VER *peVerAlignModeD) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (peVerAlignModeN != NULL) { *peVerAlignModeN = pMember->m_eVerAlignMode[0]; } if (peVerAlignModeD != NULL) { *peVerAlignModeD = pMember->m_eVerAlignMode[1]; } return 0; } int CWLText::SetTextColor(COLORREF crN, COLORREF crD, BOOL bRedraw/* = TRUE*/) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; pMember->m_cr[0] = crN; pMember->m_cr[1] = crD; if (bRedraw) { Invalidate(); } return 0; } int CWLText::GetTextColor(COLORREF *pcrN, COLORREF *pcrD) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (pcrN != NULL) { *pcrN = pMember->m_cr[0]; } if (pcrD != NULL) { *pcrD = pMember->m_cr[1]; } return 0; } int CWLText::SetTextFont(UINT uMask, LPCTSTR lpszFontIDN, LPCTSTR lpszFontIDD) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; IUISetControlFont2(uMask, pMember->m_hIUIFont, lpszFontIDN, lpszFontIDD); return 0; } int CWLText::GetTextFont(UINT uMask, CString *pstrFontIDN, CString *pstrFontIDD) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (pstrFontIDN != NULL) { GetFontResID(pMember->m_hIUIFont[0], pstrFontIDN); } if (pstrFontIDD != NULL) { GetFontResID(pMember->m_hIUIFont[1], pstrFontIDD); } return 0; } int CWLText::SetToolTips(LPCTSTR lpszToolTips) { return 0; } CToolTipCtrl *CWLText::GetToolTipCtrl() { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; return &pMember->m_wndToolTip; } int CWLText::SetTextFont(const LOGFONT *lf) { return 0; } int CWLText::GetTextFont(LOGFONT *lf) const { return 0; } int CWLText::SetTextMargin(LPCRECT lpRect) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (lpRect == NULL) { return -1; } pMember->m_rcPadding4Text = *lpRect; return 0; } int CWLText::GetTextMargin(LPRECT lpRect) const { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; if (lpRect == NULL) { return -1; } *lpRect = pMember->m_rcPadding4Text; return 0; } int CWLText::ShadowText(BOOL bShadow) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; pMember->m_bShadowText = bShadow; return 0; } BOOL CWLText::IsShadowText() const { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; return pMember->m_bShadowText; } int CWLText::SetTextShadowColor(COLORREF crShadow) { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; pMember->m_crTextShadow = crShadow; return 0; } COLORREF CWLText::GetTextShadowColor() const { WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; return pMember->m_crTextShadow; } int CWLText::SetTextShadowOffset(LPPOINT lpptOffset) { if (lpptOffset == NULL) { return -1; } WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; pMember->m_ptTextShadowOffset = *lpptOffset; return 0; } int CWLText::GetTextShadowOffset(LPPOINT lpptOffset) const { if (lpptOffset == NULL) { return -1; } WLTXTMEMBER *pMember = (WLTXTMEMBER *)m_pMember; *lpptOffset = pMember->m_ptTextShadowOffset; return 0; } LRESULT CWLText::WLWindowProc(UINT message, WPARAM wParam, LPARAM lParam) { if (message == WM_WLDESTROY) { ReleaseObject(); } return CRectCtrl::WLWindowProc(message, wParam, lParam); }
21.690141
97
0.683353
swjsky
c1bc9d29f4115276986b581e6476527298fa8249
25,939
hpp
C++
src/cppad.git/include/cppad/example/eigen_mat_mul.hpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
1
2019-11-05T02:23:47.000Z
2019-11-05T02:23:47.000Z
src/cppad.git/include/cppad/example/eigen_mat_mul.hpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
null
null
null
src/cppad.git/include/cppad/example/eigen_mat_mul.hpp
yinzixuan126/my_udacity
cada1bc047cd21282b008a0eb85a1df52fd94034
[ "MIT" ]
1
2019-11-05T02:23:51.000Z
2019-11-05T02:23:51.000Z
# ifndef CPPAD_EXAMPLE_EIGEN_MAT_MUL_HPP # define CPPAD_EXAMPLE_EIGEN_MAT_MUL_HPP /* -------------------------------------------------------------------------- CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-18 Bradley M. Bell CppAD is distributed under the terms of the Eclipse Public License Version 2.0. This Source Code may also be made available under the following Secondary License when the conditions for such availability set forth in the Eclipse Public License, Version 2.0 are satisfied: GNU General Public License, Version 2.0 or later. ---------------------------------------------------------------------------- */ /* $begin atomic_eigen_mat_mul.hpp$$ $spell Eigen Taylor nr nc $$ $section Atomic Eigen Matrix Multiply Class$$ $head See Also$$ $cref atomic_mat_mul.hpp$$ $head Purpose$$ Construct an atomic operation that computes the matrix product, $latex R = A \times \B{R}$$ for any positive integers $latex r$$, $latex m$$, $latex c$$, and any $latex A \in \B{R}^{r \times m}$$, $latex B \in \B{R}^{m \times c}$$. $head Matrix Dimensions$$ This example puts the matrix dimensions in the atomic function arguments, instead of the $cref/constructor/atomic_ctor/$$, so that they can be different for different calls to the atomic function. These dimensions are: $table $icode nr_left$$ $cnext number of rows in the left matrix; i.e, $latex r$$ $rend $icode n_middle$$ $cnext rows in the left matrix and columns in right; i.e, $latex m$$ $rend $icode nc_right$$ $cnext number of columns in the right matrix; i.e., $latex c$$ $tend $head Theory$$ $subhead Forward$$ For $latex k = 0 , \ldots $$, the $th k$$ order Taylor coefficient $latex R_k$$ is given by $latex \[ R_k = \sum_{\ell = 0}^{k} A_\ell B_{k-\ell} \] $$ $subhead Product of Two Matrices$$ Suppose $latex \bar{E}$$ is the derivative of the scalar value function $latex s(E)$$ with respect to $latex E$$; i.e., $latex \[ \bar{E}_{i,j} = \frac{ \partial s } { \partial E_{i,j} } \] $$ Also suppose that $latex t$$ is a scalar valued argument and $latex \[ E(t) = C(t) D(t) \] $$ It follows that $latex \[ E'(t) = C'(t) D(t) + C(t) D'(t) \] $$ $latex \[ (s \circ E)'(t) = \R{tr} [ \bar{E}^\R{T} E'(t) ] \] $$ $latex \[ = \R{tr} [ \bar{E}^\R{T} C'(t) D(t) ] + \R{tr} [ \bar{E}^\R{T} C(t) D'(t) ] \] $$ $latex \[ = \R{tr} [ D(t) \bar{E}^\R{T} C'(t) ] + \R{tr} [ \bar{E}^\R{T} C(t) D'(t) ] \] $$ $latex \[ \bar{C} = \bar{E} D^\R{T} \W{,} \bar{D} = C^\R{T} \bar{E} \] $$ $subhead Reverse$$ Reverse mode eliminates $latex R_k$$ as follows: for $latex \ell = 0, \ldots , k-1$$, $latex \[ \bar{A}_\ell = \bar{A}_\ell + \bar{R}_k B_{k-\ell}^\R{T} \] $$ $latex \[ \bar{B}_{k-\ell} = \bar{B}_{k-\ell} + A_\ell^\R{T} \bar{R}_k \] $$ $nospell $head Start Class Definition$$ $srccode%cpp% */ # include <cppad/cppad.hpp> # include <Eigen/Core> /* %$$ $head Public$$ $subhead Types$$ $srccode%cpp% */ namespace { // BEGIN_EMPTY_NAMESPACE template <class Base> class atomic_eigen_mat_mul : public CppAD::atomic_base<Base> { public: // ----------------------------------------------------------- // type of elements during calculation of derivatives typedef Base scalar; // type of elements during taping typedef CppAD::AD<scalar> ad_scalar; // type of matrix during calculation of derivatives typedef Eigen::Matrix< scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrix; // type of matrix during taping typedef Eigen::Matrix< ad_scalar, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > ad_matrix; /* %$$ $subhead Constructor$$ $srccode%cpp% */ // constructor atomic_eigen_mat_mul(void) : CppAD::atomic_base<Base>( "atom_eigen_mat_mul" , CppAD::atomic_base<Base>::set_sparsity_enum ) { } /* %$$ $subhead op$$ $srccode%cpp% */ // use atomic operation to multiply two AD matrices ad_matrix op( const ad_matrix& left , const ad_matrix& right ) { size_t nr_left = size_t( left.rows() ); size_t n_middle = size_t( left.cols() ); size_t nc_right = size_t( right.cols() ); assert( n_middle == size_t( right.rows() ) ); size_t nx = 3 + (nr_left + nc_right) * n_middle; size_t ny = nr_left * nc_right; size_t n_left = nr_left * n_middle; size_t n_right = n_middle * nc_right; size_t n_result = nr_left * nc_right; // assert( 3 + n_left + n_right == nx ); assert( n_result == ny ); // ----------------------------------------------------------------- // packed version of left and right CPPAD_TESTVECTOR(ad_scalar) packed_arg(nx); // packed_arg[0] = ad_scalar( nr_left ); packed_arg[1] = ad_scalar( n_middle ); packed_arg[2] = ad_scalar( nc_right ); for(size_t i = 0; i < n_left; i++) packed_arg[3 + i] = left.data()[i]; for(size_t i = 0; i < n_right; i++) packed_arg[ 3 + n_left + i ] = right.data()[i]; // ------------------------------------------------------------------ // Packed version of result = left * right. // This as an atomic_base funciton call that CppAD uses // to store the atomic operation on the tape. CPPAD_TESTVECTOR(ad_scalar) packed_result(ny); (*this)(packed_arg, packed_result); // ------------------------------------------------------------------ // unpack result matrix ad_matrix result(nr_left, nc_right); for(size_t i = 0; i < n_result; i++) result.data()[i] = packed_result[ i ]; // return result; } /* %$$ $head Private$$ $subhead Variables$$ $srccode%cpp% */ private: // ------------------------------------------------------------- // one forward mode vector of matrices for left, right, and result CppAD::vector<matrix> f_left_, f_right_, f_result_; // one reverse mode vector of matrices for left, right, and result CppAD::vector<matrix> r_left_, r_right_, r_result_; // ------------------------------------------------------------- /* %$$ $subhead forward$$ $srccode%cpp% */ // forward mode routine called by CppAD virtual bool forward( // lowest order Taylor coefficient we are evaluating size_t p , // highest order Taylor coefficient we are evaluating size_t q , // which components of x are variables const CppAD::vector<bool>& vx , // which components of y are variables CppAD::vector<bool>& vy , // tx [ 3 + j * (q+1) + k ] is x_j^k const CppAD::vector<scalar>& tx , // ty [ i * (q+1) + k ] is y_i^k CppAD::vector<scalar>& ty ) { size_t n_order = q + 1; size_t nr_left = size_t( CppAD::Integer( tx[ 0 * n_order + 0 ] ) ); size_t n_middle = size_t( CppAD::Integer( tx[ 1 * n_order + 0 ] ) ); size_t nc_right = size_t( CppAD::Integer( tx[ 2 * n_order + 0 ] ) ); # ifndef NDEBUG size_t nx = 3 + (nr_left + nc_right) * n_middle; size_t ny = nr_left * nc_right; # endif // assert( vx.size() == 0 || nx == vx.size() ); assert( vx.size() == 0 || ny == vy.size() ); assert( nx * n_order == tx.size() ); assert( ny * n_order == ty.size() ); // size_t n_left = nr_left * n_middle; size_t n_right = n_middle * nc_right; size_t n_result = nr_left * nc_right; assert( 3 + n_left + n_right == nx ); assert( n_result == ny ); // // ------------------------------------------------------------------- // make sure f_left_, f_right_, and f_result_ are large enough assert( f_left_.size() == f_right_.size() ); assert( f_left_.size() == f_result_.size() ); if( f_left_.size() < n_order ) { f_left_.resize(n_order); f_right_.resize(n_order); f_result_.resize(n_order); // for(size_t k = 0; k < n_order; k++) { f_left_[k].resize( long(nr_left), long(n_middle) ); f_right_[k].resize( long(n_middle), long(nc_right) ); f_result_[k].resize( long(nr_left), long(nc_right) ); } } // ------------------------------------------------------------------- // unpack tx into f_left and f_right for(size_t k = 0; k < n_order; k++) { // unpack left values for this order for(size_t i = 0; i < n_left; i++) f_left_[k].data()[i] = tx[ (3 + i) * n_order + k ]; // // unpack right values for this order for(size_t i = 0; i < n_right; i++) f_right_[k].data()[i] = tx[ ( 3 + n_left + i) * n_order + k ]; } // ------------------------------------------------------------------- // result for each order // (we could avoid recalculting f_result_[k] for k=0,...,p-1) for(size_t k = 0; k < n_order; k++) { // result[k] = sum_ell left[ell] * right[k-ell] f_result_[k] = matrix::Zero( long(nr_left), long(nc_right) ); for(size_t ell = 0; ell <= k; ell++) f_result_[k] += f_left_[ell] * f_right_[k-ell]; } // ------------------------------------------------------------------- // pack result_ into ty for(size_t k = 0; k < n_order; k++) { for(size_t i = 0; i < n_result; i++) ty[ i * n_order + k ] = f_result_[k].data()[i]; } // ------------------------------------------------------------------ // check if we are computing vy if( vx.size() == 0 ) return true; // ------------------------------------------------------------------ // compute variable information for y; i.e., vy // (note that the constant zero times a variable is a constant) scalar zero(0.0); assert( n_order == 1 ); for(size_t i = 0; i < nr_left; i++) { for(size_t j = 0; j < nc_right; j++) { bool var = false; for(size_t ell = 0; ell < n_middle; ell++) { // left information size_t index = 3 + i * n_middle + ell; bool var_left = vx[index]; bool nz_left = var_left | (f_left_[0]( long(i), long(ell) ) != zero); // right information index = 3 + n_left + ell * nc_right + j; bool var_right = vx[index]; bool nz_right = var_right | (f_right_[0]( long(ell), long(j) ) != zero); // effect of result var |= var_left & nz_right; var |= nz_left & var_right; } size_t index = i * nc_right + j; vy[index] = var; } } return true; } /* %$$ $subhead reverse$$ $srccode%cpp% */ // reverse mode routine called by CppAD virtual bool reverse( // highest order Taylor coefficient that we are computing derivative of size_t q , // forward mode Taylor coefficients for x variables const CppAD::vector<double>& tx , // forward mode Taylor coefficients for y variables const CppAD::vector<double>& ty , // upon return, derivative of G[ F[ {x_j^k} ] ] w.r.t {x_j^k} CppAD::vector<double>& px , // derivative of G[ {y_i^k} ] w.r.t. {y_i^k} const CppAD::vector<double>& py ) { size_t n_order = q + 1; size_t nr_left = size_t( CppAD::Integer( tx[ 0 * n_order + 0 ] ) ); size_t n_middle = size_t( CppAD::Integer( tx[ 1 * n_order + 0 ] ) ); size_t nc_right = size_t( CppAD::Integer( tx[ 2 * n_order + 0 ] ) ); # ifndef NDEBUG size_t nx = 3 + (nr_left + nc_right) * n_middle; size_t ny = nr_left * nc_right; # endif // assert( nx * n_order == tx.size() ); assert( ny * n_order == ty.size() ); assert( px.size() == tx.size() ); assert( py.size() == ty.size() ); // size_t n_left = nr_left * n_middle; size_t n_right = n_middle * nc_right; size_t n_result = nr_left * nc_right; assert( 3 + n_left + n_right == nx ); assert( n_result == ny ); // ------------------------------------------------------------------- // make sure f_left_, f_right_ are large enough assert( f_left_.size() == f_right_.size() ); assert( f_left_.size() == f_result_.size() ); // must have previous run forward with order >= n_order assert( f_left_.size() >= n_order ); // ------------------------------------------------------------------- // make sure r_left_, r_right_, and r_result_ are large enough assert( r_left_.size() == r_right_.size() ); assert( r_left_.size() == r_result_.size() ); if( r_left_.size() < n_order ) { r_left_.resize(n_order); r_right_.resize(n_order); r_result_.resize(n_order); // for(size_t k = 0; k < n_order; k++) { r_left_[k].resize( long(nr_left), long(n_middle) ); r_right_[k].resize( long(n_middle), long(nc_right) ); r_result_[k].resize( long(nr_left), long(nc_right) ); } } // ------------------------------------------------------------------- // unpack tx into f_left and f_right for(size_t k = 0; k < n_order; k++) { // unpack left values for this order for(size_t i = 0; i < n_left; i++) f_left_[k].data()[i] = tx[ (3 + i) * n_order + k ]; // // unpack right values for this order for(size_t i = 0; i < n_right; i++) f_right_[k].data()[i] = tx[ (3 + n_left + i) * n_order + k ]; } // ------------------------------------------------------------------- // unpack py into r_result_ for(size_t k = 0; k < n_order; k++) { for(size_t i = 0; i < n_result; i++) r_result_[k].data()[i] = py[ i * n_order + k ]; } // ------------------------------------------------------------------- // initialize r_left_ and r_right_ as zero for(size_t k = 0; k < n_order; k++) { r_left_[k] = matrix::Zero( long(nr_left), long(n_middle) ); r_right_[k] = matrix::Zero( long(n_middle), long(nc_right) ); } // ------------------------------------------------------------------- // matrix reverse mode calculation for(size_t k1 = n_order; k1 > 0; k1--) { size_t k = k1 - 1; for(size_t ell = 0; ell <= k; ell++) { // nr x nm = nr x nc * nc * nm r_left_[ell] += r_result_[k] * f_right_[k-ell].transpose(); // nm x nc = nm x nr * nr * nc r_right_[k-ell] += f_left_[ell].transpose() * r_result_[k]; } } // ------------------------------------------------------------------- // pack r_left and r_right int px for(size_t k = 0; k < n_order; k++) { // dimensions are integer constants px[ 0 * n_order + k ] = 0.0; px[ 1 * n_order + k ] = 0.0; px[ 2 * n_order + k ] = 0.0; // // pack left values for this order for(size_t i = 0; i < n_left; i++) px[ (3 + i) * n_order + k ] = r_left_[k].data()[i]; // // pack right values for this order for(size_t i = 0; i < n_right; i++) px[ (3 + i + n_left) * n_order + k] = r_right_[k].data()[i]; } // return true; } /* %$$ $subhead for_sparse_jac$$ $srccode%cpp% */ // forward Jacobian sparsity routine called by CppAD virtual bool for_sparse_jac( // number of columns in the matrix R size_t q , // sparsity pattern for the matrix R const CppAD::vector< std::set<size_t> >& r , // sparsity pattern for the matrix S = f'(x) * R CppAD::vector< std::set<size_t> >& s , const CppAD::vector<Base>& x ) { size_t nr_left = size_t( CppAD::Integer( x[0] ) ); size_t n_middle = size_t( CppAD::Integer( x[1] ) ); size_t nc_right = size_t( CppAD::Integer( x[2] ) ); # ifndef NDEBUG size_t nx = 3 + (nr_left + nc_right) * n_middle; size_t ny = nr_left * nc_right; # endif // assert( nx == r.size() ); assert( ny == s.size() ); // size_t n_left = nr_left * n_middle; for(size_t i = 0; i < nr_left; i++) { for(size_t j = 0; j < nc_right; j++) { // pack index for entry (i, j) in result size_t i_result = i * nc_right + j; s[i_result].clear(); for(size_t ell = 0; ell < n_middle; ell++) { // pack index for entry (i, ell) in left size_t i_left = 3 + i * n_middle + ell; // pack index for entry (ell, j) in right size_t i_right = 3 + n_left + ell * nc_right + j; // check if result of for this product is alwasy zero // note that x is nan for commponents that are variables bool zero = x[i_left] == Base(0.0) || x[i_right] == Base(0); if( ! zero ) { s[i_result] = CppAD::set_union(s[i_result], r[i_left] ); s[i_result] = CppAD::set_union(s[i_result], r[i_right] ); } } } } return true; } /* %$$ $subhead rev_sparse_jac$$ $srccode%cpp% */ // reverse Jacobian sparsity routine called by CppAD virtual bool rev_sparse_jac( // number of columns in the matrix R^T size_t q , // sparsity pattern for the matrix R^T const CppAD::vector< std::set<size_t> >& rt , // sparsoity pattern for the matrix S^T = f'(x)^T * R^T CppAD::vector< std::set<size_t> >& st , const CppAD::vector<Base>& x ) { size_t nr_left = size_t( CppAD::Integer( x[0] ) ); size_t n_middle = size_t( CppAD::Integer( x[1] ) ); size_t nc_right = size_t( CppAD::Integer( x[2] ) ); size_t nx = 3 + (nr_left + nc_right) * n_middle; # ifndef NDEBUG size_t ny = nr_left * nc_right; # endif // assert( nx == st.size() ); assert( ny == rt.size() ); // // initialize S^T as empty for(size_t i = 0; i < nx; i++) st[i].clear(); // sparsity for S(x)^T = f'(x)^T * R^T size_t n_left = nr_left * n_middle; for(size_t i = 0; i < nr_left; i++) { for(size_t j = 0; j < nc_right; j++) { // pack index for entry (i, j) in result size_t i_result = i * nc_right + j; st[i_result].clear(); for(size_t ell = 0; ell < n_middle; ell++) { // pack index for entry (i, ell) in left size_t i_left = 3 + i * n_middle + ell; // pack index for entry (ell, j) in right size_t i_right = 3 + n_left + ell * nc_right + j; // st[i_left] = CppAD::set_union(st[i_left], rt[i_result]); st[i_right] = CppAD::set_union(st[i_right], rt[i_result]); } } } return true; } /* %$$ $subhead for_sparse_hes$$ $srccode%cpp% */ virtual bool for_sparse_hes( // which components of x are variables for this call const CppAD::vector<bool>& vx, // sparsity pattern for the diagonal of R const CppAD::vector<bool>& r , // sparsity pattern for the vector S const CppAD::vector<bool>& s , // sparsity patternfor the Hessian H(x) CppAD::vector< std::set<size_t> >& h , const CppAD::vector<Base>& x ) { size_t nr_left = size_t( CppAD::Integer( x[0] ) ); size_t n_middle = size_t( CppAD::Integer( x[1] ) ); size_t nc_right = size_t( CppAD::Integer( x[2] ) ); size_t nx = 3 + (nr_left + nc_right) * n_middle; # ifndef NDEBUG size_t ny = nr_left * nc_right; # endif // assert( vx.size() == nx ); assert( r.size() == nx ); assert( s.size() == ny ); assert( h.size() == nx ); // // initilize h as empty for(size_t i = 0; i < nx; i++) h[i].clear(); // size_t n_left = nr_left * n_middle; for(size_t i = 0; i < nr_left; i++) { for(size_t j = 0; j < nc_right; j++) { // pack index for entry (i, j) in result size_t i_result = i * nc_right + j; if( s[i_result] ) { for(size_t ell = 0; ell < n_middle; ell++) { // pack index for entry (i, ell) in left size_t i_left = 3 + i * n_middle + ell; // pack index for entry (ell, j) in right size_t i_right = 3 + n_left + ell * nc_right + j; if( r[i_left] & r[i_right] ) { h[i_left].insert(i_right); h[i_right].insert(i_left); } } } } } return true; } /* %$$ $subhead rev_sparse_hes$$ $srccode%cpp% */ // reverse Hessian sparsity routine called by CppAD virtual bool rev_sparse_hes( // which components of x are variables for this call const CppAD::vector<bool>& vx, // sparsity pattern for S(x) = g'[f(x)] const CppAD::vector<bool>& s , // sparsity pattern for d/dx g[f(x)] = S(x) * f'(x) CppAD::vector<bool>& t , // number of columns in R, U(x), and V(x) size_t q , // sparsity pattern for R const CppAD::vector< std::set<size_t> >& r , // sparsity pattern for U(x) = g^{(2)} [ f(x) ] * f'(x) * R const CppAD::vector< std::set<size_t> >& u , // sparsity pattern for // V(x) = f'(x)^T * U(x) + sum_{i=0}^{m-1} S_i(x) f_i^{(2)} (x) * R CppAD::vector< std::set<size_t> >& v , // parameters as integers const CppAD::vector<Base>& x ) { size_t nr_left = size_t( CppAD::Integer( x[0] ) ); size_t n_middle = size_t( CppAD::Integer( x[1] ) ); size_t nc_right = size_t( CppAD::Integer( x[2] ) ); size_t nx = 3 + (nr_left + nc_right) * n_middle; # ifndef NDEBUG size_t ny = nr_left * nc_right; # endif // assert( vx.size() == nx ); assert( s.size() == ny ); assert( t.size() == nx ); assert( r.size() == nx ); assert( v.size() == nx ); // // initilaize return sparsity patterns as false for(size_t j = 0; j < nx; j++) { t[j] = false; v[j].clear(); } // size_t n_left = nr_left * n_middle; for(size_t i = 0; i < nr_left; i++) { for(size_t j = 0; j < nc_right; j++) { // pack index for entry (i, j) in result size_t i_result = i * nc_right + j; for(size_t ell = 0; ell < n_middle; ell++) { // pack index for entry (i, ell) in left size_t i_left = 3 + i * n_middle + ell; // pack index for entry (ell, j) in right size_t i_right = 3 + n_left + ell * nc_right + j; // // back propagate T(x) = S(x) * f'(x). t[i_left] |= bool( s[i_result] ); t[i_right] |= bool( s[i_result] ); // // V(x) = f'(x)^T * U(x) + sum_i S_i(x) * f_i''(x) * R // U(x) = g''[ f(x) ] * f'(x) * R // S_i(x) = g_i'[ f(x) ] // // back propagate f'(x)^T * U(x) v[i_left] = CppAD::set_union(v[i_left], u[i_result] ); v[i_right] = CppAD::set_union(v[i_right], u[i_result] ); // // back propagate S_i(x) * f_i''(x) * R // (here is where we use vx to check for cross terms) if( s[i_result] & vx[i_left] & vx[i_right] ) { v[i_left] = CppAD::set_union(v[i_left], r[i_right] ); v[i_right] = CppAD::set_union(v[i_right], r[i_left] ); } } } } return true; } /* %$$ $head End Class Definition$$ $srccode%cpp% */ }; // End of atomic_eigen_mat_mul class } // END_EMPTY_NAMESPACE /* %$$ $$ $comment end nospell$$ $end */ # endif
39.361153
80
0.463549
yinzixuan126
c1bdd76957f2369247d910ebf23fcf05b6a932ee
29,247
cpp
C++
Plugins/Raytracing/Raytracing.cpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
null
null
null
Plugins/Raytracing/Raytracing.cpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
null
null
null
Plugins/Raytracing/Raytracing.cpp
cryptobuks1/Stratum
3ecf56c0ce9010e6e95248c0d63edc41eeb13910
[ "MIT" ]
null
null
null
#include <Core/EnginePlugin.hpp> #include <Scene/Camera.hpp> #include <Scene/MeshRenderer.hpp> #include <Scene/Scene.hpp> #include <Util/Profiler.hpp> #include <assimp/pbrmaterial.h> using namespace std; #ifdef GetObject #undef GetObject #endif #define PASS_RAYTRACE (1u << 23) #pragma pack(push) #pragma pack(1) struct GpuBvhNode { float3 Min; uint32_t StartIndex; float3 Max; uint32_t PrimitiveCount; uint32_t RightOffset; // 1st child is at node[index + 1], 2nd child is at node[index + mRightOffset] uint32_t pad[3]; }; struct GpuLeafNode { float4x4 NodeToWorld; float4x4 WorldToNode; uint32_t RootIndex; uint32_t MaterialIndex; uint32_t pad[2]; }; struct DisneyMaterial { float3 BaseColor; float Metallic; float3 Emission; float Specular; float Anisotropy; float Roughness; float SpecularTint; float SheenTint; float Sheen; float ClearcoatGloss; float Clearcoat; float Subsurface; float Transmission; uint32_t pad[3]; }; #pragma pack(pop) class Raytracing : public EnginePlugin { private: vector<Object*> mObjects; Scene* mScene; uint32_t mFrameIndex; struct FrameData { float4x4 mViewProjection; float4x4 mInvViewProjection; float3 mCameraPosition; Texture* mPrimary; Texture* mSecondary; Texture* mMeta; Texture* mResolveTmp; Texture* mResolve; Buffer* mNodes; Buffer* mLeafNodes; Buffer* mVertices; Buffer* mTriangles; Buffer* mLights; Buffer* mMaterials; uint32_t mBvhBase; uint32_t mLightCount; uint64_t mLastBuild; unordered_map<Mesh*, uint32_t> mMeshes; // Mesh, RootIndex }; FrameData* mFrameData; void Build(CommandBuffer* commandBuffer, FrameData& fd) { PROFILER_BEGIN("Copy BVH"); ObjectBvh2* sceneBvh = mScene->BVH(); fd.mMeshes.clear(); vector<GpuBvhNode> nodes; vector<GpuLeafNode> leafNodes; vector<DisneyMaterial> materials; vector<uint3> triangles; vector<uint4> lights; uint32_t nodeBaseIndex = 0; uint32_t vertexCount = 0; unordered_map<Mesh*, uint2> triangleRanges; unordered_map<Buffer*, vector<VkBufferCopy>> vertexCopies; PROFILER_BEGIN("Copy meshes"); // Copy mesh BVHs for (uint32_t sni = 0; sni < sceneBvh->Nodes().size(); sni++){ const ObjectBvh2::Node& sn = sceneBvh->Nodes()[sni]; if (sn.mRightOffset == 0) { for (uint32_t i = 0; i < sn.mCount; i++) { MeshRenderer* mr = dynamic_cast<MeshRenderer*>(sceneBvh->GetObject(sn.mStartIndex + i)); if (mr && mr->Visible()) { leafNodes.push_back({}); Mesh* m = mr->Mesh(); if (!fd.mMeshes.count(m)) { fd.mMeshes.emplace(m, nodeBaseIndex); TriangleBvh2* bvh = m->BVH(); nodes.resize(nodeBaseIndex + bvh->Nodes().size()); uint32_t baseTri = triangles.size(); for (uint32_t ni = 0; ni < bvh->Nodes().size(); ni++) { const TriangleBvh2::Node& n = bvh->Nodes()[ni]; GpuBvhNode& gn = nodes[nodeBaseIndex + ni]; gn.RightOffset = n.mRightOffset; gn.Min = n.mBounds.mMin; gn.Max = n.mBounds.mMax; gn.StartIndex = triangles.size(); gn.PrimitiveCount = n.mCount; if (n.mRightOffset == 0) for (uint32_t i = 0; i < n.mCount; i++) triangles.push_back(vertexCount + bvh->GetTriangle(n.mStartIndex + i)); } triangleRanges.emplace(m, uint2(baseTri, triangles.size())); auto& cpy = vertexCopies[m->VertexBuffer().get()]; VkBufferCopy rgn = {}; rgn.srcOffset = m->BaseVertex() * sizeof(StdVertex); rgn.dstOffset = vertexCount * sizeof(StdVertex); rgn.size = m->VertexCount() * sizeof(StdVertex); cpy.push_back(rgn); nodeBaseIndex += bvh->Nodes().size(); vertexCount += m->VertexCount(); } } } } } PROFILER_END; // Copy scene BVH PROFILER_BEGIN("Copy scene"); fd.mBvhBase = (uint32_t)nodes.size(); nodes.resize(nodes.size() + sceneBvh->Nodes().size()); uint32_t leafNodeIndex = 0; for (uint32_t ni = 0; ni < sceneBvh->Nodes().size(); ni++){ const ObjectBvh2::Node& n = sceneBvh->Nodes()[ni]; GpuBvhNode& gn = nodes[fd.mBvhBase + ni]; gn.RightOffset = n.mRightOffset; gn.Min = n.mBounds.mMin; gn.Max = n.mBounds.mMax; gn.StartIndex = leafNodeIndex; gn.PrimitiveCount = 0; if (n.mRightOffset == 0) { for (uint32_t i = 0; i < n.mCount; i++) { MeshRenderer* mr = dynamic_cast<MeshRenderer*>(sceneBvh->GetObject(n.mStartIndex + i)); if (mr && mr->Visible()) { leafNodes[leafNodeIndex].NodeToWorld = mr->ObjectToWorld(); leafNodes[leafNodeIndex].WorldToNode = mr->WorldToObject(); leafNodes[leafNodeIndex].RootIndex = fd.mMeshes.at(mr->Mesh()); leafNodes[leafNodeIndex].MaterialIndex = materials.size(); DisneyMaterial mat = {}; mat.BaseColor = mr->PushConstant("Color").float4Value.rgb; mat.Emission = mr->PushConstant("Emission").float3Value; mat.Roughness = mr->PushConstant("Roughness").floatValue; mat.Metallic = mr->PushConstant("Metallic").floatValue; mat.ClearcoatGloss = 1; mat.Specular = .5f; mat.Transmission = 1 - mr->PushConstant("Color").float4Value.a; if (mat.Emission.r + mat.Emission.g + mat.Emission.b > 0) { uint2 r = triangleRanges.at(mr->Mesh()); for (uint32_t j = r.x; j < r.y; j++) lights.push_back(uint4(j, materials.size(), leafNodeIndex, 0)); } if (mr->mName == "SuzanneSuzanne") { mat.Subsurface = 1; } if (mr->mName == "ClearcoatClearcoat") { mat.Clearcoat = 1; } materials.push_back(mat); leafNodeIndex++; gn.PrimitiveCount++; } } } } fd.mLightCount = lights.size(); PROFILER_END; PROFILER_BEGIN("Upload data"); if (fd.mNodes && fd.mNodes->Size() < sizeof(GpuBvhNode) * nodes.size()) safe_delete(fd.mNodes); if (!fd.mNodes) fd.mNodes = new Buffer("SceneBvh", mScene->Instance()->Device(), sizeof(GpuBvhNode) * nodes.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); if (fd.mLeafNodes && fd.mLeafNodes->Size() < sizeof(GpuLeafNode) * leafNodes.size()) safe_delete(fd.mLeafNodes); if (!fd.mLeafNodes) fd.mLeafNodes = new Buffer("LeafNodes", mScene->Instance()->Device(), sizeof(GpuLeafNode) * leafNodes.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); if (fd.mTriangles && fd.mTriangles->Size() < sizeof(uint3) * triangles.size()) safe_delete(fd.mTriangles); if (!fd.mTriangles) fd.mTriangles = new Buffer("Triangles", mScene->Instance()->Device(), sizeof(uint3) * triangles.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); if (fd.mLights && fd.mLights->Size() < sizeof(uint4) * lights.size()) safe_delete(fd.mLights); if (!fd.mLights) fd.mLights = new Buffer("Lights", mScene->Instance()->Device(), sizeof(uint4) * lights.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); if (fd.mMaterials && fd.mMaterials->Size() < sizeof(DisneyMaterial) * materials.size()) safe_delete(fd.mMaterials); if (!fd.mMaterials) fd.mMaterials = new Buffer("Materials", mScene->Instance()->Device(), sizeof(DisneyMaterial) * materials.size(), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); if (fd.mVertices && fd.mVertices->Size() < sizeof(StdVertex) * vertexCount) safe_delete(fd.mVertices); if (!fd.mVertices) fd.mVertices = new Buffer("Vertices", mScene->Instance()->Device(), sizeof(StdVertex) * vertexCount, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); fd.mNodes->Upload(nodes.data(), sizeof(GpuBvhNode) * nodes.size()); fd.mLeafNodes->Upload(leafNodes.data(), sizeof(GpuLeafNode) * leafNodes.size()); fd.mMaterials->Upload(materials.data(), sizeof(DisneyMaterial)* materials.size()); fd.mLights->Upload(lights.data(), sizeof(uint3) * lights.size()); fd.mTriangles->Upload(triangles.data(), sizeof(uint3) * triangles.size()); for (auto p : vertexCopies) vkCmdCopyBuffer(*commandBuffer, *p.first, *fd.mVertices, p.second.size(), p.second.data()); VkBufferMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; barrier.buffer = *fd.mVertices; barrier.size = fd.mVertices->Size(); vkCmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 1, &barrier, 0, nullptr); fd.mLastBuild = mScene->Instance()->FrameCount(); PROFILER_END; } public: inline int Priority() override { return 10000; } PLUGIN_EXPORT Raytracing() : mScene(nullptr), mFrameIndex(0) { mEnabled = true; } PLUGIN_EXPORT ~Raytracing() { for (uint32_t i = 0; i < mScene->Instance()->Device()->MaxFramesInFlight(); i++) { safe_delete(mFrameData[i].mPrimary); safe_delete(mFrameData[i].mSecondary); safe_delete(mFrameData[i].mMeta); safe_delete(mFrameData[i].mResolveTmp); safe_delete(mFrameData[i].mResolve); safe_delete(mFrameData[i].mNodes); safe_delete(mFrameData[i].mLeafNodes); safe_delete(mFrameData[i].mVertices); safe_delete(mFrameData[i].mTriangles); safe_delete(mFrameData[i].mLights); safe_delete(mFrameData[i].mMaterials); } safe_delete_array(mFrameData); for (Object* obj : mObjects) mScene->RemoveObject(obj); } PLUGIN_EXPORT bool Init(Scene* scene) override { mScene = scene; mScene->Environment()->EnableCelestials(false); mScene->Environment()->EnableScattering(false); mScene->Environment()->AmbientLight(.3f); //mScene->Environment()->EnvironmentTexture(mScene->AssetManager()->LoadTexture("Assets/Textures/old_outdoor_theater_4k.hdr")); #pragma region load glTF string folder = "Assets/Models/"; string file = "cornellbox.gltf"; shared_ptr<Material> opaque = make_shared<Material>("PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm")); opaque->EnableKeyword("TEXTURED"); opaque->SetParameter("TextureST", float4(1, 1, 0, 0)); shared_ptr<Material> alphaClip = make_shared<Material>("Cutout PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm")); alphaClip->RenderQueue(5000); alphaClip->BlendMode(BLEND_MODE_ALPHA); alphaClip->CullMode(VK_CULL_MODE_NONE); alphaClip->EnableKeyword("TEXTURED"); alphaClip->EnableKeyword("ALPHA_CLIP"); alphaClip->EnableKeyword("TWO_SIDED"); alphaClip->SetParameter("TextureST", float4(1, 1, 0, 0)); shared_ptr<Material> alphaBlend = make_shared<Material>("Transparent PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm")); alphaBlend->RenderQueue(5000); alphaBlend->BlendMode(BLEND_MODE_ALPHA); alphaBlend->CullMode(VK_CULL_MODE_NONE); alphaBlend->EnableKeyword("TEXTURED"); alphaBlend->EnableKeyword("TWO_SIDED"); alphaBlend->SetParameter("TextureST", float4(1, 1, 0, 0)); shared_ptr<Material> curOpaque = nullptr; shared_ptr<Material> curClip = nullptr; shared_ptr<Material> curBlend = nullptr; uint32_t arraySize = mScene->AssetManager()->LoadShader("Shaders/pbr.stm")->GetGraphics(PASS_MAIN, { "TEXTURED" })->mDescriptorBindings.at("MainTextures").second.descriptorCount; uint32_t opaque_i = 0; uint32_t clip_i = 0; uint32_t blend_i = 0; auto matfunc = [&](Scene* scene, aiMaterial* aimaterial) { aiString alphaMode; if (aimaterial->Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode) == AI_SUCCESS) { if (alphaMode == aiString("MASK")) return alphaClip; if (alphaMode == aiString("BLEND")) return alphaBlend; } return opaque; }; auto objfunc = [&](Scene* scene, Object* object, aiMaterial* aimaterial) { MeshRenderer* renderer = dynamic_cast<MeshRenderer*>(object); if (!renderer) return; Material* mat = renderer->Material(); uint32_t i; if (mat == opaque.get()) { i = opaque_i; opaque_i++; if (opaque_i >= arraySize) curOpaque.reset(); if (!curOpaque) { opaque_i = opaque_i % arraySize; curOpaque = make_shared<Material>("PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm")); curOpaque->EnableKeyword("TEXTURED"); curOpaque->SetParameter("TextureST", float4(1, 1, 0, 0)); } renderer->Material(curOpaque); mat = curOpaque.get(); } else if (mat == alphaClip.get()) { i = clip_i; clip_i++; if (clip_i >= arraySize) curClip.reset(); if (!curClip) { clip_i = clip_i % arraySize; curClip = make_shared<Material>("Cutout PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm")); curClip->RenderQueue(5000); curClip->BlendMode(BLEND_MODE_ALPHA); curClip->CullMode(VK_CULL_MODE_NONE); curClip->EnableKeyword("TEXTURED"); curClip->EnableKeyword("ALPHA_CLIP"); curClip->EnableKeyword("TWO_SIDED"); curClip->SetParameter("TextureST", float4(1, 1, 0, 0)); } renderer->Material(curClip); mat = curClip.get(); } else if (mat == alphaBlend.get()) { i = blend_i; blend_i++; if (blend_i >= 64) curBlend.reset(); if (!curBlend) { blend_i = blend_i % arraySize; curBlend = make_shared<Material>("Transparent PBR", mScene->AssetManager()->LoadShader("Shaders/pbr.stm")); curBlend->RenderQueue(5000); curBlend->BlendMode(BLEND_MODE_ALPHA); curBlend->CullMode(VK_CULL_MODE_NONE); curBlend->EnableKeyword("TEXTURED"); curBlend->EnableKeyword("TWO_SIDED"); curBlend->SetParameter("TextureST", float4(1, 1, 0, 0)); } renderer->Material(curBlend); mat = curBlend.get(); } else return; mat->PassMask((PassType)(PASS_RAYTRACE)); aiColor3D emissiveColor(0); aiColor4D baseColor(1); float metallic = 1.f; float roughness = 1.f; aiString baseColorTexture, metalRoughTexture, normalTexture, emissiveTexture; if (aimaterial->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE, &baseColorTexture) == AI_SUCCESS && baseColorTexture.length) { mat->SetParameter("MainTextures", i, scene->AssetManager()->LoadTexture(folder + baseColorTexture.C_Str())); baseColor = aiColor4D(1); } else mat->SetParameter("MainTextures", i, scene->AssetManager()->LoadTexture("Assets/Textures/white.png")); if (aimaterial->GetTexture(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE, &metalRoughTexture) == AI_SUCCESS && metalRoughTexture.length) mat->SetParameter("MaskTextures", i, scene->AssetManager()->LoadTexture(folder + metalRoughTexture.C_Str(), false)); else mat->SetParameter("MaskTextures", i, scene->AssetManager()->LoadTexture("Assets/Textures/mask.png", false)); if (aimaterial->GetTexture(aiTextureType_NORMALS, 0, &normalTexture) == AI_SUCCESS && normalTexture.length) mat->SetParameter("NormalTextures", i, scene->AssetManager()->LoadTexture(folder + normalTexture.C_Str(), false)); else mat->SetParameter("NormalTextures", i, scene->AssetManager()->LoadTexture("Assets/Textures/bump.png", false)); aimaterial->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR, baseColor); aimaterial->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR, metallic); aimaterial->Get(AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR, roughness); aimaterial->Get(AI_MATKEY_COLOR_EMISSIVE, emissiveColor); renderer->PushConstant("TextureIndex", i); renderer->PushConstant("Color", float4(baseColor.r, baseColor.g, baseColor.b, baseColor.a)); renderer->PushConstant("Roughness", roughness); renderer->PushConstant("Metallic", metallic); renderer->PushConstant("Emission", float3(emissiveColor.r, emissiveColor.g, emissiveColor.b)); }; Object* root = mScene->LoadModelScene(folder + file, matfunc, objfunc, .6f, 1.f, .05f, .0015f); root->LocalRotation(quaternion(float3(0, PI / 2, 0))); queue<Object*> nodes; nodes.push(root); while (nodes.size()) { Object* o = nodes.front(); nodes.pop(); for (uint32_t i = 0; i < o->ChildCount(); i++) nodes.push(o->Child(i)); mObjects.push_back(o); if (Light* l = dynamic_cast<Light*>(o)){ if (l->Type() == LIGHT_TYPE_SUN){ l->CascadeCount(1); l->ShadowDistance(30); } } } #pragma endregion mFrameData = new FrameData[mScene->Instance()->Device()->MaxFramesInFlight()]; for (uint32_t i = 0; i < mScene->Instance()->Device()->MaxFramesInFlight(); i++) { mFrameData[i].mPrimary = nullptr; mFrameData[i].mSecondary = nullptr; mFrameData[i].mMeta = nullptr; mFrameData[i].mResolveTmp = nullptr; mFrameData[i].mResolve = nullptr; mFrameData[i].mNodes = nullptr; mFrameData[i].mLeafNodes = nullptr; mFrameData[i].mVertices = nullptr; mFrameData[i].mTriangles = nullptr; mFrameData[i].mLights = nullptr; mFrameData[i].mMaterials = nullptr; mFrameData[i].mBvhBase = 0; mFrameData[i].mLightCount = 0; mFrameData[i].mLastBuild = 0; } return true; } PLUGIN_EXPORT void PreRender(CommandBuffer* commandBuffer, Camera* camera, PassType pass) override { if (pass != PASS_MAIN) return; FrameData& fd = mFrameData[commandBuffer->Device()->FrameContextIndex()]; if (fd.mLastBuild <= mScene->LastBvhBuild()) Build(commandBuffer, fd); VkPipelineStageFlags dstStage, srcStage; VkImageMemoryBarrier barriers[4]; if (fd.mPrimary && (fd.mPrimary->Width() != camera->FramebufferWidth() || fd.mPrimary->Height() != camera->FramebufferHeight())) { safe_delete(fd.mPrimary); safe_delete(fd.mSecondary); safe_delete(fd.mMeta); safe_delete(fd.mResolveTmp); safe_delete(fd.mResolve); } if (!fd.mPrimary) { fd.mPrimary = new Texture("Raytrace Primary", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); fd.mSecondary = new Texture("Raytrace Secondary", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); fd.mMeta = new Texture("Raytrace Meta", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1, VK_FORMAT_R32G32B32A32_SFLOAT, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); fd.mResolveTmp = new Texture("Raytrace Resolve", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1, VK_FORMAT_R16G16B16A16_SFLOAT, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); fd.mResolve = new Texture("Raytrace Resolve", mScene->Instance()->Device(), camera->FramebufferWidth(), camera->FramebufferHeight(), 1, VK_FORMAT_R16G16B16A16_SFLOAT, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); fd.mResolveTmp->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, commandBuffer); barriers[0] = fd.mPrimary->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); barriers[1] = fd.mSecondary->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); barriers[2] = fd.mMeta->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); barriers[3] = fd.mResolve->TransitionImageLayout(VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); vkCmdPipelineBarrier(*commandBuffer, srcStage, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 4, barriers); } #pragma region raytrace FrameData& pfd = mFrameData[(commandBuffer->Device()->FrameContextIndex() + (commandBuffer->Device()->MaxFramesInFlight()-1)) % commandBuffer->Device()->MaxFramesInFlight()]; bool accum = pfd.mPrimary && pfd.mPrimary->Width() == fd.mPrimary->Width() && pfd.mPrimary->Height() == fd.mPrimary->Height(); Shader* rt = mScene->AssetManager()->LoadShader("Shaders/raytrace.stm"); ComputeShader* trace = accum ? rt->GetCompute("Raytrace", { "ACCUMULATE" }) : rt->GetCompute("Raytrace", {}); vkCmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, trace->mPipeline); fd.mViewProjection = camera->ViewProjection(); fd.mInvViewProjection = inverse(camera->ViewProjection()); fd.mCameraPosition = camera->WorldPosition(); float2 res(fd.mPrimary->Width(), fd.mPrimary->Height()); float near = camera->Near(); float far = camera->Far(); uint32_t vs = sizeof(StdVertex); uint32_t is = sizeof(uint32_t); commandBuffer->PushConstant(trace, "LastViewProjection", &pfd.mViewProjection); commandBuffer->PushConstant(trace, "LastCameraPosition", &pfd.mCameraPosition); commandBuffer->PushConstant(trace, "InvViewProj", &fd.mInvViewProjection); commandBuffer->PushConstant(trace, "Resolution", &res); commandBuffer->PushConstant(trace, "Near", &near); commandBuffer->PushConstant(trace, "Far", &far); commandBuffer->PushConstant(trace, "CameraPosition", &fd.mCameraPosition); commandBuffer->PushConstant(trace, "VertexStride", &vs); commandBuffer->PushConstant(trace, "IndexStride", &is); commandBuffer->PushConstant(trace, "BvhRoot", &fd.mBvhBase); commandBuffer->PushConstant(trace, "FrameIndex", &mFrameIndex); commandBuffer->PushConstant(trace, "LightCount", &fd.mLightCount); DescriptorSet* ds = commandBuffer->Device()->GetTempDescriptorSet("RT", trace->mDescriptorSetLayouts[0]); VkDeviceSize bufSize = AlignUp(sizeof(CameraBuffer), commandBuffer->Device()->Limits().minUniformBufferOffsetAlignment); ds->CreateStorageTextureDescriptor(fd.mPrimary, trace->mDescriptorBindings.at("OutputPrimary").second.binding); ds->CreateStorageTextureDescriptor(fd.mSecondary, trace->mDescriptorBindings.at("OutputSecondary").second.binding); ds->CreateStorageTextureDescriptor(fd.mMeta, trace->mDescriptorBindings.at("OutputMeta").second.binding); if (accum) { ds->CreateSampledTextureDescriptor(pfd.mPrimary, trace->mDescriptorBindings.at("PreviousPrimary").second.binding, VK_IMAGE_LAYOUT_GENERAL); ds->CreateSampledTextureDescriptor(pfd.mSecondary, trace->mDescriptorBindings.at("PreviousSecondary").second.binding, VK_IMAGE_LAYOUT_GENERAL); ds->CreateSampledTextureDescriptor(pfd.mMeta, trace->mDescriptorBindings.at("PreviousMeta").second.binding, VK_IMAGE_LAYOUT_GENERAL); } ds->CreateStorageBufferDescriptor(fd.mNodes, 0, fd.mNodes->Size(), trace->mDescriptorBindings.at("SceneBvh").second.binding); ds->CreateStorageBufferDescriptor(fd.mLeafNodes, 0, fd.mLeafNodes->Size(), trace->mDescriptorBindings.at("LeafNodes").second.binding); ds->CreateStorageBufferDescriptor(fd.mVertices, 0, fd.mVertices->Size(), trace->mDescriptorBindings.at("Vertices").second.binding); ds->CreateStorageBufferDescriptor(fd.mTriangles, 0, fd.mTriangles->Size(), trace->mDescriptorBindings.at("Triangles").second.binding); ds->CreateStorageBufferDescriptor(fd.mMaterials, 0, fd.mMaterials->Size(), trace->mDescriptorBindings.at("Materials").second.binding); ds->CreateStorageBufferDescriptor(fd.mLights, 0, fd.mLights->Size(), trace->mDescriptorBindings.at("Lights").second.binding); ds->CreateSampledTextureDescriptor(mScene->AssetManager()->LoadTexture("Assets/Textures/rgbanoise.png", false), trace->mDescriptorBindings.at("NoiseTex").second.binding, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); ds->FlushWrites(); vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, trace->mPipelineLayout, 0, 1, *ds, 0, nullptr); vkCmdDispatch(*commandBuffer, (fd.mPrimary->Width() + 7) / 8, (fd.mPrimary->Height() + 7) / 8, 1); #pragma endregion barriers[0] = fd.mPrimary->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); barriers[1] = fd.mSecondary->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); barriers[2] = fd.mMeta->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); vkCmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 3, barriers); uint2 ires(camera->FramebufferWidth(), camera->FramebufferHeight()); #pragma region combine x ComputeShader* combine = mScene->AssetManager()->LoadShader("Shaders/resolve.stm")->GetCompute("Combine", {"MULTI_COMBINE"}); vkCmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, combine->mPipeline); ds = commandBuffer->Device()->GetTempDescriptorSet("Resolve", combine->mDescriptorSetLayouts[0]); ds->CreateSampledTextureDescriptor(fd.mPrimary, combine->mDescriptorBindings.at("Primary").second.binding, VK_IMAGE_LAYOUT_GENERAL); ds->CreateSampledTextureDescriptor(fd.mSecondary, combine->mDescriptorBindings.at("Secondary").second.binding, VK_IMAGE_LAYOUT_GENERAL); ds->CreateSampledTextureDescriptor(fd.mMeta, combine->mDescriptorBindings.at("Meta").second.binding, VK_IMAGE_LAYOUT_GENERAL); ds->CreateStorageTextureDescriptor(fd.mResolveTmp, combine->mDescriptorBindings.at("Output").second.binding); ds->FlushWrites(); vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, combine->mPipelineLayout, 0, 1, *ds, 0, nullptr); commandBuffer->PushConstant(combine, "InvViewProj", &fd.mInvViewProjection); commandBuffer->PushConstant(combine, "Resolution", &ires); commandBuffer->PushConstant(combine, "CameraPosition", &fd.mCameraPosition); uint32_t axis = 0; commandBuffer->PushConstant(combine, "BlurAxis", &axis); vkCmdDispatch(*commandBuffer, (fd.mResolve->Width() + 7) / 8, (fd.mResolve->Height() + 7) / 8, 1); #pragma endregion barriers[0] = fd.mResolveTmp->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); vkCmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, barriers); #pragma region combine y combine = mScene->AssetManager()->LoadShader("Shaders/resolve.stm")->GetCompute("Combine", {}); vkCmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, combine->mPipeline); ds = commandBuffer->Device()->GetTempDescriptorSet("Resolve2", combine->mDescriptorSetLayouts[0]); ds->CreateSampledTextureDescriptor(fd.mResolveTmp, combine->mDescriptorBindings.at("Primary").second.binding, VK_IMAGE_LAYOUT_GENERAL); ds->CreateSampledTextureDescriptor(fd.mMeta, combine->mDescriptorBindings.at("Meta").second.binding, VK_IMAGE_LAYOUT_GENERAL); ds->CreateStorageTextureDescriptor(fd.mResolve, combine->mDescriptorBindings.at("Output").second.binding); ds->FlushWrites(); vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, combine->mPipelineLayout, 0, 1, *ds, 0, nullptr); commandBuffer->PushConstant(combine, "InvViewProj", &fd.mInvViewProjection); commandBuffer->PushConstant(combine, "Resolution", &ires); commandBuffer->PushConstant(combine, "CameraPosition", &fd.mCameraPosition); axis = 1; commandBuffer->PushConstant(combine, "BlurAxis", &axis); vkCmdDispatch(*commandBuffer, (fd.mResolve->Width() + 7) / 8, (fd.mResolve->Height() + 7) / 8, 1); #pragma endregion barriers[0] = fd.mResolve->TransitionImageLayout(VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL, srcStage, dstStage); vkCmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, barriers); mFrameIndex++; } PLUGIN_EXPORT void PostRenderScene(CommandBuffer* commandBuffer, Camera* camera, PassType pass) override { if (pass != PASS_MAIN) return; GraphicsShader* shader = mScene->AssetManager()->LoadShader("Shaders/rtblit.stm")->GetGraphics(PASS_MAIN, {}); if (!shader) return; VkPipelineLayout layout = commandBuffer->BindShader(shader, pass, nullptr); if (!layout) return; float4 st(1, 1, 0, 0); float4 tst(1, -1, 0, 1); float exposure = .4f; FrameData& fd = mFrameData[commandBuffer->Device()->FrameContextIndex()]; commandBuffer->PushConstant(shader, "ScaleTranslate", &st); commandBuffer->PushConstant(shader, "TextureST", &tst); commandBuffer->PushConstant(shader, "Exposure", &exposure); DescriptorSet* ds = commandBuffer->Device()->GetTempDescriptorSet("Blit", shader->mDescriptorSetLayouts[0]); ds->CreateSampledTextureDescriptor(fd.mResolve, shader->mDescriptorBindings.at("Radiance").second.binding, VK_IMAGE_LAYOUT_GENERAL); ds->FlushWrites(); vkCmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, *ds, 0, nullptr); vkCmdDraw(*commandBuffer, 6, 1, 0, 0); } }; ENGINE_PLUGIN(Raytracing)
43.782934
284
0.729716
cryptobuks1
c1be765e20213864af4152203dab76e411c8a402
1,364
cpp
C++
Sources/Athena2D/Tools/TextureCacheViewer.cpp
jccit/Athena
fa204647bf9e60ae113fcaf5e391813da51b0881
[ "BSD-3-Clause" ]
null
null
null
Sources/Athena2D/Tools/TextureCacheViewer.cpp
jccit/Athena
fa204647bf9e60ae113fcaf5e391813da51b0881
[ "BSD-3-Clause" ]
null
null
null
Sources/Athena2D/Tools/TextureCacheViewer.cpp
jccit/Athena
fa204647bf9e60ae113fcaf5e391813da51b0881
[ "BSD-3-Clause" ]
null
null
null
#include "pch.h" #include "TextureCacheViewer.h" #include <imgui.h> TextureCacheViewer::TextureCacheViewer(std::map<std::string, SDL_Texture*>* texCache) { title = "Texture Cache Viewer"; cache = texCache; } std::string selectedTexture; void TextureCacheViewer::renderPanel() { if (isShowing()) { // left { ImGui::BeginChild("items", ImVec2(200, 0), true); for (auto& cacheEntry : *cache) { if (selectedTexture.empty()) { selectedTexture = cacheEntry.first; } if (ImGui::Selectable(cacheEntry.first.c_str(), selectedTexture == cacheEntry.first)) selectedTexture = cacheEntry.first; } ImGui::EndChild(); } ImGui::SameLine(); // right { ImGui::BeginChild("item view", ImVec2(0, 0)); if (cache->count(selectedTexture)) { SDL_Texture* tex = cache->at(selectedTexture); int texWidth = 0; int texHeight = 0; SDL_QueryTexture(tex, nullptr, nullptr, &texWidth, &texHeight); ImGui::Image((ImTextureID)tex, ImVec2(static_cast<float>(texWidth), static_cast<float>(texHeight))); } ImGui::EndChild(); } ImGui::End(); } }
25.735849
116
0.53739
jccit
c1c1ed9a884c62b14ed8e9ff4704ba783db8b35e
11,757
cpp
C++
test/source/tests/executor_tests/inline_executor_tests.cpp
insujang/concurrencpp
580f430caf1369521ee1422c15c4c8a89823972b
[ "MIT" ]
1
2022-01-08T01:53:16.000Z
2022-01-08T01:53:16.000Z
test/source/tests/executor_tests/inline_executor_tests.cpp
tlming16/concurrencpp
580f430caf1369521ee1422c15c4c8a89823972b
[ "MIT" ]
null
null
null
test/source/tests/executor_tests/inline_executor_tests.cpp
tlming16/concurrencpp
580f430caf1369521ee1422c15c4c8a89823972b
[ "MIT" ]
null
null
null
#include "concurrencpp/concurrencpp.h" #include "infra/tester.h" #include "infra/assertions.h" #include "utils/object_observer.h" #include "utils/test_generators.h" #include "utils/test_ready_result.h" #include "utils/executor_shutdowner.h" namespace concurrencpp::tests { void test_inline_executor_name(); void test_inline_executor_shutdown(); void test_inline_executor_max_concurrency_level(); void test_inline_executor_post_exception(); void test_inline_executor_post_foreign(); void test_inline_executor_post_inline(); void test_inline_executor_post(); void test_inline_executor_submit_exception(); void test_inline_executor_submit_foreign(); void test_inline_executor_submit_inline(); void test_inline_executor_submit(); void test_inline_executor_bulk_post_exception(); void test_inline_executor_bulk_post_foreign(); void test_inline_executor_bulk_post_inline(); void test_inline_executor_bulk_post(); void test_inline_executor_bulk_submit_exception(); void test_inline_executor_bulk_submit_foreign(); void test_inline_executor_bulk_submit_inline(); void test_inline_executor_bulk_submit(); void assert_executed_inline(const std::unordered_map<size_t, size_t>& execution_map) noexcept { assert_equal(execution_map.size(), static_cast<size_t>(1)); assert_equal(execution_map.begin()->first, ::concurrencpp::details::thread::get_current_virtual_id()); } } // namespace concurrencpp::tests using concurrencpp::details::thread; void concurrencpp::tests::test_inline_executor_name() { auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); assert_equal(executor->name, concurrencpp::details::consts::k_inline_executor_name); } void concurrencpp::tests::test_inline_executor_shutdown() { auto executor = std::make_shared<inline_executor>(); assert_false(executor->shutdown_requested()); executor->shutdown(); assert_true(executor->shutdown_requested()); // it's ok to shut down an executor more than once executor->shutdown(); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { executor->enqueue(concurrencpp::task {}); }); assert_throws<concurrencpp::errors::runtime_shutdown>([executor] { concurrencpp::task array[4]; std::span<concurrencpp::task> span = array; executor->enqueue(span); }); } void concurrencpp::tests::test_inline_executor_max_concurrency_level() { auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); assert_equal(executor->max_concurrency_level(), concurrencpp::details::consts::k_inline_executor_max_concurrency_level); } void concurrencpp::tests::test_inline_executor_post_exception() { auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); executor->post([] { throw std::runtime_error(""); }); } void concurrencpp::tests::test_inline_executor_post_foreign() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); for (size_t i = 0; i < task_count; i++) { executor->post(observer.get_testing_stub()); } assert_equal(observer.get_execution_count(), task_count); assert_equal(observer.get_destruction_count(), task_count); assert_executed_inline(observer.get_execution_map()); } void concurrencpp::tests::test_inline_executor_post_inline() { object_observer observer; constexpr size_t task_count = 1'024; auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); executor->post([executor, &observer] { for (size_t i = 0; i < task_count; i++) { executor->post(observer.get_testing_stub()); } }); assert_equal(observer.get_execution_count(), task_count); assert_equal(observer.get_destruction_count(), task_count); assert_executed_inline(observer.get_execution_map()); } void concurrencpp::tests::test_inline_executor_post() { test_inline_executor_post_exception(); test_inline_executor_post_inline(); test_inline_executor_post_foreign(); } void concurrencpp::tests::test_inline_executor_submit_exception() { auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); constexpr intptr_t id = 12345; auto result = executor->submit([id] { throw custom_exception(id); }); result.wait(); test_ready_result_custom_exception(std::move(result), id); } void concurrencpp::tests::test_inline_executor_submit_foreign() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); std::vector<result<size_t>> results; results.resize(task_count); for (size_t i = 0; i < task_count; i++) { results[i] = executor->submit(observer.get_testing_stub(i)); } for (size_t i = 0; i < task_count; i++) { assert_equal(results[i].status(), result_status::value); assert_equal(results[i].get(), i); } assert_equal(observer.get_execution_count(), task_count); assert_equal(observer.get_destruction_count(), task_count); assert_executed_inline(observer.get_execution_map()); } void concurrencpp::tests::test_inline_executor_submit_inline() { object_observer observer; constexpr size_t task_count = 1'024; auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); auto results_res = executor->submit([executor, &observer] { std::vector<result<size_t>> results; results.resize(task_count); for (size_t i = 0; i < task_count; i++) { results[i] = executor->submit(observer.get_testing_stub(i)); } return results; }); auto results = results_res.get(); for (size_t i = 0; i < task_count; i++) { assert_equal(results[i].status(), result_status::value); assert_equal(results[i].get(), i); } assert_equal(observer.get_execution_count(), task_count); assert_equal(observer.get_destruction_count(), task_count); assert_executed_inline(observer.get_execution_map()); } void concurrencpp::tests::test_inline_executor_submit() { test_inline_executor_submit_exception(); test_inline_executor_submit_foreign(); test_inline_executor_submit_inline(); } void concurrencpp::tests::test_inline_executor_bulk_post_exception() { auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); auto thrower = [] { throw std::runtime_error(""); }; std::vector<decltype(thrower)> tasks; tasks.resize(4); executor->bulk_post<decltype(thrower)>(tasks); } void concurrencpp::tests::test_inline_executor_bulk_post_foreign() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); std::vector<testing_stub> stubs; stubs.reserve(task_count); for (size_t i = 0; i < task_count; i++) { stubs.emplace_back(observer.get_testing_stub()); } std::span<testing_stub> span = stubs; executor->bulk_post<testing_stub>(span); assert_equal(observer.get_execution_count(), task_count); assert_equal(observer.get_destruction_count(), task_count); assert_executed_inline(observer.get_execution_map()); } void concurrencpp::tests::test_inline_executor_bulk_post_inline() { object_observer observer; constexpr size_t task_count = 1'024; auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); executor->post([executor, &observer]() mutable { std::vector<testing_stub> stubs; stubs.reserve(task_count); for (size_t i = 0; i < task_count; i++) { stubs.emplace_back(observer.get_testing_stub()); } executor->bulk_post<testing_stub>(stubs); }); assert_equal(observer.get_execution_count(), task_count); assert_equal(observer.get_destruction_count(), task_count); assert_executed_inline(observer.get_execution_map()); } void concurrencpp::tests::test_inline_executor_bulk_post() { test_inline_executor_bulk_post_exception(); test_inline_executor_bulk_post_foreign(); test_inline_executor_bulk_post_inline(); } void concurrencpp::tests::test_inline_executor_bulk_submit_exception() { auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); constexpr intptr_t id = 12345; auto thrower = [id] { throw custom_exception(id); }; std::vector<decltype(thrower)> tasks; tasks.resize(4, thrower); auto results = executor->bulk_submit<decltype(thrower)>(tasks); for (auto& result : results) { result.wait(); test_ready_result_custom_exception(std::move(result), id); } } void concurrencpp::tests::test_inline_executor_bulk_submit_foreign() { object_observer observer; const size_t task_count = 1'024; auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); std::vector<value_testing_stub> stubs; stubs.reserve(task_count); for (size_t i = 0; i < task_count; i++) { stubs.emplace_back(observer.get_testing_stub(i)); } auto results = executor->bulk_submit<value_testing_stub>(stubs); for (size_t i = 0; i < task_count; i++) { assert_equal(results[i].status(), result_status::value); assert_equal(results[i].get(), i); } assert_equal(observer.get_execution_count(), task_count); assert_equal(observer.get_destruction_count(), task_count); assert_executed_inline(observer.get_execution_map()); } void concurrencpp::tests::test_inline_executor_bulk_submit_inline() { object_observer observer; constexpr size_t task_count = 1'024; auto executor = std::make_shared<inline_executor>(); executor_shutdowner shutdown(executor); auto results_res = executor->submit([executor, &observer] { std::vector<value_testing_stub> stubs; stubs.reserve(task_count); for (size_t i = 0; i < task_count; i++) { stubs.emplace_back(observer.get_testing_stub(i)); } return executor->bulk_submit<value_testing_stub>(stubs); }); auto results = results_res.get(); for (size_t i = 0; i < task_count; i++) { assert_equal(results[i].status(), result_status::value); assert_equal(results[i].get(), i); } assert_equal(observer.get_execution_count(), task_count); assert_equal(observer.get_destruction_count(), task_count); assert_executed_inline(observer.get_execution_map()); } void concurrencpp::tests::test_inline_executor_bulk_submit() { test_inline_executor_bulk_submit_exception(); test_inline_executor_bulk_submit_foreign(); test_inline_executor_bulk_submit_inline(); } using namespace concurrencpp::tests; int main() { tester tester("inline_executor test"); tester.add_step("name", test_inline_executor_name); tester.add_step("shutdown", test_inline_executor_shutdown); tester.add_step("max_concurrency_level", test_inline_executor_max_concurrency_level); tester.add_step("post", test_inline_executor_post); tester.add_step("submit", test_inline_executor_submit); tester.add_step("bulk_post", test_inline_executor_bulk_post); tester.add_step("bulk_submit", test_inline_executor_bulk_submit); tester.launch_test(); return 0; }
33.305949
124
0.722378
insujang
c1c5cd073ae8e747c8e3761617eaa3f5f7a62784
9,936
cpp
C++
src/misc/sharedmemory.cpp
OpenSpace/Ghoul
af5545a13d140b15e7b37f581ea7dde522be2b5b
[ "MIT" ]
8
2016-09-13T12:39:49.000Z
2022-03-21T12:30:50.000Z
src/misc/sharedmemory.cpp
OpenSpace/Ghoul
af5545a13d140b15e7b37f581ea7dde522be2b5b
[ "MIT" ]
33
2016-07-07T20:35:05.000Z
2021-10-15T03:12:13.000Z
src/misc/sharedmemory.cpp
OpenSpace/Ghoul
af5545a13d140b15e7b37f581ea7dde522be2b5b
[ "MIT" ]
16
2015-06-24T20:41:28.000Z
2022-01-08T04:14:03.000Z
/***************************************************************************************** * * * GHOUL * * General Helpful Open Utility Library * * * * Copyright (c) 2012-2021 * * * * 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 <ghoul/misc/sharedmemory.h> #include <ghoul/fmt.h> #include <ghoul/misc/crc32.h> #include <atomic> #ifndef WIN32 #include <errno.h> #include <string.h> #include <sys/shm.h> // Common access type bits, used with ipcperm() #define IPC_R 000400 // read permission #define IPC_W 000200 // write/alter permission #define IPC_M 010000 // permission to change control info #else #include <Windows.h> #endif namespace ghoul { #ifdef WIN32 std::map<const std::string, HANDLE> SharedMemory::_createdSections; #endif // WIN32 namespace { struct Header { std::atomic_flag mutex; #ifdef WIN32 size_t size; #endif // WIN32 }; Header* header(void* memory) { return reinterpret_cast<Header*>(memory); } #ifdef WIN32 std::string lastErrorToString(DWORD err) { LPTSTR errorBuffer = nullptr; DWORD nValues = FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPTSTR>(&errorBuffer), 0, nullptr ); if ((nValues > 0) && (errorBuffer != nullptr)) { std::string errorMsg(errorBuffer); LocalFree(errorBuffer); return errorMsg; } else { return "Error constructing format message for error: " + std::to_string(err); } } #endif // WIN32 } SharedMemory::SharedMemoryError::SharedMemoryError(std::string msg) : RuntimeError(std::move(msg), "SharedMemory") {} SharedMemory::SharedMemoryNotFoundError::SharedMemoryNotFoundError() : SharedMemoryError("Shared memory did not exist") {} void SharedMemory::create(const std::string& name, size_t size) { // adjust for the header size size += sizeof(Header); #ifdef WIN32 HANDLE handle = CreateFileMapping( INVALID_HANDLE_VALUE, // NOLINT nullptr, PAGE_READWRITE, 0, static_cast<DWORD>(size), name.c_str() ); const DWORD error = GetLastError(); if (!handle) { std::string errorMsg = lastErrorToString(error); throw SharedMemoryError(fmt::format( "Error creating shared memory '{}': {}", name, errorMsg )); } if (error == ERROR_ALREADY_EXISTS) { throw SharedMemoryError(fmt::format( "Error creating shared memory '{}': Section exists", name )); } void* memory = MapViewOfFileEx(handle, FILE_MAP_ALL_ACCESS, 0, 0, 0, nullptr); if (!memory) { std::string errorMsg = lastErrorToString(error); throw SharedMemoryError(fmt::format( "Error creating a view on shared memory '{}': {}", name, errorMsg )); } Header* h = header(memory); h->mutex.clear(); h->size = size - sizeof(Header); UnmapViewOfFile(memory); _createdSections[name] = handle; #else // ^^^^ WIN32 // !WIN32 vvvv unsigned int h = hashCRC32(name); int result = shmget(h, size, IPC_CREAT | IPC_EXCL | IPC_R | IPC_W | IPC_M); if (result == -1) { std::string errorMsg = strerror(errno); throw SharedMemoryError(fmt::format( "Error creating shared memory '{}': {}", name, errorMsg )); } void* memory = shmat(result, nullptr, SHM_R | SHM_W); Header* memoryHeader = header(memory); memoryHeader->mutex.clear(); shmdt(memory); #endif } // WIN32 void SharedMemory::remove(const std::string& name) { #ifdef WIN32 if (_createdSections.find(name) == _createdSections.end()) { throw SharedMemoryNotFoundError(); } HANDLE h = _createdSections[name]; _createdSections.erase(name); BOOL result = CloseHandle(h); if (result == 0) { DWORD error = GetLastError(); std::string errorMsg = lastErrorToString(error); throw SharedMemoryError("Error closing handle: " + errorMsg); } #else // ^^^^ WIN32 // !WIN32 vvvv unsigned int h = hashCRC32(name); int result = shmget(h, 0, IPC_R | IPC_W | IPC_M); if (result == -1) { std::string errorMsg = strerror(errno); throw SharedMemoryError("Error while retrieving shared memory: " + errorMsg); } result = shmctl(result, IPC_RMID, nullptr); if (result == -1) { std::string errorMsg = strerror(errno); throw SharedMemoryError("Error while removing shared memory: " + errorMsg); } #endif // WIN32 } bool SharedMemory::exists(const std::string& name) { #ifdef WIN32 HANDLE handle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name.c_str()); if (handle) { // the file exists, so we have to close it immediately to not leak the handle CloseHandle(handle); return true; } // The handle doesn't exist, which can mean two things: the memory mapped file // doesn't exist or it exists but there was an error accessing it const DWORD error = GetLastError(); if (error == ERROR_FILE_NOT_FOUND) { return false; } else { std::string errorMsg = lastErrorToString(error); throw SharedMemoryError( "Error checking if shared memory exists: " + errorMsg ); } #else // ^^^^ WIN32 // !WIN32 vvvv unsigned int h = hashCRC32(name); int result = shmget(h, 0, IPC_EXCL); return result != -1; #endif // WIN32 } SharedMemory::SharedMemory(std::string name) : _name(std::move(name)) { #ifdef WIN32 _sharedMemoryHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, _name.c_str()); if (!_sharedMemoryHandle) { std::string errorMsg = lastErrorToString(GetLastError()); throw SharedMemoryError(fmt::format( "Error accessing shared memory '{}': {}", name, errorMsg )); } _memory = MapViewOfFileEx(_sharedMemoryHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0, nullptr); if (!_memory) { CloseHandle(_sharedMemoryHandle); std::string errorMsg = lastErrorToString(GetLastError()); throw SharedMemoryError(fmt::format( "Error creating view for shared memory '{}': {}", name, errorMsg )); } #else // ^^^^ WIN32 // !WIN32 vvvv unsigned int h = hashCRC32(_name); _sharedMemoryHandle = shmget(h, 0, IPC_R | IPC_W | IPC_M); if (_sharedMemoryHandle == -1) { std::string errorMsg = strerror(errno); throw SharedMemoryError( "Error accessing shared memory '" + name + "': " + errorMsg ); } _memory = shmat(_sharedMemoryHandle, nullptr, SHM_R | SHM_W); if (_memory == reinterpret_cast<void*>(-1)) { std::string errorMsg = strerror(errno); throw SharedMemoryError("Error mapping shared memory '" + name + "':" + errorMsg); } struct shmid_ds sharedMemoryInfo; shmctl(_sharedMemoryHandle, IPC_STAT, &sharedMemoryInfo); _size = sharedMemoryInfo.shm_segsz - sizeof(Header); #endif // WIN32 } SharedMemory::~SharedMemory() { #ifdef WIN32 CloseHandle(_sharedMemoryHandle); UnmapViewOfFile(_memory); #else // ^^^^ WIN32 // !WIN32 vvvv shmdt(_memory); #endif // WIN32 } void* SharedMemory::memory() const { return reinterpret_cast<void*>(reinterpret_cast<char*>(_memory) + sizeof(Header)); } size_t SharedMemory::size() const { #ifdef WIN32 return header(_memory)->size; #else // ^^^^ WIN32 // !WIN32 vvvv return _size; #endif // WIN32 } std::string SharedMemory::name() const { return _name; } void SharedMemory::acquireLock() { Header* h = header(_memory); while (h->mutex.test_and_set()) {} } void SharedMemory::releaseLock() { Header* h = header(_memory); h->mutex.clear(); } } // namespace ghoul
34.620209
90
0.580213
OpenSpace
c1c5de6bb615ca0dfdf7e1ee0a053e96a1ee39ed
2,627
cpp
C++
morphdialog.cpp
emreozanalkan/VPOpenCVProject
953fccdac9fa4c9793e3aeb0b97352ccabd28a64
[ "MIT" ]
1
2021-11-30T11:43:34.000Z
2021-11-30T11:43:34.000Z
morphdialog.cpp
emreozanalkan/VPOpenCVProject
953fccdac9fa4c9793e3aeb0b97352ccabd28a64
[ "MIT" ]
null
null
null
morphdialog.cpp
emreozanalkan/VPOpenCVProject
953fccdac9fa4c9793e3aeb0b97352ccabd28a64
[ "MIT" ]
null
null
null
#include "morphdialog.h" #include "ui_morphdialog.h" #include "pch.h" MorphDialog::MorphDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MorphDialog) { ui->setupUi(this); } MorphDialog::~MorphDialog() { delete ui; } void MorphDialog::on_buttonBox_accepted() { QString morphologicalOperation = ui->comboBoxMorphologicalOperation->currentText(); if(morphologicalOperation == "Dilation") morphOperation = cv::MORPH_DILATE; else if(morphologicalOperation == "Erosion") morphOperation = cv::MORPH_ERODE; else if(morphologicalOperation == "Opening") morphOperation = cv::MORPH_OPEN; else if(morphologicalOperation == "Closing") morphOperation = cv::MORPH_CLOSE; else if(morphologicalOperation == "Morphological Gradient") morphOperation = cv::MORPH_GRADIENT; else if(morphologicalOperation == "Top Hat") morphOperation = cv::MORPH_TOPHAT; else if(morphologicalOperation == "Black Hat") morphOperation = cv::MORPH_BLACKHAT; else morphOperation = cv::MORPH_DILATE; QString kernelTypeString = ui->comboBoxMorphologicalKernelType->currentText(); if(kernelTypeString == "Rectangle") kernelType = cv::MORPH_RECT; else if(kernelTypeString == "Cross") kernelType = cv::MORPH_CROSS; else if(kernelTypeString == "Ellipse") kernelType = cv::MORPH_ELLIPSE; else kernelType = cv::MORPH_RECT; QString imagePaddingMethodString = ui->comboBoxMorphologicalPaddingMethod->currentText(); if(imagePaddingMethodString == "Border Replicate - aaaaaa|abcdefgh|hhhhhhh") // Border Replicate - aaaaaa|abcdefgh|hhhhhhh imagePaddingMethod = cv::BORDER_REPLICATE; else if(imagePaddingMethodString == "Border Reflect - fedcba|abcdefgh|hgfedcb") // Border Reflect - fedcba|abcdefgh|hgfedcb imagePaddingMethod = cv::BORDER_REFLECT; else if(imagePaddingMethodString == "Border Reflect 101 - gfedcb|abcdefgh|gfedcba") // Border Reflect 101 - gfedcb|abcdefgh|gfedcba imagePaddingMethod = cv::BORDER_REFLECT_101; else if(imagePaddingMethodString == "Border Wrap - cdefgh|abcdefgh|abcdefg") // Border Wrap - cdefgh|abcdefgh|abcdefg imagePaddingMethod = cv::BORDER_WRAP; else imagePaddingMethod = cv::BORDER_REPLICATE; iterationCount = ui->spinBoxMorphologicalIterationCount->value(); int kSize = ui->spinBoxMorphologicalKernelSize->value(); kernelSize = new cv::Size(kSize, kSize); anchorPoint = new cv::Point(ui->spinBoxMorphologicalKernelAnchorX->value(), ui->spinBoxMorphologicalKernelAnchorY->value()); }
39.80303
135
0.714884
emreozanalkan
c1c78d1f34346d9b979c3fa80ce828abe80aa0d1
1,733
hpp
C++
container/contiguous_storage_impl.hpp
birbacher/plaincontainers
27386929da24b3d82887699458c99fc293618d05
[ "BSL-1.0" ]
null
null
null
container/contiguous_storage_impl.hpp
birbacher/plaincontainers
27386929da24b3d82887699458c99fc293618d05
[ "BSL-1.0" ]
null
null
null
container/contiguous_storage_impl.hpp
birbacher/plaincontainers
27386929da24b3d82887699458c99fc293618d05
[ "BSL-1.0" ]
null
null
null
#ifndef NEWCONTAINER_CONTAINER_CONTIGUOUSSTORAGE_IMPL_INCLUDED #define NEWCONTAINER_CONTAINER_CONTIGUOUSSTORAGE_IMPL_INCLUDED #include "container/contiguous_storage.hpp" #include "memory/interface/allocator.hpp" #include "memory/adapter/typed_allocator.hpp" #include <cassert> #include <memory> #include <utility> namespace container { template<typename ElemType, typename Allocator> contiguous_storage<ElemType, Allocator>::contiguous_storage( allocator_type& allocator_instance, size_type const element_count ) noexcept : allocator_adapter_instance(allocator_instance) , storage(allocator_adapter_instance.allocate(element_count)) , capacity(element_count) { } template<typename ElemType, typename Allocator> contiguous_storage<ElemType, Allocator>::~contiguous_storage() noexcept { if(storage) allocator_adapter_instance.deallocate(storage, capacity); } template<typename ElemType, typename Allocator> contiguous_storage<ElemType, Allocator>::contiguous_storage( contiguous_storage&& other ) noexcept : contiguous_storage() { swap(other); } template<typename ElemType, typename Allocator> auto contiguous_storage<ElemType, Allocator>::operator = ( contiguous_storage&& other ) noexcept -> contiguous_storage& { contiguous_storage temp(std::move(other)); swap(temp); return *this; } template<typename ElemType, typename Allocator> void contiguous_storage<ElemType, Allocator>::swap( contiguous_storage& other ) noexcept { using std::swap; swap(storage, other.storage); swap(capacity, other.capacity); swap(allocator_adapter_instance, other.allocator_adapter_instance); } } //namespace container #endif
26.661538
71
0.767455
birbacher
c1cba5e3548121de6d7a0cbe39a36f7beb25fe6b
13,348
cpp
C++
flatland_server/src/debug_visualization.cpp
schmiddey/flatland
7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb
[ "BSD-3-Clause" ]
null
null
null
flatland_server/src/debug_visualization.cpp
schmiddey/flatland
7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb
[ "BSD-3-Clause" ]
null
null
null
flatland_server/src/debug_visualization.cpp
schmiddey/flatland
7ae1c7e5a3edcad372ccde56fd7b5e79484ffeeb
[ "BSD-3-Clause" ]
null
null
null
/* * ______ __ __ __ * /\ _ \ __ /\ \/\ \ /\ \__ * \ \ \L\ \ __ __ /\_\ \_\ \ \ \____ ___\ \ ,_\ ____ * \ \ __ \/\ \/\ \\/\ \ /'_` \ \ '__`\ / __`\ \ \/ /',__\ * \ \ \/\ \ \ \_/ |\ \ \/\ \L\ \ \ \L\ \/\ \L\ \ \ \_/\__, `\ * \ \_\ \_\ \___/ \ \_\ \___,_\ \_,__/\ \____/\ \__\/\____/ * \/_/\/_/\/__/ \/_/\/__,_ /\/___/ \/___/ \/__/\/___/ * @copyright Copyright 2017 Avidbots Corp. * @name debug_visualization.cpp * @brief Transform box2d types into published visualization messages * @author Joseph Duchesne * * Software License Agreement (BSD License) * * Copyright (c) 2017, Avidbots Corp. * 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 the Avidbots Corp. 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. */ #include "flatland_server/debug_visualization.h" #include <Box2D/Box2D.h> #include <rclcpp/rclcpp.hpp> #include <tf2/LinearMath/Quaternion.h> #include <tf2/convert.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <map> #include <string> namespace flatland_server { DebugVisualization::DebugVisualization(rclcpp::Node::SharedPtr node) : node_(node) { topic_list_publisher_ = node_->create_publisher<flatland_msgs::msg::DebugTopicList>("topics", 1); } std::shared_ptr<DebugVisualization> DebugVisualization::Get(rclcpp::Node::SharedPtr node) { static std::shared_ptr<DebugVisualization> instance; // todo: fix this? How should singletons work with shared pointers? if (!instance) { instance = std::make_shared<DebugVisualization>(node); } return instance; } void DebugVisualization::JointToMarkers( visualization_msgs::msg::MarkerArray& markers, b2Joint* joint, float r, float g, float b, float a) { if (joint->GetType() == e_distanceJoint || joint->GetType() == e_pulleyJoint || joint->GetType() == e_mouseJoint) { RCLCPP_ERROR(rclcpp::get_logger("DebugVis"), "Unimplemented visualization joints. See b2World.cpp for " "implementation"); return; } visualization_msgs::msg::Marker marker; marker.header.frame_id = "map"; marker.color.r = r; marker.color.g = g; marker.color.b = b; marker.color.a = a; marker.type = marker.LINE_LIST; marker.scale.x = 0.01; geometry_msgs::msg::Point p_a1, p_a2, p_b1, p_b2; p_a1.x = joint->GetAnchorA().x; p_a1.y = joint->GetAnchorA().y; p_a2.x = joint->GetAnchorB().x; p_a2.y = joint->GetAnchorB().y; p_b1.x = joint->GetBodyA()->GetPosition().x; p_b1.y = joint->GetBodyA()->GetPosition().y; p_b2.x = joint->GetBodyB()->GetPosition().x; p_b2.y = joint->GetBodyB()->GetPosition().y; // Visualization shows lines from bodyA to anchorA, bodyB to anchorB, and // anchorA to anchorB marker.id = markers.markers.size(); marker.points.push_back(p_b1); marker.points.push_back(p_a1); marker.points.push_back(p_b2); marker.points.push_back(p_a2); marker.points.push_back(p_a1); marker.points.push_back(p_a2); markers.markers.push_back(marker); marker.id = markers.markers.size(); marker.type = marker.CUBE_LIST; marker.scale.x = marker.scale.y = marker.scale.z = 0.03; marker.points.clear(); marker.points.push_back(p_a1); marker.points.push_back(p_a2); marker.points.push_back(p_b1); marker.points.push_back(p_b2); markers.markers.push_back(marker); } void DebugVisualization::BodyToMarkers(visualization_msgs::msg::MarkerArray& markers, b2Body* body, float r, float g, float b, float a) { b2Fixture* fixture = body->GetFixtureList(); while (fixture != NULL) { // traverse fixture linked list visualization_msgs::msg::Marker marker; marker.header.frame_id = "map"; marker.id = markers.markers.size(); marker.color.r = r; marker.color.g = g; marker.color.b = b; marker.color.a = a; marker.pose.position.x = body->GetPosition().x; marker.pose.position.y = body->GetPosition().y; tf2::Quaternion q; // use tf2 to convert 2d yaw -> 3d quaternion q.setRPY(0, 0, body->GetAngle()); // from euler angles: roll, pitch, yaw marker.pose.orientation = tf2::toMsg(q); bool add_marker = true; // Get the shape from the fixture switch (fixture->GetType()) { case b2Shape::e_circle: { b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); marker.type = marker.SPHERE_LIST; float diameter = circle->m_radius * 2.0; marker.scale.z = 0.01; marker.scale.x = diameter; marker.scale.y = diameter; geometry_msgs::msg::Point p; p.x = circle->m_p.x; p.y = circle->m_p.y; marker.points.push_back(p); } break; case b2Shape::e_polygon: { // Convert b2Polygon -> LINE_STRIP b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); marker.type = marker.LINE_STRIP; marker.scale.x = 0.03; // 3cm wide lines for (int i = 0; i < poly->m_count; i++) { geometry_msgs::msg::Point p; p.x = poly->m_vertices[i].x; p.y = poly->m_vertices[i].y; marker.points.push_back(p); } marker.points.push_back(marker.points[0]); // Close the shape } break; case b2Shape::e_edge: { // Convert b2Edge -> LINE_LIST geometry_msgs::msg::Point p; // b2Edge uses vertex1 and 2 for its edges b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); // If the last marker is a line list, extend it if (markers.markers.size() > 0 && markers.markers.back().type == marker.LINE_LIST) { add_marker = false; p.x = edge->m_vertex1.x; p.y = edge->m_vertex1.y; markers.markers.back().points.push_back(p); p.x = edge->m_vertex2.x; p.y = edge->m_vertex2.y; markers.markers.back().points.push_back(p); } else { // otherwise create a new line list marker.type = marker.LINE_LIST; marker.scale.x = 0.03; // 3cm wide lines p.x = edge->m_vertex1.x; p.y = edge->m_vertex1.y; marker.points.push_back(p); p.x = edge->m_vertex2.x; p.y = edge->m_vertex2.y; marker.points.push_back(p); } } break; default: // Unsupported shape rclcpp::Clock steady_clock = rclcpp::Clock(RCL_STEADY_TIME); RCLCPP_WARN_THROTTLE(rclcpp::get_logger("Debug Visualization"), steady_clock, 1000, "Unsupported Box2D shape %d", static_cast<int>(fixture->GetType())); fixture = fixture->GetNext(); continue; // Do not add broken marker break; } if (add_marker) { markers.markers.push_back(marker); // Add the new marker } fixture = fixture->GetNext(); // Traverse the linked list of fixtures } } void DebugVisualization::Publish(const Timekeeper& timekeeper) { // Iterate over the topics_ map as pair(name, topic) std::vector<std::string> to_delete; for (auto& topic : topics_) { if (!topic.second.needs_publishing) { continue; } // since if empty markers are published rviz will continue to publish // using the old data, delete the topic list if (topic.second.markers.markers.size() == 0) { to_delete.push_back(topic.first); } else { // Iterate the marker array to update all the timestamps for (unsigned int i = 0; i < topic.second.markers.markers.size(); i++) { topic.second.markers.markers[i].header.stamp = timekeeper.GetSimTime(); } topic.second.publisher->publish(topic.second.markers); topic.second.needs_publishing = false; } } if (to_delete.size() > 0) { for (const auto& topic : to_delete) { RCLCPP_WARN(rclcpp::get_logger("DebugVis"), "Deleting topic %s", topic.c_str()); topics_.erase(topic); } PublishTopicList(); } } void DebugVisualization::VisualizeLayer(std::string name, Body* body) { AddTopicIfNotExist(name); b2Fixture* fixture = body->physics_body_->GetFixtureList(); visualization_msgs::msg::Marker marker; if (fixture == NULL) return; // Nothing to visualize, empty linked list while (fixture != NULL) { // traverse fixture linked list marker.header.frame_id = "map"; marker.id = topics_[name].markers.markers.size(); marker.color.r = body->color_.r; marker.color.g = body->color_.g; marker.color.b = body->color_.b; marker.color.a = body->color_.a; marker.scale.x = marker.scale.y = marker.scale.z = 1.0; marker.frame_locked = true; marker.pose.position.x = body->physics_body_->GetPosition().x; marker.pose.position.y = body->physics_body_->GetPosition().y; tf2::Quaternion q; // use tf2 to convert 2d yaw -> 3d quaternion q.setRPY(0, 0, body->physics_body_ ->GetAngle()); // from euler angles: roll, pitch, yaw marker.pose.orientation = tf2::toMsg(q); marker.type = marker.TRIANGLE_LIST; YamlReader reader(node_, body->properties_); YamlReader debug_reader = reader.SubnodeOpt("debug", YamlReader::NodeTypeCheck::MAP); float min_z = debug_reader.Get<float>("min_z", 0.0); float max_z = debug_reader.Get<float>("max_z", 1.0); // Get the shape from the fixture if (fixture->GetType() == b2Shape::e_edge) { geometry_msgs::msg::Point p; // b2Edge uses vertex1 and 2 for its edges b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); p.x = edge->m_vertex1.x; p.y = edge->m_vertex1.y; p.z = min_z; marker.points.push_back(p); p.x = edge->m_vertex2.x; p.y = edge->m_vertex2.y; p.z = min_z; marker.points.push_back(p); p.x = edge->m_vertex2.x; p.y = edge->m_vertex2.y; p.z = max_z; marker.points.push_back(p); p.x = edge->m_vertex1.x; p.y = edge->m_vertex1.y; p.z = min_z; marker.points.push_back(p); p.x = edge->m_vertex2.x; p.y = edge->m_vertex2.y; p.z = max_z; marker.points.push_back(p); p.x = edge->m_vertex1.x; p.y = edge->m_vertex1.y; p.z = max_z; marker.points.push_back(p); } fixture = fixture->GetNext(); // Traverse the linked list of fixtures } topics_[name].markers.markers.push_back(marker); // Add the new marker topics_[name].needs_publishing = true; } void DebugVisualization::Visualize(std::string name, b2Body* body, float r, float g, float b, float a) { AddTopicIfNotExist(name); BodyToMarkers(topics_[name].markers, body, r, g, b, a); topics_[name].needs_publishing = true; } void DebugVisualization::Visualize(std::string name, b2Joint* joint, float r, float g, float b, float a) { AddTopicIfNotExist(name); JointToMarkers(topics_[name].markers, joint, r, g, b, a); topics_[name].needs_publishing = true; } void DebugVisualization::Reset(std::string name) { if (topics_.count(name) > 0) { // If the topic exists, clear it topics_[name].markers.markers.clear(); topics_[name].needs_publishing = true; } } void DebugVisualization::AddTopicIfNotExist(const std::string& name) { // If the topic doesn't exist yet, create it if (topics_.count(name) == 0) { topics_[name] = { node_->create_publisher<visualization_msgs::msg::MarkerArray>(name, 1), true, visualization_msgs::msg::MarkerArray()}; RCLCPP_INFO_ONCE(rclcpp::get_logger("Debug Visualization"), "Visualizing %s", name.c_str()); PublishTopicList(); } } void DebugVisualization::PublishTopicList() { flatland_msgs::msg::DebugTopicList topic_list; for (auto const& topic_pair : topics_) topic_list.topics.push_back(topic_pair.first); topic_list_publisher_->publish(topic_list); } } //namespace flatland_server
36.173442
121
0.641744
schmiddey
c1cd25572d1bd1f2e3eeef5280aa22a2722479d7
12,144
cpp
C++
src/coreclr/jit/likelyclass.cpp
JimmyCushnie/runtime
b7eb82871f1d742efb444873e11dd6241cea73d2
[ "MIT" ]
3
2021-06-24T15:39:52.000Z
2021-11-04T02:13:43.000Z
src/coreclr/jit/likelyclass.cpp
JimmyCushnie/runtime
b7eb82871f1d742efb444873e11dd6241cea73d2
[ "MIT" ]
18
2019-12-03T00:21:59.000Z
2022-01-30T04:45:58.000Z
src/coreclr/jit/likelyclass.cpp
JimmyCushnie/runtime
b7eb82871f1d742efb444873e11dd6241cea73d2
[ "MIT" ]
2
2022-03-05T21:34:42.000Z
2022-03-10T15:17:42.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX Likely Class Processing XX XX XX XX Parses Pgo data to find the most likely class in use at a given XX XX IL offset in a method. Used by both the JIT, and by crossgen XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #ifndef DLLEXPORT #define DLLEXPORT #endif // !DLLEXPORT // Data item in class profile histogram // struct LikelyClassHistogramEntry { // Class that was observed at runtime INT_PTR m_mt; // This may be an "unknown type handle" // Number of observations in the table unsigned m_count; }; // Summarizes a ClassProfile table by forming a Histogram // struct LikelyClassHistogram { LikelyClassHistogram(INT_PTR* histogramEntries, unsigned entryCount); // Sum of counts from all entries in the histogram. This includes "unknown" entries which are not captured in // m_histogram unsigned m_totalCount; // Rough guess at count of unknown types unsigned m_unknownTypes; // Histogram entries, in no particular order. LikelyClassHistogramEntry m_histogram[64]; UINT32 countHistogramElements = 0; LikelyClassHistogramEntry HistogramEntryAt(unsigned index) { return m_histogram[index]; } }; //------------------------------------------------------------------------ // LikelyClassHistogram::LikelyClassHistgram: construct a new histogram // // Arguments: // histogramEntries - pointer to the table portion of a ClassProfile* object (see corjit.h) // entryCount - number of entries in the table to examine // LikelyClassHistogram::LikelyClassHistogram(INT_PTR* histogramEntries, unsigned entryCount) { m_unknownTypes = 0; m_totalCount = 0; uint32_t unknownTypeHandleMask = 0; for (unsigned k = 0; k < entryCount; k++) { if (histogramEntries[k] == 0) { continue; } m_totalCount++; INT_PTR currentEntry = histogramEntries[k]; bool found = false; unsigned h = 0; for (; h < countHistogramElements; h++) { if (m_histogram[h].m_mt == currentEntry) { m_histogram[h].m_count++; found = true; break; } } if (!found) { if (countHistogramElements >= _countof(m_histogram)) { continue; } LikelyClassHistogramEntry newEntry; newEntry.m_mt = currentEntry; newEntry.m_count = 1; m_histogram[countHistogramElements++] = newEntry; } } } //------------------------------------------------------------------------ // getLikelyClass: find class profile data for an IL offset, and return the most likely class // // Arguments: // schema - profile schema // countSchemaItems - number of items in the schema // pInstrumentationData - associated data // ilOffset - il offset of the callvirt // pLikelihood - [OUT] likelihood of observing that entry [0...100] // pNumberOfClasses - [OUT] estimated number of classes seen at runtime // // Returns: // Class handle for the most likely class, or nullptr // // Notes: // A "monomorphic" call site will return likelihood 100 and number of entries = 1. // // This is used by the devirtualization logic below, and by crossgen2 when producing // the R2R image (to reduce the sizecost of carrying the type histogram) // // This code can runs without a jit instance present, so JITDUMP and related // cannot be used. // extern "C" DLLEXPORT CORINFO_CLASS_HANDLE WINAPI getLikelyClass(ICorJitInfo::PgoInstrumentationSchema* schema, UINT32 countSchemaItems, BYTE* pInstrumentationData, int32_t ilOffset, UINT32* pLikelihood, UINT32* pNumberOfClasses) { *pLikelihood = 0; *pNumberOfClasses = 0; if (schema == NULL) return NULL; for (COUNT_T i = 0; i < countSchemaItems; i++) { if (schema[i].ILOffset != (int32_t)ilOffset) continue; if ((schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::GetLikelyClass) && (schema[i].Count == 1)) { *pNumberOfClasses = (UINT32)schema[i].Other >> 8; *pLikelihood = (UINT32)(schema[i].Other & 0xFF); INT_PTR result = *(INT_PTR*)(pInstrumentationData + schema[i].Offset); if (ICorJitInfo::IsUnknownTypeHandle(result)) return NULL; else return (CORINFO_CLASS_HANDLE)result; } bool isHistogramCount = (schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramIntCount) || (schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramLongCount); if (isHistogramCount && (schema[i].Count == 1) && ((i + 1) < countSchemaItems) && (schema[i + 1].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramTypeHandle)) { // Form a histogram // LikelyClassHistogram h((INT_PTR*)(pInstrumentationData + schema[i + 1].Offset), schema[i + 1].Count); // Use histogram count as number of classes estimate // *pNumberOfClasses = (uint32_t)h.countHistogramElements + h.m_unknownTypes; // Report back what we've learned // (perhaps, use count to augment likelihood?) // switch (*pNumberOfClasses) { case 0: { return NULL; } break; case 1: { if (ICorJitInfo::IsUnknownTypeHandle(h.HistogramEntryAt(0).m_mt)) { return NULL; } *pLikelihood = 100; return (CORINFO_CLASS_HANDLE)h.HistogramEntryAt(0).m_mt; } break; case 2: { if ((h.HistogramEntryAt(0).m_count >= h.HistogramEntryAt(1).m_count) && !ICorJitInfo::IsUnknownTypeHandle(h.HistogramEntryAt(0).m_mt)) { *pLikelihood = (100 * h.HistogramEntryAt(0).m_count) / h.m_totalCount; return (CORINFO_CLASS_HANDLE)h.HistogramEntryAt(0).m_mt; } else if (!ICorJitInfo::IsUnknownTypeHandle(h.HistogramEntryAt(1).m_mt)) { *pLikelihood = (100 * h.HistogramEntryAt(1).m_count) / h.m_totalCount; return (CORINFO_CLASS_HANDLE)h.HistogramEntryAt(1).m_mt; } else { return NULL; } } break; default: { // Find maximum entry and return it // unsigned maxKnownIndex = 0; unsigned maxKnownCount = 0; for (unsigned m = 0; m < h.countHistogramElements; m++) { if ((h.HistogramEntryAt(m).m_count > maxKnownCount) && !ICorJitInfo::IsUnknownTypeHandle(h.HistogramEntryAt(m).m_mt)) { maxKnownIndex = m; maxKnownCount = h.HistogramEntryAt(m).m_count; } } if (maxKnownCount > 0) { *pLikelihood = (100 * maxKnownCount) / h.m_totalCount; return (CORINFO_CLASS_HANDLE)h.HistogramEntryAt(maxKnownIndex).m_mt; } return NULL; } break; } } } // Failed to find histogram data for this method // return NULL; } //------------------------------------------------------------------------ // getRandomClass: find class profile data for an IL offset, and return // one of the possible classes at random // // Arguments: // schema - profile schema // countSchemaItems - number of items in the schema // pInstrumentationData - associated data // ilOffset - il offset of the callvirt // random - randomness generator // // Returns: // Randomly observed class, or nullptr. // CORINFO_CLASS_HANDLE Compiler::getRandomClass(ICorJitInfo::PgoInstrumentationSchema* schema, UINT32 countSchemaItems, BYTE* pInstrumentationData, int32_t ilOffset, CLRRandom* random) { if (schema == nullptr) { return NO_CLASS_HANDLE; } for (COUNT_T i = 0; i < countSchemaItems; i++) { if (schema[i].ILOffset != (int32_t)ilOffset) { continue; } if ((schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::GetLikelyClass) && (schema[i].Count == 1)) { INT_PTR result = *(INT_PTR*)(pInstrumentationData + schema[i].Offset); if (ICorJitInfo::IsUnknownTypeHandle(result)) { return NO_CLASS_HANDLE; } else { return (CORINFO_CLASS_HANDLE)result; } } bool isHistogramCount = (schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramIntCount) || (schema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramLongCount); if (isHistogramCount && (schema[i].Count == 1) && ((i + 1) < countSchemaItems) && (schema[i + 1].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::TypeHandleHistogramTypeHandle)) { // Form a histogram // LikelyClassHistogram h((INT_PTR*)(pInstrumentationData + schema[i + 1].Offset), schema[i + 1].Count); if (h.countHistogramElements == 0) { return NO_CLASS_HANDLE; } // Choose an entry at random. // unsigned randomEntryIndex = random->Next(0, h.countHistogramElements - 1); LikelyClassHistogramEntry randomEntry = h.HistogramEntryAt(randomEntryIndex); if (ICorJitInfo::IsUnknownTypeHandle(randomEntry.m_mt)) { return NO_CLASS_HANDLE; } return (CORINFO_CLASS_HANDLE)randomEntry.m_mt; } } return NO_CLASS_HANDLE; }
36.911854
120
0.523798
JimmyCushnie
c1cd7ca6031e50ca4a041303f4cf8898726f2ed3
1,735
cpp
C++
functions/func.cpp
lucienmakutano/learn-cpp
de78caba34295938462b229a8669feaf401b3dbe
[ "MIT" ]
null
null
null
functions/func.cpp
lucienmakutano/learn-cpp
de78caba34295938462b229a8669feaf401b3dbe
[ "MIT" ]
null
null
null
functions/func.cpp
lucienmakutano/learn-cpp
de78caba34295938462b229a8669feaf401b3dbe
[ "MIT" ]
null
null
null
#include "func.h" #include <iostream> #include <string> #include <vector> using namespace std; void print_vector(vector<string> v); void print_vector(vector<int> v = {1, 2, 3, 4, 5}); void print_array(int arr[], size_t size); // mutable void print_array(const int arr[], size_t size); // immutable void pass_by_ref(int &num); // mutable void pass_by_const_ref(const int &num); // immutable void swap(int &a, int &b); void scopes(); void print_vector(vector<string> v) { for (int i = 0; i < v.size(); i++) { cout << v[i] << endl; } } // function overloading + default arguments void print_vector(vector<int> v) { for (int i = 0; i < v.size(); i++) { cout << v[i] << endl; } } // In this case the function can modify the array elements void print_array(int arr[], size_t size) { for (int i = 0; i < size; i++) { cout << arr[i] << endl; arr[i] = i; } } // To protect ourselves from modifying the array elements, // we can use `const` to make the array a read-only array void print_array(const int arr[], size_t size) { for (int i = 0; i < size; i++) { cout << arr[i] << endl; } } void pass_by_ref(int &num) { num = num + 1; } void pass_by_const_ref(const int &num) // immutable { // num = num + 1; // error cout << num << endl; } void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void scopes() { int a = 10; { int a = 20; cout << a << endl; // 20 } cout << a << endl; // 10 } void func_work() { vector<string> v; v.push_back("Hello"); v.push_back("World"); v.push_back("!"); print_vector(v); print_vector(); }
18.263158
60
0.55562
lucienmakutano
c1d398d751c40a07b8c1e391757793dd50315106
2,047
cpp
C++
extensions/test/nsphere/nsphere-multi_within.cpp
jonasdmentia/geometry
097f6fdbe98118be82cd1917cc72c3c6a37bdf30
[ "BSL-1.0" ]
326
2015-02-08T13:47:49.000Z
2022-03-16T02:13:59.000Z
extensions/test/nsphere/nsphere-multi_within.cpp
jonasdmentia/geometry
097f6fdbe98118be82cd1917cc72c3c6a37bdf30
[ "BSL-1.0" ]
623
2015-01-02T23:45:23.000Z
2022-03-09T11:15:23.000Z
extensions/test/nsphere/nsphere-multi_within.cpp
jonasdmentia/geometry
097f6fdbe98118be82cd1917cc72c3c6a37bdf30
[ "BSL-1.0" ]
215
2015-01-14T15:50:38.000Z
2022-02-23T03:58:36.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <geometry_test_common.hpp> #include <boost/geometry/algorithms/correct.hpp> #include <boost/geometry/algorithms/within.hpp> #include <boost/geometry/core/cs.hpp> #include <boost/geometry/geometries/box.hpp> #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry/geometries/ring.hpp> #include <boost/geometry/geometries/linestring.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/point_xy.hpp> #include <boost/geometry/geometries/polygon.hpp> #include <boost/geometry/multi/algorithms/within.hpp> #include <boost/geometry/multi/core/point_type.hpp> #include <boost/geometry/multi/geometries/multi_geometries.hpp> #include <boost/geometry/strategies/strategies.hpp> #include <boost/geometry/extensions/nsphere/nsphere.hpp> int test_main( int , char* [] ) { typedef bg::model::d2::point_xy<double> gl_point; typedef bg::model::nsphere<gl_point, double> gl_circle; typedef bg::model::ring<gl_point> gl_ring; typedef bg::model::polygon<gl_point> gl_polygon; typedef bg::model::multi_polygon<gl_polygon> gl_multi_polygon; gl_circle circle(gl_point(1, 1), 2.5); gl_ring ring; ring.push_back(gl_point(0,0)); ring.push_back(gl_point(1,0)); ring.push_back(gl_point(1,1)); ring.push_back(gl_point(0,1)); bg::correct(ring); gl_polygon pol; pol.outer() = ring; gl_multi_polygon multi_polygon; multi_polygon.push_back(pol); // Multipolygon in circle BOOST_CHECK_EQUAL(bg::within(multi_polygon, circle), true); multi_polygon.front().outer().insert(multi_polygon.front().outer().begin() + 1, gl_point(10, 10)); BOOST_CHECK_EQUAL(bg::within(multi_polygon, circle), false); return 0; }
35.912281
102
0.745481
jonasdmentia
c1d6dd87f8eae1fe05c6d040b6aaee7b6fac87aa
7,257
cpp
C++
Official Windows Platform Sample/Windows Phone 8.1 samples/[C++]-Windows Phone 8.1 samples/Association launching sample/C++/Shared/App.xaml.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
Official Windows Platform Sample/Windows Phone 8.1 samples/[C++]-Windows Phone 8.1 samples/Association launching sample/C++/Shared/App.xaml.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Official Windows Platform Sample/Windows Phone 8.1 samples/[C++]-Windows Phone 8.1 samples/Association launching sample/C++/Shared/App.xaml.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2015-12-25T11:15:10.000Z
2015-12-25T11:15:10.000Z
// Copyright (c) Microsoft. All rights reserved. #include "pch.h" using namespace SDKSample; using namespace Concurrency; using namespace Platform; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::Activation; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Interop; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> App::App() { InitializeComponent(); Suspending += ref new SuspendingEventHandler(this, &App::OnSuspending); } Frame^ App::CreateRootFrame() { Frame^ rootFrame = dynamic_cast<Frame^>(Window::Current->Content); if (rootFrame == nullptr) { // Create a Frame to act as the navigation context rootFrame = ref new Frame(); // Set the default language rootFrame->Language = Windows::Globalization::ApplicationLanguages::Languages->GetAt(0); rootFrame->NavigationFailed += ref new Windows::UI::Xaml::Navigation::NavigationFailedEventHandler(this, &App::OnNavigationFailed); // Place the frame in the current Window Window::Current->Content = rootFrame; } return rootFrame; } concurrency::task<void> App::RestoreStatus(ApplicationExecutionState previousExecutionState) { auto prerequisite = task<void>([](){}); if (previousExecutionState == ApplicationExecutionState::Terminated) { prerequisite = SuspensionManager::RestoreAsync(); } return prerequisite; } void App::OnFileActivated(Windows::ApplicationModel::Activation::FileActivatedEventArgs^ e) { auto rootFrame = CreateRootFrame(); RestoreStatus(e->PreviousExecutionState).then([=](task<void> prerequisite) { try { prerequisite.get(); } catch (Platform::Exception^) { //Something went wrong restoring state. //Assume there is no state and continue } //MainPage is always in rootFrame so we don't have to worry about restoring the navigation state on resume rootFrame->Navigate(TypeName(MainPage::typeid)); auto p = dynamic_cast<MainPage^>(rootFrame->Content); p->FileEvent = e; p->ProtocolEvent = nullptr; p->NavigateToFilePage(); // Ensure the current window is active Window::Current->Activate(); }, task_continuation_context::use_current()); } void App::OnActivated(IActivatedEventArgs^ e) { if (e->Kind == Windows::ApplicationModel::Activation::ActivationKind::Protocol) { auto rootFrame = CreateRootFrame(); RestoreStatus(e->PreviousExecutionState).then([=](task<void> prerequisite) { try { prerequisite.get(); } catch (Platform::Exception^) { //Something went wrong restoring state. //Assume there is no state and continue } //MainPage is always in rootFrame so we don't have to worry about restoring the navigation state on resume rootFrame->Navigate(TypeName(MainPage::typeid)); auto p = dynamic_cast<MainPage^>(rootFrame->Content); p->FileEvent = nullptr; p->ProtocolEvent = safe_cast<Windows::ApplicationModel::Activation::ProtocolActivatedEventArgs^>(e); p->NavigateToProtocolPage(); // Ensure the current window is active Window::Current->Activate(); }, task_continuation_context::use_current()); } #if WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP else if (e->Kind == Windows::ApplicationModel::Activation::ActivationKind::PickFileContinuation) { Application::OnActivated(e); continuationManager = ref new ContinuationManager(); RestoreStatus(e->PreviousExecutionState).then([=](task<void> prerequisite) { try { prerequisite.get(); } catch (Platform::Exception^) { //Something went wrong restoring state. //Assume there is no state and continue } auto continuationEventArgs = dynamic_cast<IContinuationActivatedEventArgs^>(e); if (continuationEventArgs != nullptr) { MainPage^ mainPage = MainPage::Current; Frame^ scenarioFrame = dynamic_cast<Frame^>(mainPage->FindName("ScenarioFrame")); if (scenarioFrame == nullptr) { return; } continuationManager->Continue(continuationEventArgs, scenarioFrame); } }, task_continuation_context::use_current()); } #endif //WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> void App::OnLaunched(LaunchActivatedEventArgs^ e) { auto rootFrame = CreateRootFrame(); RestoreStatus(e->PreviousExecutionState).then([=](task<void> prerequisite) { try { prerequisite.get(); } catch (Platform::Exception^) { //Something went wrong restoring state. //Assume there is no state and continue } //MainPage is always in rootFrame so we don't have to worry about restoring the navigation state on resume rootFrame->Navigate(TypeName(MainPage::typeid), e->Arguments); // Ensure the current window is active Window::Current->Activate(); }, task_continuation_context::use_current()); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> void App::OnSuspending(Object^ sender, SuspendingEventArgs^ e) { (void)sender; // Unused parameter auto deferral = e->SuspendingOperation->GetDeferral(); SuspensionManager::SaveAsync().then([=]() { deferral->Complete(); }); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void App::OnNavigationFailed(Platform::Object ^sender, Windows::UI::Xaml::Navigation::NavigationFailedEventArgs ^e) { throw ref new FailureException("Failed to load Page " + e->SourcePageType.Name); }
34.393365
139
0.656194
zzgchina888
c1df72113b58732f01bd47e8eb6307510913a3db
3,857
cpp
C++
plugins/logging/logging.cpp
rpastrana/HPCC-Platform
489454bd326ed6a39228c81f5d837c276724c022
[ "Apache-2.0" ]
null
null
null
plugins/logging/logging.cpp
rpastrana/HPCC-Platform
489454bd326ed6a39228c81f5d837c276724c022
[ "Apache-2.0" ]
null
null
null
plugins/logging/logging.cpp
rpastrana/HPCC-Platform
489454bd326ed6a39228c81f5d837c276724c022
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. 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 <time.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "logging.hpp" #include "jlog.hpp" #define LOGGING_VERSION "LOGGING 1.0.1" static const char * compatibleVersions[] = { "LOGGING 1.0.0 [66aec3fb4911ceda247c99d6a2a5944c]", // linux version LOGGING_VERSION, NULL }; static const char * EclDefinition = "export Logging := SERVICE : time\n" " dbglog(const string src) : c,action,entrypoint='logDbgLog'; \n" " addWorkunitInformation(const varstring txt, unsigned code=0, unsigned severity=0, const varstring source='user') : ctxmethod,action,entrypoint='addWuException'; \n" " addWorkunitWarning(const varstring txt, unsigned code=0, unsigned severity=1, const varstring source='user') : ctxmethod,action,entrypoint='addWuException'; \n" " addWorkunitError(const varstring txt, unsigned code=0, unsigned severity=2, const varstring source='user') : ctxmethod,action,entrypoint='addWuException'; \n" " addWorkunitInformationEx(const varstring txt, unsigned code=0, unsigned severity=0, unsigned audience=2, const varstring source='user') : ctxmethod,action,entrypoint='addWuExceptionEx'; \n" " addWorkunitWarningEx(const varstring txt, unsigned code=0, unsigned severity=1, unsigned audience=2, const varstring source='user') : ctxmethod,action,entrypoint='addWuExceptionEx'; \n" " addWorkunitErrorEx(const varstring txt, unsigned code=0, unsigned severity=2, unsigned audience=2, const varstring source='user') : ctxmethod,action,entrypoint='addWuExceptionEx'; \n" " varstring getGlobalId() : c,context,entrypoint='logGetGlobalId'; \n" " varstring getLocalId() : c,context,entrypoint='logGetLocalId'; \n" " varstring getCallerId() : c,context,entrypoint='logGetCallerId'; \n" "END;"; LOGGING_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb) { if (pb->size == sizeof(ECLPluginDefinitionBlockEx)) { ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb; pbx->compatibleVersions = compatibleVersions; } else if (pb->size != sizeof(ECLPluginDefinitionBlock)) return false; pb->magicVersion = PLUGIN_VERSION; pb->version = LOGGING_VERSION; pb->moduleName = "lib_logging"; pb->ECL = EclDefinition; pb->flags = PLUGIN_IMPLICIT_MODULE; pb->description = "Logging library"; return true; } //------------------------------------------------------------------------------------------------------------------------------------------- LOGGING_API void LOGGING_CALL logDbgLog(unsigned srcLen, const char * src) { DBGLOG("%.*s", srcLen, src); } LOGGING_API char * LOGGING_CALL logGetGlobalId(ICodeContext *ctx) { StringBuffer ret(ctx->queryContextLogger().queryGlobalId()); return ret.detach(); } LOGGING_API char * LOGGING_CALL logGetLocalId(ICodeContext *ctx) { StringBuffer ret(ctx->queryContextLogger().queryLocalId()); return ret.detach(); } LOGGING_API char * LOGGING_CALL logGetCallerId(ICodeContext *ctx) { StringBuffer ret(ctx->queryContextLogger().queryCallerId()); return ret.detach(); }
44.333333
192
0.681618
rpastrana
c1e40a0ff91577b0b279fbd5a76a1932fb55a497
2,277
hpp
C++
cppcache/src/StructSetImpl.hpp
mcmellawatt/geode-native
53315985c4386e6781473c5713d638c8139e3e8e
[ "Apache-2.0" ]
null
null
null
cppcache/src/StructSetImpl.hpp
mcmellawatt/geode-native
53315985c4386e6781473c5713d638c8139e3e8e
[ "Apache-2.0" ]
null
null
null
cppcache/src/StructSetImpl.hpp
mcmellawatt/geode-native
53315985c4386e6781473c5713d638c8139e3e8e
[ "Apache-2.0" ]
null
null
null
#pragma once #ifndef GEODE_STRUCTSETIMPL_H_ #define GEODE_STRUCTSETIMPL_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. */ #include <geode/internal/geode_globals.hpp> #include <geode/StructSet.hpp> #include <geode/Struct.hpp> #include <geode/CacheableBuiltins.hpp> #include <geode/SelectResultsIterator.hpp> #include <string> #include <map> /** * @file */ namespace apache { namespace geode { namespace client { class APACHE_GEODE_EXPORT StructSetImpl : public StructSet, public std::enable_shared_from_this<StructSetImpl> { public: StructSetImpl(const std::shared_ptr<CacheableVector>& values, const std::vector<std::string>& fieldNames); bool isModifiable() const override; size_t size() const override; const std::shared_ptr<Serializable> operator[](size_t index) const override; size_t getFieldIndex(const std::string& fieldname) override; const std::string& getFieldName(int32_t index) override; SelectResultsIterator getIterator() override; /** Get an iterator pointing to the start of vector. */ virtual SelectResults::Iterator begin() const override; /** Get an iterator pointing to the end of vector. */ virtual SelectResults::Iterator end() const override; ~StructSetImpl() noexcept override {} private: std::shared_ptr<CacheableVector> m_structVector; std::map<std::string, int32_t> m_fieldNameIndexMap; size_t m_nextIndex; }; } // namespace client } // namespace geode } // namespace apache #endif // GEODE_STRUCTSETIMPL_H_
28.111111
78
0.748353
mcmellawatt
c1e6dd448aa4d38f5b3151c626d05271bb339353
730
cc
C++
src/FillTheSkips.cc
DrScKAWAMOTO/cmdrecplay
f1191b455cb63460f1fd34e947fdb1474489b94c
[ "Apache-2.0" ]
null
null
null
src/FillTheSkips.cc
DrScKAWAMOTO/cmdrecplay
f1191b455cb63460f1fd34e947fdb1474489b94c
[ "Apache-2.0" ]
null
null
null
src/FillTheSkips.cc
DrScKAWAMOTO/cmdrecplay
f1191b455cb63460f1fd34e947fdb1474489b94c
[ "Apache-2.0" ]
null
null
null
/* * Project: ifendif * Version: 1.0 * Copyright: (C) 2017 Dr.Sc.KAWAMOTO,Takuji (Ext) * Create: 2017/03/03 05:38:45 JST */ #include <string.h> #include "FillTheSkips.h" FillTheSkips::FillTheSkips(LineBuffer* parent) : p_parent(parent) { p_parent->read_line(); } FillTheSkips::~FillTheSkips() { } bool FillTheSkips::read_line() { ++p_line_no; if (p_parent->is_eof()) { strcpy(p_line_buffer, "\n"); return false; } if (p_parent->line_number() > p_line_no) { strcpy(p_line_buffer, "\n"); return false; } strcpy(p_line_buffer, p_parent->line()); p_parent->read_line(); return false; } /* Local Variables: */ /* mode: c++ */ /* End: */
16.976744
50
0.593151
DrScKAWAMOTO
c1e811cc5876921134c52168170b4d40ce9876d5
303
hpp
C++
pythran/pythonic/__builtin__/RuntimeWarning.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
1
2018-03-24T00:33:03.000Z
2018-03-24T00:33:03.000Z
pythran/pythonic/__builtin__/RuntimeWarning.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/__builtin__/RuntimeWarning.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_BUILTIN_RUNTIMEWARNING_HPP #define PYTHONIC_BUILTIN_RUNTIMEWARNING_HPP #include "pythonic/include/__builtin__/RuntimeWarning.hpp" #include "pythonic/types/exceptions.hpp" PYTHONIC_NS_BEGIN namespace __builtin__ { PYTHONIC_EXCEPTION_IMPL(RuntimeWarning) } PYTHONIC_NS_END #endif
16.833333
58
0.854785
SylvainCorlay
c1ea4f480b12eda6b000d01d3c2b8a3f6e09de4c
53,483
cpp
C++
meta/source/app/App.cpp
congweitao/congfs
54cedf484f8a2cacab567fe182cc1f6413c25cf2
[ "BSD-3-Clause" ]
null
null
null
meta/source/app/App.cpp
congweitao/congfs
54cedf484f8a2cacab567fe182cc1f6413c25cf2
[ "BSD-3-Clause" ]
null
null
null
meta/source/app/App.cpp
congweitao/congfs
54cedf484f8a2cacab567fe182cc1f6413c25cf2
[ "BSD-3-Clause" ]
null
null
null
#include <common/app/log/LogContext.h> #include <common/components/worker/queue/UserWorkContainer.h> #include <common/components/worker/DummyWork.h> #include <common/components/ComponentInitException.h> #include <common/components/RegistrationDatagramListener.h> #include <common/net/message/nodes/RegisterNodeMsg.h> #include <common/net/message/nodes/RegisterNodeRespMsg.h> #include <common/net/sock/RDMASocket.h> #include <common/nodes/LocalNode.h> #include <common/storage/striping/Raid0Pattern.h> #include <common/toolkit/NodesTk.h> #include <components/FileEventLogger.h> #include <components/ModificationEventFlusher.h> #include <components/DisposalGarbageCollector.h> #include <program/Program.h> #include <session/SessionStore.h> #include <storage/MetadataEx.h> #include <toolkit/BuddyCommTk.h> #include <toolkit/StorageTkEx.h> #include <boost/format.hpp> #include "App.h" #include <array> #include <mntent.h> #include <csignal> #include <fstream> #include <sstream> #include <syslog.h> #include <sys/resource.h> #include <sys/statfs.h> #include <blkid/blkid.h> #include <uuid/uuid.h> // this magic number is not available on all supported platforms. specifically, rhel5 does not have // linux/magic.h (which is where this constant is found). #ifndef EXT3_SUPER_MAGIC #define EXT3_SUPER_MAGIC 0xEF53 #endif #define APP_WORKERS_DIRECT_NUM 1 #define APP_SYSLOG_IDENTIFIER "congfs-meta" App::App(int argc, char** argv) { this->argc = argc; this->argv = argv; this->appResult = APPCODE_NO_ERROR; this->cfg = NULL; this->netFilter = NULL; this->tcpOnlyFilter = NULL; this->log = NULL; this->mgmtNodes = NULL; this->metaNodes = NULL; this->storageNodes = NULL; this->clientNodes = NULL; this->metaCapacityPools = NULL; this->targetMapper = NULL; this->storageBuddyGroupMapper = NULL; this->metaBuddyGroupMapper = NULL; this->targetStateStore = NULL; this->metaStateStore = NULL; this->metaBuddyCapacityPools = NULL; this->workQueue = NULL; this->commSlaveQueue = NULL; this->disposalDir = NULL; this->buddyMirrorDisposalDir = NULL; this->rootDir = NULL; this->metaStore = NULL; this->ackStore = NULL; this->sessions = NULL; this->mirroredSessions = NULL; this->nodeOperationStats = NULL; this->netMessageFactory = NULL; this->inodesPath = NULL; this->dentriesPath = NULL; this->buddyMirrorInodesPath = NULL; this->buddyMirrorDentriesPath = NULL; this->dgramListener = NULL; this->connAcceptor = NULL; this->statsCollector = NULL; this->internodeSyncer = NULL; this->modificationEventFlusher = NULL; this->timerQueue = new TimerQueue(1, 1); this->gcQueue = new TimerQueue(1, 1); this->buddyResyncer = NULL; this->nextNumaBindTarget = 0; } App::~App() { // Note: Logging of the common lib classes is not working here, because this is called // from class Program (so the thread-specific app-pointer isn't set in this context). commSlavesDelete(); workersDelete(); SAFE_DELETE(this->buddyResyncer); SAFE_DELETE(this->timerQueue); SAFE_DELETE(this->modificationEventFlusher); SAFE_DELETE(this->internodeSyncer); SAFE_DELETE(this->statsCollector); SAFE_DELETE(this->connAcceptor); streamListenersDelete(); SAFE_DELETE(this->dgramListener); SAFE_DELETE(this->dentriesPath); SAFE_DELETE(this->inodesPath); SAFE_DELETE(this->buddyMirrorDentriesPath); SAFE_DELETE(this->buddyMirrorInodesPath); SAFE_DELETE(this->netMessageFactory); SAFE_DELETE(this->nodeOperationStats); SAFE_DELETE(this->sessions); SAFE_DELETE(this->mirroredSessions); SAFE_DELETE(this->ackStore); if(this->disposalDir && this->metaStore) this->metaStore->releaseDir(this->disposalDir->getID() ); if(this->buddyMirrorDisposalDir && this->metaStore) this->metaStore->releaseDir(this->buddyMirrorDisposalDir->getID() ); if(this->rootDir && this->metaStore) this->metaStore->releaseDir(this->rootDir->getID() ); SAFE_DELETE(this->metaStore); SAFE_DELETE(this->commSlaveQueue); SAFE_DELETE(this->workQueue); SAFE_DELETE(this->clientNodes); SAFE_DELETE(this->storageNodes); SAFE_DELETE(this->metaNodes); SAFE_DELETE(this->mgmtNodes); this->localNode.reset(); SAFE_DELETE(this->metaBuddyCapacityPools); SAFE_DELETE(this->storageBuddyGroupMapper); SAFE_DELETE(this->metaBuddyGroupMapper); SAFE_DELETE(this->targetMapper); SAFE_DELETE(this->metaStateStore); SAFE_DELETE(this->targetStateStore); SAFE_DELETE(this->metaCapacityPools); SAFE_DELETE(this->log); SAFE_DELETE(this->tcpOnlyFilter); SAFE_DELETE(this->netFilter); SAFE_DELETE(this->cfg); delete timerQueue; Logger::destroyLogger(); closelog(); } /** * Initialize config and run app either in normal mode or in special unit tests mode. */ void App::run() { try { openlog(APP_SYSLOG_IDENTIFIER, LOG_NDELAY | LOG_PID | LOG_CONS, LOG_DAEMON); this->cfg = new Config(argc, argv); runNormal(); } catch (InvalidConfigException& e) { std::cerr << std::endl; std::cerr << "Error: " << e.what() << std::endl; std::cerr << std::endl; std::cerr << "[ConGFS Metadata Node Version: " << CONGFS_VERSION << std::endl; std::cerr << "Refer to the default config file (/etc/congfs/congfs-meta.conf)" << std::endl; std::cerr << "or visit http://www.congfs.com to find out about configuration options.]" << std::endl; std::cerr << std::endl; if(this->log) log->logErr(e.what() ); appResult = APPCODE_INVALID_CONFIG; return; } catch (std::exception& e) { std::cerr << std::endl; std::cerr << "Unrecoverable error: " << e.what() << std::endl; std::cerr << std::endl; if(this->log) log->logErr(e.what() ); appResult = APPCODE_RUNTIME_ERROR; return; } } /** * @throw InvalidConfigException on error */ void App::runNormal() { // numa binding (as early as possible) if(cfg->getTuneBindToNumaZone() != -1) // -1 means disable binding { bool bindRes = System::bindToNumaNode(cfg->getTuneBindToNumaZone() ); if(!bindRes) throw InvalidConfigException("Unable to bind to this NUMA zone: " + StringTk::intToStr(cfg->getTuneBindToNumaZone() ) ); } // init basic data objects & storage NumNodeID localNodeNumID; std::string localNodeID; // locks working dir => call before anything else that accesses the disk const bool targetNew = preinitStorage(); initLogging(); checkTargetUUID(); initLocalNodeIDs(localNodeID, localNodeNumID); initDataObjects(); initBasicNetwork(); initStorage(); initXAttrLimit(); initRootDir(localNodeNumID); initDisposalDir(); registerSignalHandler(); // prepare ibverbs for forking RDMASocket::rdmaForkInitOnce(); // ACLs need enabled client side XAttrs in order to work. if (cfg->getStoreClientACLs() && !cfg->getStoreClientXAttrs() ) throw InvalidConfigException( "Client ACLs are enabled in config file, but extended attributes are not. " "ACLs cannot be stored without extended attributes."); // detach process if(cfg->getRunDaemonized() ) daemonize(); // find RDMA interfaces (based on TCP/IP interfaces) // note: we do this here, because when we first create an RDMASocket (and this is done in this // check), the process opens the verbs device. Recent OFED versions have a check if the // credentials of the opening process match those of the calling process (not only the values // are compared, but the pointer is checked for equality). Thus, the first open needs to happen // after the fork, because we need to access the device in the child process. if(cfg->getConnUseRDMA() && RDMASocket::rdmaDevicesExist() ) { bool foundRdmaInterfaces = NetworkInterfaceCard::checkAndAddRdmaCapability(localNicList); if (foundRdmaInterfaces) localNicList.sort(NetworkInterfaceCard::NicAddrComp{&allowedInterfaces}); // re-sort the niclist } // Find MgmtNode bool mgmtWaitRes = waitForMgmtNode(); if(!mgmtWaitRes) { // typically user just pressed ctrl+c in this case log->logErr("Waiting for congfs-mgmtd canceled"); appResult = APPCODE_RUNTIME_ERROR; return; } // retrieve localNodeNumID from management node (if we don't have it yet) if(!localNodeNumID) { // no local num ID yet => try to retrieve one from mgmt bool preregisterRes = preregisterNode(localNodeID, localNodeNumID); if(!preregisterRes) throw InvalidConfigException("Pre-registration at management node canceled"); } if (!localNodeNumID) // just a sanity check that should never fail throw InvalidConfigException("Failed to retrieve numeric local node ID from mgmt"); // we have all local node data now => init localNode initLocalNode(localNodeID, localNodeNumID); initLocalNodeNumIDFile(localNodeNumID); // Keeps the local node state from the static call to the InternodeSyncer method so we can pass // it when we construct the actual object. TargetConsistencyState initialConsistencyState; bool downloadRes = downloadMgmtInfo(initialConsistencyState); if (!downloadRes) { log->log(1, "Downloading target states from management node failed. Shutting down..."); appResult = APPCODE_INITIALIZATION_ERROR; return; } // Check for the sessions file. If there is none, it's either the first run, or we crashed so we // need a resync. bool sessionFilePresent = StorageTk::checkSessionFileExists(metaPathStr); if (!targetNew && !sessionFilePresent) initialConsistencyState = TargetConsistencyState_NEEDS_RESYNC; // init components BuddyCommTk::prepareBuddyNeedsResyncState(*mgmtNodes->referenceFirstNode(), *metaBuddyGroupMapper, *timerQueue, localNode->getNumID()); try { initComponents(initialConsistencyState); } catch(ComponentInitException& e) { log->logErr(e.what() ); log->log(Log_CRITICAL, "A hard error occurred. Shutting down..."); appResult = APPCODE_INITIALIZATION_ERROR; return; } // restore sessions from last clean shut down restoreSessions(); // log system and configuration info logInfos(); // start component threads and join them startComponents(); // session restore is finished so delete old session files // clean shutdown will generate a new session file deleteSessionFiles(); // wait for termination joinComponents(); // clean shutdown (at least no cache loss) => generate a new session file if(sessions) storeSessions(); // close all client sessions InternodeSyncer::syncClients({}, false); log->log(Log_CRITICAL, "All components stopped. Exiting now!"); } void App::initLogging() { // check absolute log path to avoid chdir() problems Path logStdPath(cfg->getLogStdFile() ); if(!logStdPath.empty() && !logStdPath.absolute()) { throw InvalidConfigException("Path to log file must be absolute"); } Logger::createLogger(cfg->getLogLevel(), cfg->getLogType(), cfg->getLogNoDate(), cfg->getLogStdFile(), cfg->getLogNumLines(), cfg->getLogNumRotatedFiles()); this->log = new LogContext("App"); if (!cfg->getFileEventLogTarget().empty()) fileEventLogger.reset(new FileEventLogger(cfg->getFileEventLogTarget())); } /** * Init basic shared objects like work queues, node stores etc. */ void App::initDataObjects() { this->mgmtNodes = new NodeStoreServers(NODETYPE_Mgmt, true); this->metaNodes = new NodeStoreServers(NODETYPE_Meta, true); this->storageNodes = new NodeStoreServers(NODETYPE_Storage, false); this->clientNodes = new NodeStoreClients(); NicAddressList nicList; this->targetMapper = new TargetMapper(); this->storageNodes->attachTargetMapper(targetMapper); this->storageBuddyGroupMapper = new MirrorBuddyGroupMapper(targetMapper); this->metaBuddyGroupMapper = new MirrorBuddyGroupMapper(); this->metaCapacityPools = new NodeCapacityPools( false, DynamicPoolLimits(0, 0, 0, 0, 0, 0), DynamicPoolLimits(0, 0, 0, 0, 0, 0) ); this->metaNodes->attachCapacityPools(metaCapacityPools); this->metaBuddyCapacityPools = new NodeCapacityPools( false, DynamicPoolLimits(0, 0, 0, 0, 0, 0), DynamicPoolLimits(0, 0, 0, 0, 0, 0) ); this->metaBuddyGroupMapper->attachMetaCapacityPools(metaBuddyCapacityPools); this->targetStateStore = new TargetStateStore(NODETYPE_Storage); this->targetMapper->attachStateStore(targetStateStore); this->metaStateStore = new TargetStateStore(NODETYPE_Meta); this->metaNodes->attachStateStore(metaStateStore); this->storagePoolStore = boost::make_unique<StoragePoolStore>(storageBuddyGroupMapper, targetMapper); // add newly mapped targets and buddy groups to storage pool store this->targetMapper->attachStoragePoolStore(storagePoolStore.get()); this->storageBuddyGroupMapper->attachStoragePoolStore(storagePoolStore.get()); this->targetMapper->attachExceededQuotaStores(&exceededQuotaStores); this->workQueue = new MultiWorkQueue(); this->commSlaveQueue = new MultiWorkQueue(); if(cfg->getTuneUsePerUserMsgQueues() ) workQueue->setIndirectWorkList(new UserWorkContainer() ); this->ackStore = new AcknowledgmentStore(); this->sessions = new SessionStore(); this->mirroredSessions = new SessionStore(); this->nodeOperationStats = new MetaNodeOpStats(); this->isRootBuddyMirrored = false; } /** * Init basic networking data structures. * * Note: no RDMA is detected here, because this needs to be done later */ void App::initBasicNetwork() { // check if management host is defined if(!cfg->getSysMgmtdHost().length() ) throw InvalidConfigException("Management host undefined"); // prepare filter for outgoing packets/connections this->netFilter = new NetFilter(cfg->getConnNetFilterFile() ); this->tcpOnlyFilter = new NetFilter(cfg->getConnTcpOnlyFilterFile() ); // prepare filter for interfaces std::string interfacesList = cfg->getConnInterfacesList(); if(!interfacesList.empty() ) { log->log(Log_DEBUG, "Allowed interfaces: " + interfacesList); StringTk::explodeEx(interfacesList, ',', true, &allowedInterfaces); } // discover local NICs and filter them NetworkInterfaceCard::findAllInterfaces(allowedInterfaces, localNicList); if(localNicList.empty() ) throw InvalidConfigException("Couldn't find any usable NIC"); localNicList.sort(NetworkInterfaceCard::NicAddrComp{&allowedInterfaces}); // prepare factory for incoming messages this->netMessageFactory = new NetMessageFactory(); } /** * Load node IDs from disk or generate string ID. */ void App::initLocalNodeIDs(std::string& outLocalID, NumNodeID& outLocalNumID) { // load (or generate) nodeID and compare to original nodeID Path metaPath(metaPathStr); Path nodeIDPath = metaPath / STORAGETK_NODEID_FILENAME; StringList nodeIDList; // actually contains only a single line bool idPathExists = StorageTk::pathExists(nodeIDPath.str()); if(idPathExists) ICommonConfig::loadStringListFile(nodeIDPath.str().c_str(), nodeIDList); if(!nodeIDList.empty() ) outLocalID = *nodeIDList.begin(); // auto-generate nodeID if it wasn't loaded if(outLocalID.empty() ) outLocalID = System::getHostname(); // check for nodeID changes StorageTk::checkOrCreateOrigNodeIDFile(metaPathStr, outLocalID); // load nodeNumID file StorageTk::readNumIDFile(metaPath.str(), STORAGETK_NODENUMID_FILENAME, &outLocalNumID); // note: localNodeNumID is still 0 here if it wasn't loaded from the file } /** * create and attach the localNode object, store numID in storage dir */ void App::initLocalNode(std::string& localNodeID, NumNodeID localNodeNumID) { unsigned portUDP = cfg->getConnMetaPortUDP(); unsigned portTCP = cfg->getConnMetaPortTCP(); // create localNode object localNode = std::make_shared<LocalNode>(NODETYPE_Meta, localNodeID, localNodeNumID, portUDP, portTCP, localNicList); // attach to metaNodes store metaNodes->setLocalNode(this->localNode); } /** * Store numID file in storage directory */ void App::initLocalNodeNumIDFile(NumNodeID localNodeNumID) { StorageTk::createNumIDFile(metaPathStr, STORAGETK_NODENUMID_FILENAME, localNodeNumID.val()); } /** * this contains things that would actually live inside initStorage() but need to be * done at an earlier stage (like working dir locking before log file creation). * * note: keep in mind that we don't have the logger here yet, because logging can only be * initialized after the working dir has conn locked within this method. * * @returns true if there was no storageFormatFile before (target was uninitialized) */ bool App::preinitStorage() { Path metaPath(cfg->getStoreMetaDirectory() ); this->metaPathStr = metaPath.str(); // normalize if(metaPath.empty() ) throw InvalidConfigException("No metadata storage directory specified"); if(!metaPath.absolute() ) /* (check to avoid problems after chdir later) */ throw InvalidConfigException("Path to storage directory must be absolute: " + metaPathStr); const bool formatFileExists = StorageTk::checkStorageFormatFileExists(metaPathStr); if(!cfg->getStoreAllowFirstRunInit() && !formatFileExists) throw InvalidConfigException("Storage directory not initialized and " "initialization has conn disabled: " + metaPathStr); this->pidFileLockFD = createAndLockPIDFile(cfg->getPIDFile() ); // ignored if pidFile not defined if(!StorageTk::createPathOnDisk(metaPath, false) ) throw InvalidConfigException("Unable to create metadata directory: " + metaPathStr + " (" + System::getErrString(errno) + ")" ); this->workingDirLockFD = StorageTk::lockWorkingDirectory(cfg->getStoreMetaDirectory() ); if (!workingDirLockFD.valid()) throw InvalidConfigException("Unable to lock working directory: " + metaPathStr); return !formatFileExists; } void App::initStorage() { // change working dir to meta directory int changeDirRes = chdir(metaPathStr.c_str() ); if(changeDirRes) { // unable to change working directory throw InvalidConfigException("Unable to change working directory to: " + metaPathStr + " " "(SysErr: " + System::getErrString() + ")"); } // storage format file if(!StorageTkEx::createStorageFormatFile(metaPathStr) ) throw InvalidConfigException("Unable to create storage format file in: " + cfg->getStoreMetaDirectory() ); StorageTkEx::checkStorageFormatFile(metaPathStr); // dentries directory dentriesPath = new Path(META_DENTRIES_SUBDIR_NAME); StorageTk::initHashPaths(*dentriesPath, META_DENTRIES_LEVEL1_SUBDIR_NUM, META_DENTRIES_LEVEL2_SUBDIR_NUM); // buddy mirrored dentries directory buddyMirrorDentriesPath = new Path(META_BUDDYMIRROR_SUBDIR_NAME "/" META_DENTRIES_SUBDIR_NAME); StorageTk::initHashPaths(*buddyMirrorDentriesPath, META_DENTRIES_LEVEL1_SUBDIR_NUM, META_DENTRIES_LEVEL2_SUBDIR_NUM); // inodes directory inodesPath = new Path(META_INODES_SUBDIR_NAME); if(!StorageTk::createPathOnDisk(*this->inodesPath, false) ) throw InvalidConfigException("Unable to create directory: " + inodesPath->str() ); StorageTk::initHashPaths(*inodesPath, META_INODES_LEVEL1_SUBDIR_NUM, META_INODES_LEVEL2_SUBDIR_NUM); // buddy mirrored inodes directory buddyMirrorInodesPath = new Path(META_BUDDYMIRROR_SUBDIR_NAME "/" META_INODES_SUBDIR_NAME); if(!StorageTk::createPathOnDisk(*this->buddyMirrorInodesPath, false) ) throw InvalidConfigException( "Unable to create directory: " + buddyMirrorInodesPath->str()); StorageTk::initHashPaths(*buddyMirrorInodesPath, META_INODES_LEVEL1_SUBDIR_NUM, META_INODES_LEVEL2_SUBDIR_NUM); // raise file descriptor limit if(cfg->getTuneProcessFDLimit() ) { uint64_t oldLimit; bool setFDLimitRes = System::incProcessFDLimit(cfg->getTuneProcessFDLimit(), &oldLimit); if(!setFDLimitRes) log->log(Log_CRITICAL, std::string("Unable to increase process resource limit for " "number of file handles. Proceeding with default limit: ") + StringTk::uintToStr(oldLimit) + " " + "(SysErr: " + System::getErrString() + ")"); } } void App::initXAttrLimit() { // check whether the filesystem supports overly many amounts of xattrs (>64kb list size). // of the filesystems we support, this is currently only xfs. // also check for filesystems mounted beneath the metadata root dir, if any are found, limit the // xattrs too (it's probably not worth it to check the fs types here, since the setup should be // rare.) if (!cfg->getStoreUseExtendedAttribs()) return; cfg->setLimitXAttrListLength(true); struct statfs metaRootStat; if (::statfs(cfg->getStoreMetaDirectory().c_str(), &metaRootStat)) { LOG(GENERAL, CRITICAL, "Could not statfs() meta root directory.", sysErr); throw InvalidConfigException("Could not statfs() meta root directory."); } // ext3 and ext4 have the same magic, and are currently the only "safe" filesystems officially // supported. if (metaRootStat.f_type == EXT3_SUPER_MAGIC) cfg->setLimitXAttrListLength(false); else { LOG(GENERAL, NOTICE, "Limiting number of xattrs per inode."); return; } // the metadata root directory does not support overly long xattrs. check for filesystems mounted // beneath the metadata root, and enable xattrs limiting if any are found. std::string metaRootPath(PATH_MAX, '\0'); if (!realpath(cfg->getStoreMetaDirectory().c_str(), &metaRootPath[0])) { LOG(GENERAL, CRITICAL, "Could not check meta root dir for xattr compatibility.", sysErr); throw InvalidConfigException("Could not check meta root dir for xattr compatibility."); } metaRootPath.resize(strlen(metaRootPath.c_str())); metaRootPath += '/'; FILE* mounts = setmntent("/etc/mtab", "r"); if (!mounts) { LOG(GENERAL, CRITICAL, "Could not open mtab.", sysErr); throw InvalidConfigException("Could not open mtab."); } struct mntent mountBuf; char buf[PATH_MAX * 4]; struct mntent* mount; errno = 0; while ((mount = getmntent_r(mounts, &mountBuf, buf, sizeof(buf)))) { if (strstr(mount->mnt_dir, metaRootPath.c_str()) == mount->mnt_dir) { cfg->setLimitXAttrListLength(true); break; } } endmntent(mounts); if (errno) { LOG(GENERAL, ERR, "Could not read mtab.", sysErr); throw InvalidConfigException("Could not read mtab."); } if (cfg->getLimitXAttrListLength()) LOG(GENERAL, NOTICE, "Limiting number of xattrs per inode."); } void App::initRootDir(NumNodeID localNodeNumID) { // try to load root dir from disk (through metaStore) or create a new one this->metaStore = new MetaStore(); // try to reference root directory with buddy mirroring rootDir = this->metaStore->referenceDir(META_ROOTDIR_ID_STR, true, true); // if that didn't work try to reference non-buddy-mirrored root dir if (!rootDir) { rootDir = this->metaStore->referenceDir(META_ROOTDIR_ID_STR, false, true); } if(rootDir) { // loading succeeded (either with or without mirroring => init rootNodeID this->log->log(Log_NOTICE, "Root directory loaded."); NumNodeID rootDirOwner = rootDir->getOwnerNodeID(); bool rootIsBuddyMirrored = rootDir->getIsBuddyMirrored(); // try to set rootDirOwner as root node if (rootDirOwner && metaRoot.setIfDefault(rootDirOwner, rootIsBuddyMirrored)) { // new root node accepted (check if rootNode is localNode) NumNodeID primaryRootDirOwner; if (rootIsBuddyMirrored) primaryRootDirOwner = NumNodeID( metaBuddyGroupMapper->getPrimaryTargetID(rootDirOwner.val() ) ); else primaryRootDirOwner = rootDirOwner; if(localNodeNumID == primaryRootDirOwner) { log->log(Log_CRITICAL, "I got root (by possession of root directory)"); if (rootIsBuddyMirrored) log->log(Log_CRITICAL, "Root directory is mirrored"); } else log->log(Log_CRITICAL, "Root metadata server (by possession of root directory): " + rootDirOwner.str()); } } else { // failed to load root directory => create a new rootDir (not mirrored) this->log->log(Log_CRITICAL, "This appears to be a new storage directory. Creating a new root dir."); UInt16Vector stripeTargets; unsigned defaultChunkSize = this->cfg->getTuneDefaultChunkSize(); unsigned defaultNumStripeTargets = this->cfg->getTuneDefaultNumStripeTargets(); Raid0Pattern stripePattern(defaultChunkSize, stripeTargets, defaultNumStripeTargets); DirInode newRootDir(META_ROOTDIR_ID_STR, S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO, 0, 0, NumNodeID(), stripePattern, false); this->metaStore->makeDirInode(newRootDir); this->rootDir = this->metaStore->referenceDir(META_ROOTDIR_ID_STR, false, true); if(!this->rootDir) { // error this->log->logErr("Failed to store root directory. Unable to proceed."); throw InvalidConfigException("Failed to store root directory"); } } } void App::initDisposalDir() { // try to load disposal dir from disk (through metaStore) or create a new one this->disposalDir = this->metaStore->referenceDir(META_DISPOSALDIR_ID_STR, false, true); if(this->disposalDir) { // loading succeeded this->log->log(Log_DEBUG, "Disposal directory loaded."); } else { // failed to load disposal directory => create a new one this->log->log(Log_DEBUG, "Creating a new disposal directory."); UInt16Vector stripeTargets; unsigned defaultChunkSize = this->cfg->getTuneDefaultChunkSize(); unsigned defaultNumStripeTargets = this->cfg->getTuneDefaultNumStripeTargets(); Raid0Pattern stripePattern(defaultChunkSize, stripeTargets, defaultNumStripeTargets); DirInode newDisposalDir(META_DISPOSALDIR_ID_STR, S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO, 0, 0, NumNodeID(), stripePattern, false); this->metaStore->makeDirInode(newDisposalDir); this->disposalDir = this->metaStore->referenceDir(META_DISPOSALDIR_ID_STR, false, true); if(!this->disposalDir) { // error this->log->logErr("Failed to store disposal directory. Unable to proceed."); throw InvalidConfigException("Failed to store disposal directory"); } } buddyMirrorDisposalDir = metaStore->referenceDir(META_MIRRORDISPOSALDIR_ID_STR, true, true); if(buddyMirrorDisposalDir) { // loading succeeded log->log(Log_DEBUG, "Mirrored disposal directory loaded."); } else { // failed to load disposal directory => create a new one log->log(Log_DEBUG, "Creating a new mirrored disposal directory."); UInt16Vector stripeTargets; unsigned defaultChunkSize = cfg->getTuneDefaultChunkSize(); unsigned defaultNumStripeTargets = cfg->getTuneDefaultNumStripeTargets(); Raid0Pattern stripePattern(defaultChunkSize, stripeTargets, defaultNumStripeTargets); DirInode newDisposalDir(META_MIRRORDISPOSALDIR_ID_STR, S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO, 0, 0, NumNodeID(), stripePattern, true); metaStore->makeDirInode(newDisposalDir); buddyMirrorDisposalDir = metaStore->referenceDir(META_MIRRORDISPOSALDIR_ID_STR, true, true); if(!buddyMirrorDisposalDir) { // error log->logErr("Failed to store mirrored disposal directory. Unable to proceed."); throw InvalidConfigException("Failed to store mirrored disposal directory"); } } } void App::initComponents(TargetConsistencyState initialConsistencyState) { this->log->log(Log_DEBUG, "Initializing components..."); this->dgramListener = new DatagramListener( netFilter, localNicList, ackStore, cfg->getConnMetaPortUDP() ); if(cfg->getTuneListenerPrioShift() ) dgramListener->setPriorityShift(cfg->getTuneListenerPrioShift() ); streamListenersInit(); unsigned short listenPort = cfg->getConnMetaPortTCP(); this->connAcceptor = new ConnAcceptor(this, localNicList, listenPort); this->statsCollector = new StatsCollector(workQueue, STATSCOLLECTOR_COLLECT_INTERVAL_MS, STATSCOLLECTOR_HISTORY_LENGTH); this->buddyResyncer = new BuddyResyncer(); this->internodeSyncer = new InternodeSyncer(initialConsistencyState); this->modificationEventFlusher = new ModificationEventFlusher(); workersInit(); commSlavesInit(); this->log->log(Log_DEBUG, "Components initialized."); } void App::startComponents() { log->log(Log_DEBUG, "Starting up components..."); // make sure child threads don't receive SIGINT/SIGTERM (blocked signals are inherited) PThread::blockInterruptSignals(); timerQueue->start(); gcQueue->start(); this->dgramListener->start(); // wait for nodes list download before we start handling client requests PThread::unblockInterruptSignals(); // temporarily unblock interrupt, so user can cancel waiting PThread::blockInterruptSignals(); // reblock signals for next child threads streamListenersStart(); this->connAcceptor->start(); this->statsCollector->start(); this->internodeSyncer->start(); timerQueue->enqueue(std::chrono::minutes(5), [] { InternodeSyncer::downloadAndSyncClients(true); }); this->modificationEventFlusher->start(); if(const auto wait = getConfig()->getTuneDisposalGCPeriod()) { this->gcQueue->enqueue(std::chrono::seconds(wait), disposalGarbageCollector); } workersStart(); commSlavesStart(); PThread::unblockInterruptSignals(); // main app thread may receive SIGINT/SIGTERM log->log(Log_DEBUG, "Components running."); } void App::stopComponents() { SAFE_DELETE(this->gcQueue); // note: this method may not wait for termination of the components, because that could // lead to a deadlock (when calling from signal handler) // note: no commslave stop here, because that would keep workers from terminating if(modificationEventFlusher) // The modificationEventFlusher has to be stopped before the // workers, because it tries to notify all the workers about the // changed modification state. modificationEventFlusher->selfTerminate(); // resyncer wants to control the workers, so any running resync must be finished or aborted // before the workers are stopped. if(buddyResyncer) buddyResyncer->shutdown(); workersStop(); if(internodeSyncer) internodeSyncer->selfTerminate(); if(statsCollector) statsCollector->selfTerminate(); if(connAcceptor) connAcceptor->selfTerminate(); streamListenersStop(); if(dgramListener) { dgramListener->selfTerminate(); dgramListener->sendDummyToSelfUDP(); // for faster termination } this->selfTerminate(); /* this flag can be noticed by thread-independent methods and is also required e.g. to let App::waitForMgmtNode() know that it should cancel */ } /** * Handles expections that lead to the termination of a component. * Initiates an application shutdown. */ void App::handleComponentException(std::exception& e) { const char* logContext = "App (component exception handler)"; LogContext log(logContext); const auto componentName = PThread::getCurrentThreadName(); log.logErr( "The component [" + componentName + "] encountered an unrecoverable error. " + std::string("[SysErr: ") + System::getErrString() + "] " + std::string("Exception message: ") + e.what() ); log.log(Log_WARNING, "Shutting down..."); stopComponents(); } void App::joinComponents() { log->log(Log_DEBUG, "Joining component threads..."); /* (note: we need one thread for which we do an untimed join, so this should be a quite reliably terminating thread) */ statsCollector->join(); workersJoin(); waitForComponentTermination(modificationEventFlusher); waitForComponentTermination(dgramListener); waitForComponentTermination(connAcceptor); streamListenersJoin(); waitForComponentTermination(internodeSyncer); commSlavesStop(); // placed here because otherwise it would keep workers from terminating commSlavesJoin(); } void App::streamListenersInit() { this->numStreamListeners = cfg->getTuneNumStreamListeners(); for(unsigned i=0; i < numStreamListeners; i++) { StreamListenerV2* listener = new StreamListenerV2( std::string("StreamLis") + StringTk::uintToStr(i+1), this, workQueue); if(cfg->getTuneListenerPrioShift() ) listener->setPriorityShift(cfg->getTuneListenerPrioShift() ); if(cfg->getTuneUseAggressiveStreamPoll() ) listener->setUseAggressivePoll(); streamLisVec.push_back(listener); } } void App::workersInit() { unsigned numWorkers = cfg->getTuneNumWorkers(); for(unsigned i=0; i < numWorkers; i++) { Worker* worker = new Worker( std::string("Worker") + StringTk::uintToStr(i+1), workQueue, QueueWorkType_INDIRECT); worker->setBufLens(cfg->getTuneWorkerBufSize(), cfg->getTuneWorkerBufSize() ); workerList.push_back(worker); } for(unsigned i=0; i < APP_WORKERS_DIRECT_NUM; i++) { Worker* worker = new Worker( std::string("DirectWorker") + StringTk::uintToStr(i+1), workQueue, QueueWorkType_DIRECT); worker->setBufLens(cfg->getTuneWorkerBufSize(), cfg->getTuneWorkerBufSize() ); workerList.push_back(worker); } } void App::commSlavesInit() { unsigned numCommSlaves = cfg->getTuneNumCommSlaves(); for(unsigned i=0; i < numCommSlaves; i++) { Worker* worker = new Worker( std::string("CommSlave") + StringTk::uintToStr(i+1), commSlaveQueue, QueueWorkType_DIRECT); worker->setBufLens(cfg->getTuneCommSlaveBufSize(), cfg->getTuneCommSlaveBufSize() ); commSlaveList.push_back(worker); } } void App::streamListenersStart() { unsigned numNumaNodes = System::getNumNumaNodes(); for(StreamLisVecIter iter = streamLisVec.begin(); iter != streamLisVec.end(); iter++) { if(cfg->getTuneListenerNumaAffinity() ) (*iter)->startOnNumaNode( (++nextNumaBindTarget) % numNumaNodes); else (*iter)->start(); } } void App::workersStart() { unsigned numNumaNodes = System::getNumNumaNodes(); for(WorkerListIter iter = workerList.begin(); iter != workerList.end(); iter++) { if(cfg->getTuneWorkerNumaAffinity() ) (*iter)->startOnNumaNode( (++nextNumaBindTarget) % numNumaNodes); else (*iter)->start(); } } void App::commSlavesStart() { unsigned numNumaNodes = System::getNumNumaNodes(); for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++) { if(cfg->getTuneWorkerNumaAffinity() ) (*iter)->startOnNumaNode( (++nextNumaBindTarget) % numNumaNodes); else (*iter)->start(); } } void App::streamListenersStop() { for(StreamLisVecIter iter = streamLisVec.begin(); iter != streamLisVec.end(); iter++) { (*iter)->selfTerminate(); } } void App::workersStop() { for(WorkerListIter iter = workerList.begin(); iter != workerList.end(); iter++) { (*iter)->selfTerminate(); // add dummy work to wake up the worker immediately for faster self termination PersonalWorkQueue* personalQ = (*iter)->getPersonalWorkQueue(); workQueue->addPersonalWork(new DummyWork(), personalQ); } } void App::commSlavesStop() { // need two loops because we don't know if the worker that handles the work will be the same that // received the self-terminate-request for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++) { (*iter)->selfTerminate(); } for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++) { commSlaveQueue->addDirectWork(new DummyWork() ); } } void App::streamListenersDelete() { for(StreamLisVecIter iter = streamLisVec.begin(); iter != streamLisVec.end(); iter++) { delete(*iter); } streamLisVec.clear(); } void App::workersDelete() { for(WorkerListIter iter = workerList.begin(); iter != workerList.end(); iter++) { delete(*iter); } workerList.clear(); } void App::commSlavesDelete() { for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++) { delete(*iter); } commSlaveList.clear(); } void App::streamListenersJoin() { for(StreamLisVecIter iter = streamLisVec.begin(); iter != streamLisVec.end(); iter++) { waitForComponentTermination(*iter); } } void App::workersJoin() { for(WorkerListIter iter = workerList.begin(); iter != workerList.end(); iter++) { waitForComponentTermination(*iter); } } void App::commSlavesJoin() { for(WorkerListIter iter = commSlaveList.begin(); iter != commSlaveList.end(); iter++) { waitForComponentTermination(*iter); } } void App::logInfos() { // print software version (CONGFS_VERSION) log->log(Log_CRITICAL, std::string("Version: ") + CONGFS_VERSION); // print debug version info LOG_DEBUG_CONTEXT(*log, Log_CRITICAL, "--DEBUG VERSION--"); // print local nodeIDs log->log(Log_WARNING, "LocalNode: " + localNode->getNodeIDWithTypeStr() ); // list usable network interfaces NicAddressList nicList(localNode->getNicList() ); std::string nicListStr; std::string extendedNicListStr; for (NicAddressListIter nicIter = nicList.begin(); nicIter != nicList.end(); nicIter++) { std::string nicTypeStr; if (nicIter->nicType == NICADDRTYPE_RDMA) nicTypeStr = "RDMA"; else if (nicIter->nicType == NICADDRTYPE_SDP) nicTypeStr = "SDP"; else if (nicIter->nicType == NICADDRTYPE_STANDARD) nicTypeStr = "TCP"; else nicTypeStr = "Unknown"; nicListStr += " " + std::string(nicIter->name) + "(" + nicTypeStr + ")"; extendedNicListStr += "\n+ " + NetworkInterfaceCard::nicAddrToString(&(*nicIter) ); } log->log(Log_WARNING, std::string("Usable NICs:") + nicListStr); log->log(Log_DEBUG, std::string("Extended list of usable NICs:") + extendedNicListStr); // print net filters if(netFilter->getNumFilterEntries() ) { log->log(Log_WARNING, std::string("Net filters: ") + StringTk::uintToStr(netFilter->getNumFilterEntries() ) ); } if(tcpOnlyFilter->getNumFilterEntries() ) { this->log->log(Log_WARNING, std::string("TCP-only filters: ") + StringTk::uintToStr(tcpOnlyFilter->getNumFilterEntries() ) ); } // print numa info // (getTuneBindToNumaZone==-1 means disable binding) if(cfg->getTuneListenerNumaAffinity() || cfg->getTuneWorkerNumaAffinity() || (cfg->getTuneBindToNumaZone() != -1) ) { unsigned numNumaNodes = System::getNumNumaNodes(); /* note: we use the term "numa areas" instead of "numa nodes" in log messages to avoid confusion with cluster "nodes" */ log->log(Log_NOTICE, std::string("NUMA areas: ") + StringTk::uintToStr(numNumaNodes) ); for(unsigned nodeNum=0; nodeNum < numNumaNodes; nodeNum++) { // print core list for each numa node cpu_set_t cpuSet; System::getNumaCoresByNode(nodeNum, &cpuSet); // create core list for current numa node std::string coreListStr; for(unsigned coreNum = 0; coreNum < CPU_SETSIZE; coreNum++) { if(CPU_ISSET(coreNum, &cpuSet) ) coreListStr += StringTk::uintToStr(coreNum) + " "; } log->log(Log_SPAM, "NUMA area " + StringTk::uintToStr(nodeNum) + " cores: " + coreListStr); } } } void App::daemonize() { int nochdir = 1; // 1 to keep working directory int noclose = 0; // 1 to keep stdin/-out/-err open log->log(Log_DEBUG, std::string("Detaching process...") ); int detachRes = daemon(nochdir, noclose); if(detachRes == -1) throw InvalidConfigException(std::string("Unable to detach process. SysErr: ") + System::getErrString() ); updateLockedPIDFile(pidFileLockFD); // ignored if pidFileFD is -1 } void App::registerSignalHandler() { signal(SIGINT, App::signalHandler); signal(SIGTERM, App::signalHandler); } void App::signalHandler(int sig) { App* app = Program::getApp(); Logger* log = Logger::getLogger(); const char* logContext = "App::signalHandler"; // note: this might deadlock if the signal was thrown while the logger mutex is locked by the // application thread (depending on whether the default mutex style is recursive). but // even recursive mutexes are not acceptable in this case. // we need something like a timed lock for the log mutex. if it succeeds within a // few seconds, we know that we didn't hold the mutex lock. otherwise we simply skip the // log message. this will only work if the mutex is non-recusive (which is unknown for // the default mutex style). // but it is very unlikely that the application thread holds the log mutex, because it // joins the component threads and so it doesn't do anything else but sleeping! switch(sig) { case SIGINT: { signal(sig, SIG_DFL); // reset the handler to its default log->log(Log_CRITICAL, logContext, "Received a SIGINT. Shutting down..."); } break; case SIGTERM: { signal(sig, SIG_DFL); // reset the handler to its default log->log(Log_CRITICAL, logContext, "Received a SIGTERM. Shutting down..."); } break; default: { signal(sig, SIG_DFL); // reset the handler to its default log->log(Log_CRITICAL, logContext, "Received an unknown signal. Shutting down..."); } break; } app->stopComponents(); } /** * Request mgmt heartbeat and wait for the mgmt node to appear in nodestore. * * @return true if mgmt heartbeat received, false on error or thread selftermination order */ bool App::waitForMgmtNode() { const unsigned waitTimeoutMS = 0; // infinite wait const unsigned nameResolutionRetries = 3; unsigned udpListenPort = cfg->getConnMetaPortUDP(); unsigned udpMgmtdPort = cfg->getConnMgmtdPortUDP(); std::string mgmtdHost = cfg->getSysMgmtdHost(); RegistrationDatagramListener regDGramLis(netFilter, localNicList, ackStore, udpListenPort); regDGramLis.start(); log->log(Log_CRITICAL, "Waiting for congfs-mgmtd@" + mgmtdHost + ":" + StringTk::uintToStr(udpMgmtdPort) + "..."); bool gotMgmtd = NodesTk::waitForMgmtHeartbeat( this, &regDGramLis, mgmtNodes, mgmtdHost, udpMgmtdPort, waitTimeoutMS, nameResolutionRetries); regDGramLis.selfTerminate(); regDGramLis.sendDummyToSelfUDP(); // for faster termination regDGramLis.join(); return gotMgmtd; } /** * Pre-register node to get a numeric ID from mgmt. * * @return true if pre-registration successful and localNodeNumID set. */ bool App::preregisterNode(std::string& localNodeID, NumNodeID& outLocalNodeNumID) { static bool registrationFailureLogged = false; // to avoid log spamming auto mgmtNode = mgmtNodes->referenceFirstNode(); if(!mgmtNode) { log->logErr("Unexpected: No management node found in store during node pre-registration."); return false; } NumNodeID rootNodeID = metaRoot.getID(); RegisterNodeMsg msg(localNodeID, outLocalNodeNumID, NODETYPE_Meta, &localNicList, cfg->getConnMetaPortUDP(), cfg->getConnMetaPortTCP() ); msg.setRootNumID(rootNodeID); Time startTime; Time lastRetryTime; unsigned nextRetryDelayMS = 0; // wait for mgmt node to appear and periodically resend request /* note: we usually expect not to loop here, because we already waited for mgmtd in waitForMgmtNode(), so mgmt should respond immediately. */ while(!outLocalNodeNumID && !getSelfTerminate() ) { if(lastRetryTime.elapsedMS() < nextRetryDelayMS) { // wait some time between retries waitForSelfTerminateOrder(nextRetryDelayMS); if(getSelfTerminate() ) break; } const auto respMsg = MessagingTk::requestResponse(*mgmtNode, msg, NETMSGTYPE_RegisterNodeResp); if (respMsg) { // communication successful RegisterNodeRespMsg* respMsgCast = (RegisterNodeRespMsg*)respMsg.get(); outLocalNodeNumID = respMsgCast->getNodeNumID(); if(!outLocalNodeNumID) { // mgmt rejected our registration log->logErr("ID reservation request was rejected by this mgmt node: " + mgmtNode->getTypedNodeID() ); } else log->log(Log_WARNING, "Node ID reservation successful."); break; } // comm failed => log status message if(!registrationFailureLogged) { log->log(Log_CRITICAL, "Node ID reservation failed. Management node offline? " "Will keep on trying..."); registrationFailureLogged = true; } // calculate next retry wait time lastRetryTime.setToNow(); nextRetryDelayMS = NodesTk::getRetryDelayMS(startTime.elapsedMS() ); } return bool(outLocalNodeNumID); } /** * Downloads the list of nodes, targets and buddy groups (for meta and storage servers) from the * mgmtd. * * @param outInitialConsistencyState The consistency state the local meta node has on the mgmtd * before any state reports are sent. */ bool App::downloadMgmtInfo(TargetConsistencyState& outInitialConsistencyState) { Config* cfg = this->getConfig(); int retrySleepTimeMS = 10000; // 10sec unsigned udpListenPort = cfg->getConnMetaPortUDP(); bool allSuccessful = false; // start temporary registration datagram listener RegistrationDatagramListener regDGramLis(netFilter, localNicList, ackStore, udpListenPort); regDGramLis.start(); // loop until we're registered and everything is downloaded (or until we got interrupted) do { // register ourselves // (note: node registration needs to be done before downloads to get notified of updates) if (!InternodeSyncer::registerNode(&regDGramLis) ) continue; // download all mgmt info the HBM cares for if (!InternodeSyncer::downloadAndSyncNodes() || !InternodeSyncer::downloadAndSyncTargetMappings() || !InternodeSyncer::downloadAndSyncStoragePools() || !InternodeSyncer::downloadAndSyncTargetStatesAndBuddyGroups() || !InternodeSyncer::updateMetaCapacityPools() || !InternodeSyncer::updateMetaBuddyCapacityPools()) continue; InternodeSyncer::downloadAndSyncClients(false); // ...and then the InternodeSyncer's part. if (!InternodeSyncer::updateMetaStatesAndBuddyGroups(outInitialConsistencyState, false) ) continue; if(!InternodeSyncer::downloadAllExceededQuotaLists(storagePoolStore->getPoolsAsVec())) continue; allSuccessful = true; break; } while(!waitForSelfTerminateOrder(retrySleepTimeMS) ); // stop temporary registration datagram listener regDGramLis.selfTerminate(); regDGramLis.sendDummyToSelfUDP(); // for faster termination regDGramLis.join(); if(allSuccessful) log->log(Log_NOTICE, "Registration and management info download complete."); return allSuccessful; } bool App::restoreSessions() { bool retVal = true; std::string path = this->metaPathStr + "/" + std::string(STORAGETK_SESSIONS_BACKUP_FILE_NAME); std::string mpath = this->metaPathStr + "/" + std::string(STORAGETK_MSESSIONS_BACKUP_FILE_NAME); bool pathRes = StorageTk::pathExists(path); bool mpathRes = StorageTk::pathExists(mpath); if (!pathRes && !mpathRes) return false; if (pathRes) { bool loadRes = this->sessions->loadFromFile(path, *metaStore); if (!loadRes) { log->logErr("Could not restore all sessions"); retVal = false; } } if (mpathRes) { bool loadRes = this->mirroredSessions->loadFromFile(mpath, *metaStore); if (!loadRes) { log->logErr("Could not restore all mirrored sessions"); retVal = false; } } log->log(Log_NOTICE, "Restored " + StringTk::uintToStr(sessions->getSize()) + " sessions and " + StringTk::uintToStr(mirroredSessions->getSize()) + " mirrored sessions"); return retVal; } bool App::storeSessions() { bool retVal = true; std::string path = this->metaPathStr + "/" + std::string(STORAGETK_SESSIONS_BACKUP_FILE_NAME); std::string mpath = this->metaPathStr + "/" + std::string(STORAGETK_MSESSIONS_BACKUP_FILE_NAME); if (StorageTk::pathExists(path)) log->log(Log_WARNING, "Overwriting existing session file"); bool saveRes = this->sessions->saveToFile(path); if(!saveRes) { this->log->logErr("Could not store all sessions to file " + path); retVal = false; } if (StorageTk::pathExists(mpath)) log->log(Log_WARNING, "Overwriting existing mirror session file"); saveRes = this->mirroredSessions->saveToFile(mpath); if(!saveRes) { this->log->logErr("Could not store all mirror sessions to file " + mpath); retVal = false; } if (retVal) log->log(Log_NOTICE, "Stored " + StringTk::uintToStr(sessions->getSize()) + " sessions and " + StringTk::uintToStr(mirroredSessions->getSize()) + " mirrored sessions"); return retVal; } bool App::deleteSessionFiles() { bool retVal = true; std::string path = this->metaPathStr + "/" + std::string(STORAGETK_SESSIONS_BACKUP_FILE_NAME); std::string mpath = this->metaPathStr + "/" + std::string(STORAGETK_MSESSIONS_BACKUP_FILE_NAME); bool pathRes = StorageTk::pathExists(path); bool mpathRes = StorageTk::pathExists(mpath); if (!pathRes && !mpathRes) return retVal; if (pathRes && remove(path.c_str())) { log->logErr("Could not remove sessions file"); retVal = false; } if (mpathRes && remove(mpath.c_str())) { log->logErr("Could not remove mirrored sessions file"); retVal = false; } return retVal; } void App::checkTargetUUID() { if (!cfg->getStoreFsUUID().empty()) { Path metaPath(cfg->getStoreMetaDirectory() ); // Find out device numbers of underlying device struct stat st; if (stat(metaPath.str().c_str(), &st)) { throw InvalidConfigException("Could not stat metadata directory: " + metaPathStr); } // look for the device path std::ifstream mountInfo("/proc/self/mountinfo"); if (!mountInfo) { throw InvalidConfigException("Could not open /proc/self/mountinfo"); } std::string line, device_path, device_majmin; while (std::getline(mountInfo, line)) { std::istringstream is(line); std::string dummy; is >> dummy >> dummy >> device_majmin >> dummy >> dummy >> dummy >> dummy >> dummy >> dummy >> device_path; auto majmin_f = boost::format("%1%:%2%") % (st.st_dev >> 8) % (st.st_dev & 0xFF); if (majmin_f.str() == device_majmin) break; device_path = ""; } if (device_path.empty()) { throw InvalidConfigException("Could not find a device path that belongs to device " + device_majmin); } // Lookup the fs UUID std::unique_ptr<blkid_struct_probe, void(*)(blkid_struct_probe*)> probe(blkid_new_probe_from_filename(device_path.data()), blkid_free_probe); if (!probe) { throw InvalidConfigException("Failed to open device for probing: " + device_path); } if (blkid_probe_enable_superblocks(probe.get(), 1) < 0) { throw InvalidConfigException("Failed to enable superblock probing"); } if (blkid_do_fullprobe(probe.get()) < 0) { throw InvalidConfigException("Failed to probe device"); } const char* uuid = nullptr; // gets released automatically if (blkid_probe_lookup_value(probe.get(), "UUID", &uuid, nullptr) < 0) { throw InvalidConfigException("Failed to lookup file system UUID"); } std::string uuid_str(uuid); if (cfg->getStoreFsUUID() != uuid_str) { throw InvalidConfigException("UUID of the metadata file system (" + uuid_str + ") does not match the one configured (" + cfg->getStoreFsUUID() + ")"); } } else { LOG(GENERAL, WARNING, "UUID of underlying file system has not conn configured and will " "therefore not be checked. To prevent starting the server accidentally with the wrong " "data, it is strongly recommended to set the storeFsUUID config parameter to " "the appropriate UUID."); } }
32.179904
116
0.687116
congweitao
c1ea541864e67d3598c7f0f9c36cdd7ca95d8c4f
10,990
cpp
C++
interface/src/ui/HMDToolsDialog.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
null
null
null
interface/src/ui/HMDToolsDialog.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
null
null
null
interface/src/ui/HMDToolsDialog.cpp
stojce/hifi
8e6c860a243131859c0706424097db56e6a604bd
[ "Apache-2.0" ]
null
null
null
// // HMDToolsDialog.cpp // interface/src/ui // // Created by Brad Hefta-Gaub on 7/19/13. // Copyright 2013 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <QDesktopWidget> #include <QDialogButtonBox> #include <QFormLayout> #include <QGuiApplication> #include <QLabel> #include <QPushButton> #include <QString> #include <QScreen> #include <QWindow> #include <plugins/PluginManager.h> #include <display-plugins/DisplayPlugin.h> #include "Application.h" #include "MainWindow.h" #include "Menu.h" #include "ui/DialogsManager.h" #include "ui/HMDToolsDialog.h" static const int WIDTH = 350; static const int HEIGHT = 100; HMDToolsDialog::HMDToolsDialog(QWidget* parent) : QDialog(parent, Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowStaysOnTopHint) { // FIXME do we want to support more than one connected HMD? It seems like a pretty corner case foreach(auto displayPlugin, PluginManager::getInstance()->getDisplayPlugins()) { // The first plugin is always the standard 2D display, by convention if (_defaultPluginName.isEmpty()) { _defaultPluginName = displayPlugin->getName(); continue; } if (displayPlugin->isHmd()) { // Not all HMD's have corresponding screens if (displayPlugin->getHmdScreen() >= 0) { _hmdScreenNumber = displayPlugin->getHmdScreen(); } _hmdPluginName = displayPlugin->getName(); break; } } setWindowTitle("HMD Tools"); // Create layouter { QFormLayout* form = new QFormLayout(); // Add a button to enter _switchModeButton = new QPushButton("Toggle HMD Mode"); if (_hmdPluginName.isEmpty()) { _switchModeButton->setEnabled(false); } // Add a button to enter _switchModeButton->setFixedWidth(WIDTH); form->addRow("", _switchModeButton); // Create a label with debug details... _debugDetails = new QLabel(); _debugDetails->setFixedSize(WIDTH, HEIGHT); form->addRow("", _debugDetails); setLayout(form); } qApp->getWindow()->activateWindow(); // watch for our dialog window moving screens. If it does we want to enforce our rules about // what screens we're allowed on watchWindow(windowHandle()); auto dialogsManager = DependencyManager::get<DialogsManager>(); if (qApp->getRunningScriptsWidget()) { watchWindow(qApp->getRunningScriptsWidget()->windowHandle()); } if (qApp->getToolWindow()) { watchWindow(qApp->getToolWindow()->windowHandle()); } if (dialogsManager->getBandwidthDialog()) { watchWindow(dialogsManager->getBandwidthDialog()->windowHandle()); } if (dialogsManager->getOctreeStatsDialog()) { watchWindow(dialogsManager->getOctreeStatsDialog()->windowHandle()); } if (dialogsManager->getLodToolsDialog()) { watchWindow(dialogsManager->getLodToolsDialog()->windowHandle()); } connect(_switchModeButton, &QPushButton::clicked, [this]{ toggleHMDMode(); }); // when the application is about to quit, leave HDM mode connect(qApp, &Application::beforeAboutToQuit, [this]{ // FIXME this is ineffective because it doesn't trigger the menu to // save the fact that VR Mode is not checked. leaveHMDMode(); }); connect(qApp, &Application::activeDisplayPluginChanged, [this]{ updateUi(); }); // watch for our application window moving screens. If it does we want to update our screen details QWindow* mainWindow = qApp->getWindow()->windowHandle(); connect(mainWindow, &QWindow::screenChanged, [this]{ updateUi(); }); // keep track of changes to the number of screens connect(QApplication::desktop(), &QDesktopWidget::screenCountChanged, this, &HMDToolsDialog::screenCountChanged); updateUi(); } HMDToolsDialog::~HMDToolsDialog() { foreach(HMDWindowWatcher* watcher, _windowWatchers) { delete watcher; } _windowWatchers.clear(); } QString HMDToolsDialog::getDebugDetails() const { QString results; if (_hmdScreenNumber >= 0) { results += "HMD Screen: " + QGuiApplication::screens()[_hmdScreenNumber]->name() + "\n"; } else { results += "HMD Screen Name: N/A\n"; } int desktopPrimaryScreenNumber = QApplication::desktop()->primaryScreen(); QScreen* desktopPrimaryScreen = QGuiApplication::screens()[desktopPrimaryScreenNumber]; results += "Desktop's Primary Screen: " + desktopPrimaryScreen->name() + "\n"; results += "Application Primary Screen: " + QGuiApplication::primaryScreen()->name() + "\n"; QScreen* mainWindowScreen = qApp->getWindow()->windowHandle()->screen(); results += "Application Main Window Screen: " + mainWindowScreen->name() + "\n"; results += "Total Screens: " + QString::number(QApplication::desktop()->screenCount()) + "\n"; return results; } void HMDToolsDialog::toggleHMDMode() { if (!qApp->isHMDMode()) { enterHMDMode(); } else { leaveHMDMode(); } } void HMDToolsDialog::enterHMDMode() { if (!qApp->isHMDMode()) { qApp->setActiveDisplayPlugin(_hmdPluginName); qApp->getWindow()->activateWindow(); } } void HMDToolsDialog::leaveHMDMode() { if (qApp->isHMDMode()) { qApp->setActiveDisplayPlugin(_defaultPluginName); qApp->getWindow()->activateWindow(); } } void HMDToolsDialog::reject() { // We don't want this window to be closable from a close icon, just from our "Leave HMD Mode" button } void HMDToolsDialog::closeEvent(QCloseEvent* event) { // We don't want this window to be closable from a close icon, just from our "Leave HMD Mode" button event->ignore(); } void HMDToolsDialog::centerCursorOnWidget(QWidget* widget) { QWindow* window = widget->windowHandle(); QScreen* screen = window->screen(); QPoint windowCenter = window->geometry().center(); QCursor::setPos(screen, windowCenter); } void HMDToolsDialog::updateUi() { _switchModeButton->setText(qApp->isHMDMode() ? "Leave HMD Mode" : "Enter HMD Mode"); _debugDetails->setText(getDebugDetails()); } void HMDToolsDialog::showEvent(QShowEvent* event) { // center the cursor on the hmd tools dialog centerCursorOnWidget(this); updateUi(); } void HMDToolsDialog::hideEvent(QHideEvent* event) { // center the cursor on the main application window centerCursorOnWidget(qApp->getWindow()); } void HMDToolsDialog::screenCountChanged(int newCount) { int hmdScreenNumber = -1; auto displayPlugins = PluginManager::getInstance()->getDisplayPlugins(); foreach(auto dp, displayPlugins) { if (dp->isHmd()) { if (dp->getHmdScreen() >= 0) { hmdScreenNumber = dp->getHmdScreen(); } break; } } if (qApp->isHMDMode() && _hmdScreenNumber != hmdScreenNumber) { qDebug() << "HMD Display changed WHILE IN HMD MODE"; leaveHMDMode(); // if there is a new best HDM screen then go back into HDM mode after done leaving if (hmdScreenNumber >= 0) { qDebug() << "Trying to go back into HMD Mode"; const int SLIGHT_DELAY = 2000; QTimer::singleShot(SLIGHT_DELAY, [this]{ enterHMDMode(); }); } } } void HMDToolsDialog::watchWindow(QWindow* window) { qDebug() << "HMDToolsDialog::watchWindow() window:" << window; if (window && !_windowWatchers.contains(window)) { HMDWindowWatcher* watcher = new HMDWindowWatcher(window, this); _windowWatchers[window] = watcher; } } HMDWindowWatcher::HMDWindowWatcher(QWindow* window, HMDToolsDialog* hmdTools) : _window(window), _hmdTools(hmdTools), _previousScreen(NULL) { connect(window, &QWindow::screenChanged, this, &HMDWindowWatcher::windowScreenChanged); connect(window, &QWindow::xChanged, this, &HMDWindowWatcher::windowGeometryChanged); connect(window, &QWindow::yChanged, this, &HMDWindowWatcher::windowGeometryChanged); connect(window, &QWindow::widthChanged, this, &HMDWindowWatcher::windowGeometryChanged); connect(window, &QWindow::heightChanged, this, &HMDWindowWatcher::windowGeometryChanged); } HMDWindowWatcher::~HMDWindowWatcher() { } void HMDWindowWatcher::windowGeometryChanged(int arg) { _previousRect = _window->geometry(); _previousScreen = _window->screen(); } void HMDWindowWatcher::windowScreenChanged(QScreen* screen) { // if we have more than one screen, and a known hmdScreen then try to // keep our dialog off of the hmdScreen if (QApplication::desktop()->screenCount() > 1) { int hmdScreenNumber = _hmdTools->_hmdScreenNumber; // we want to use a local variable here because we are not necesarily in HMD mode if (hmdScreenNumber >= 0) { QScreen* hmdScreen = QGuiApplication::screens()[hmdScreenNumber]; if (screen == hmdScreen) { qDebug() << "HMD Tools: Whoa! What are you doing? You don't want to move me to the HMD Screen!"; // try to pick a better screen QScreen* betterScreen = NULL; QScreen* lastApplicationScreen = _hmdTools->getLastApplicationScreen(); QWindow* appWindow = qApp->getWindow()->windowHandle(); QScreen* appScreen = appWindow->screen(); if (_previousScreen && _previousScreen != hmdScreen) { // first, if the previous dialog screen is not the HMD screen, then move it there. betterScreen = _previousScreen; } else if (appScreen != hmdScreen) { // second, if the application screen is not the HMD screen, then move it there. betterScreen = appScreen; } else if (lastApplicationScreen && lastApplicationScreen != hmdScreen) { // third, if the application screen is the HMD screen, we want to move it to // the previous screen betterScreen = lastApplicationScreen; } else { // last, if we can't use the previous screen the use the primary desktop screen int desktopPrimaryScreenNumber = QApplication::desktop()->primaryScreen(); QScreen* desktopPrimaryScreen = QGuiApplication::screens()[desktopPrimaryScreenNumber]; betterScreen = desktopPrimaryScreen; } if (betterScreen) { _window->setScreen(betterScreen); _window->setGeometry(_previousRect); } } } } }
35.566343
117
0.643494
stojce
c1ec3c57e46722eccc5fd273c4183b50f4f3aff1
1,804
hpp
C++
shared/src/single_application.hpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
shared/src/single_application.hpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
shared/src/single_application.hpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
/// QasTools: Desktop toolset for the Linux sound system ALSA. /// \copyright See COPYING file. #ifndef __INC_single_application_hpp__ #define __INC_single_application_hpp__ #include <QApplication> #include <QList> #include <QLocalServer> #include <QPointer> class Single_Application : public QApplication { Q_OBJECT // Public methods public: Single_Application ( int & argc, char * argv[], const QString & unique_key_n = QString () ); ~Single_Application (); // Unique key const QString & unique_key () const; bool set_unique_key ( const QString & unique_key_n ); bool is_running () const; // Message bool send_message ( const QString & msg_n ); const QString latest_message () const; // Session management void commitData ( QSessionManager & manager_n ); void saveState ( QSessionManager & manager_n ); // Signals signals: void sig_message_available ( QString mesg_n ); // Protected slots protected slots: void new_client (); void read_clients_data (); void clear_dead_clients (); // Protected methods protected: void publish_message ( QByteArray & data_n ); // Private attributes private: bool _is_running; QString _unique_key; QString _com_key; QString _com_file; QString _latest_message; QLocalServer * _local_server; struct Client { QPointer< QLocalSocket > socket; QByteArray data; }; QList<Client> _clients; const unsigned int _timeout; }; inline bool Single_Application::is_running () const { return _is_running; } inline const QString & Single_Application::unique_key () const { return _unique_key; } inline const QString Single_Application::latest_message () const { return _latest_message; } #endif
15.824561
67
0.695122
amazingidiot
c1f00d76bd6d589ade8d2cf83656cb920d8689ca
3,229
cpp
C++
src/qt/btcu/mninfodialog.cpp
askiiRobotics/orion
b664d3bbcd0c8bde3798724e33cc56aae6d2b6d8
[ "MIT" ]
2
2021-02-05T18:37:43.000Z
2021-04-27T04:29:22.000Z
src/qt/btcu/mninfodialog.cpp
askiiRobotics/orion
b664d3bbcd0c8bde3798724e33cc56aae6d2b6d8
[ "MIT" ]
2
2021-02-15T13:16:49.000Z
2021-05-19T12:06:09.000Z
src/qt/btcu/mninfodialog.cpp
askiiRobotics/orion
b664d3bbcd0c8bde3798724e33cc56aae6d2b6d8
[ "MIT" ]
4
2021-02-22T22:03:39.000Z
2022-03-31T10:18:34.000Z
// Copyright (c) 2019 The PIVX developers // Copyright (c) 2020 The BTCU developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/btcu/mninfodialog.h" #include "qt/btcu/forms/ui_mninfodialog.h" #include "walletmodel.h" #include "wallet/wallet.h" #include "guiutil.h" #include "qt/btcu/qtutils.h" #include <QDateTime> MnInfoDialog::MnInfoDialog(QWidget *parent) : QDialog(parent), ui(new Ui::MnInfoDialog) { ui->setupUi(this); this->setStyleSheet(parent->styleSheet()); setCssProperty(ui->frame, "container-border"); ui->frame->setContentsMargins(10,10,10,10); //setCssProperty(ui->layoutScroll, "container-border"); //setCssProperty(ui->scrollArea, "container-border"); setCssProperty(ui->labelTitle, "text-title-dialog"); QList<QWidget*> lWidjets = {ui->labelName, ui->textName, ui->labelAddress, ui->textAddress, ui->labelPubKey, ui->textPubKey, ui->labelIP, ui->textIP, ui->labelTxId, ui->textTxId, ui->labelOutIndex, ui->textOutIndex, ui->labelStatus, ui->textStatus, ui->textExport}; for(int i = 0; i < lWidjets.size(); ++i) setCssSubtitleScreen(lWidjets.at(i)); setCssProperty({ui->labelDivider1, ui->labelDivider2, ui->labelDivider3, ui->labelDivider4, ui->labelDivider5, ui->labelDivider6, ui->labelDivider7, ui->labelDivider8}, "container-divider"); setCssProperty({ui->pushCopyKey, ui->pushCopyId, ui->pushExport}, "ic-copy-big"); setCssProperty(ui->btnEsc, "ic-close"); connect(ui->btnEsc, SIGNAL(clicked()), this, SLOT(closeDialog())); connect(ui->pushCopyKey, &QPushButton::clicked, [this](){ copyInform(pubKey, "Masternode public key copied"); }); connect(ui->pushCopyId, &QPushButton::clicked, [this](){ copyInform(txId, "Collateral tx id copied"); }); connect(ui->pushExport, &QPushButton::clicked, [this](){ exportMN = true; accept(); }); } void MnInfoDialog::setData(QString name, QString address, QString pubKey, QString ip, QString txId, QString outputIndex, QString status){ this->pubKey = pubKey; this->txId = txId; QString shortPubKey = pubKey; QString shortTxId = txId; if(shortPubKey.length() > 20) { shortPubKey = shortPubKey.left(13) + "..." + shortPubKey.right(13); } if(shortTxId.length() > 20) { shortTxId = shortTxId.left(12) + "..." + shortTxId.right(12); } ui->textName->setText(name); ui->textAddress->setText(address); ui->textPubKey->setText(shortPubKey); ui->textIP->setText(ip); ui->textTxId->setText(shortTxId); ui->textOutIndex->setText(outputIndex); ui->textStatus->setText(status); } void MnInfoDialog::copyInform(QString& copyStr, QString message){ GUIUtil::setClipboard(copyStr); if(!snackBar) snackBar = new SnackBar(nullptr, this); snackBar->setText(tr(message.toStdString().c_str())); snackBar->resize(this->width(), snackBar->height()); openDialog(snackBar, this); } void MnInfoDialog::closeDialog(){ if(snackBar && snackBar->isVisible()) snackBar->hide(); close(); } MnInfoDialog::~MnInfoDialog(){ if(snackBar) delete snackBar; delete ui; }
40.873418
194
0.6869
askiiRobotics
c1f216fd0d04799b4abcb0f5d4789a723dbfe7b6
4,452
cpp
C++
GUI.cpp
guc-cs/FPS-Trainer
84c36af2abf9182fd76fead037ba7f6866a2749b
[ "MIT" ]
null
null
null
GUI.cpp
guc-cs/FPS-Trainer
84c36af2abf9182fd76fead037ba7f6866a2749b
[ "MIT" ]
1
2020-04-11T21:04:28.000Z
2020-04-12T22:05:31.000Z
GUI.cpp
guc-cs/FPS-Trainer
84c36af2abf9182fd76fead037ba7f6866a2749b
[ "MIT" ]
null
null
null
#include <GL/glut.h> #include "GUI.h" GUI gui; Point::Point() { } Point::Point(float posX, float posY) { x = posX; y = posY; } MenuItem::MenuItem() { } MenuItem::MenuItem(char* str) { s = str; } MenuItem::MenuItem(char* str, Point p1, Point p2, Point p3, Point p4) { s = str; one = p1; two = p2; three = p3; four = p4; } void MenuItem::drawItem() { glBegin(GL_LINE_LOOP); glColor3f(1,0,0); glVertex2f(one.x, one.y); glVertex2f(two.x, two.y); glVertex2f(three.x, three.y); glVertex2f(four.x, four.y); glEnd(); } StartMenu::StartMenu() { Point p1 = Point(300,440), p2 = Point(300,500), p3 = Point(500,500), p4 = Point(500,440); Point p5 = Point(300,240), p6 = Point(300,300), p7 = Point(500,300), p8 = Point(500,240); startGame = MenuItem("Start Game", p1, p2, p3, p4); exit = MenuItem("E X I T", p5, p6, p7, p8); } void StartMenu::drawMenu() { gui.draw2D(); startGame.drawItem(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(startGame.one.x + 8, (startGame.one.y + startGame.two.y)/2 - 10, 0); glScaled(0.25, 0.25, 0.25); gui.print(startGame.s, GLUT_STROKE_ROMAN); glPopMatrix(); exit.drawItem(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(exit.one.x + 30, (exit.one.y + exit.two.y)/2 - 10, 0); glScaled(0.25, 0.25, 0.25); gui.print(exit.s, GLUT_STROKE_ROMAN); glPopMatrix(); } PauseMenu::PauseMenu() { Point p1 = Point(300,440), p2 = Point(300,500), p3 = Point(500,500), p4 = Point(500,440); Point p5 = Point(300,320), p6 = Point(300,380), p7 = Point(500,380), p8 = Point(500,320); Point p9 = Point(300,200), p10 = Point(300,260), p11 = Point(500,260), p12 = Point(500,200); resumeGame = MenuItem("Resume", p1, p2, p3, p4); back = MenuItem("Main Menu", p5, p6, p7, p8); exit = MenuItem("E X I T", p9, p10, p11, p12); } void PauseMenu::drawMenu() { gui.draw2D(); resumeGame.drawItem(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(resumeGame.one.x + 40, (resumeGame.one.y + resumeGame.two.y)/2 - 10, 0); glScaled(0.25, 0.25, 0.25); gui.print(resumeGame.s, GLUT_STROKE_ROMAN); glPopMatrix(); back.drawItem(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(back.one.x + 15, (back.one.y + back.two.y)/2 - 10, 0); glScaled(0.25, 0.25, 0.25); gui.print(back.s, GLUT_STROKE_ROMAN); glPopMatrix(); exit.drawItem(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(exit.one.x + 30, (exit.one.y + exit.two.y)/2 - 10, 0); glScaled(0.25, 0.25, 0.25); gui.print(exit.s, GLUT_STROKE_ROMAN); glPopMatrix(); } PlayMenu::PlayMenu() { name = MenuItem("Training"); bullets = MenuItem("Bullets:"); message = MenuItem(""); cursor = MenuItem("."); } void PlayMenu::drawMenu(int nBullets) { gui.draw2D(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(30, 550, 0); glScaled(0.25, 0.25, 0.25); gui.print(name.s, GLUT_STROKE_ROMAN); glPopMatrix(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(650, 550, 0); glScaled(0.25, 0.25, 0.25); char *buffer = new char[2]; //char *text = itoa(nBullets, buffer, 10); gui.print(bullets.s, GLUT_STROKE_ROMAN); //gui.print(text, GLUT_STROKE_ROMAN); glPopMatrix(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(300, 550, 0); glScaled(0.25, 0.25, 0.25); gui.print(message.s, GLUT_STROKE_ROMAN); glPopMatrix(); glPushMatrix(); glLineWidth(5); glColor3f(0.13, 0.54, 0.13); glTranslated(400, 300, 0); glScaled(0.25, 0.25, 0.25); gui.print(cursor.s, GLUT_STROKE_ROMAN); glPopMatrix(); draw3D(); } void PlayMenu::draw3D() { glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-2.0*70/54.0, 2.0*70/54.0, -2.0, 2.0, 0.1, 200); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(2.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); } GUI::GUI() { } void GUI::draw2D() { glDisable( GL_TEXTURE_2D ); glDisable(GL_DEPTH_TEST); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0, 800, 0, 600); glMatrixMode(GL_MODELVIEW); } void GUI::print(char* string, void *font) { char* c; for (c=string; *c != '\0'; c++) glutStrokeCharacter(font, *c); }
22.598985
94
0.623091
guc-cs
c1f79185179907836710189d5ff29b8af4818d3a
9,227
hpp
C++
kty/containers/stringpool.hpp
mattheuslee/Kitty
50bd18dc0b6c895f4b6b816c7340c03dd00a5f40
[ "MIT" ]
null
null
null
kty/containers/stringpool.hpp
mattheuslee/Kitty
50bd18dc0b6c895f4b6b816c7340c03dd00a5f40
[ "MIT" ]
6
2017-08-28T15:39:28.000Z
2018-04-24T16:02:09.000Z
kty/containers/stringpool.hpp
mattheuslee/KittyInterpreter
50bd18dc0b6c895f4b6b816c7340c03dd00a5f40
[ "MIT" ]
null
null
null
#pragma once #include <kty/sizes.hpp> #include <kty/types.hpp> namespace kty { /*! @brief Class that maintains all the strings in the program. The memory pool is created on the stack to avoid heap fragmentation. Holds enough memory to allocate N strings of at most length S. */ template <int N = Sizes::stringpool_size, int S = Sizes::string_length> class StringPool { public: /*! @brief Constructor for the string pool */ StringPool() { Log.verbose(F("%s\n"), PRINT_FUNC); memset((void*)pool_, '\0', N * (S + 1)); memset((void*)refCount_, 0, N * sizeof(int)); numTaken_ = 0; maxNumTaken_ = 0; } /*! @brief Prints stats about the string pool. */ void stat() const { Log.notice(F("%s: num taken = %d, max num taken = %d\n"), PRINT_FUNC, numTaken_, maxNumTaken_); } /*! @brief Resets the stats about the string pool. */ void reset_stat() { Log.verbose(F("%s\n"), PRINT_FUNC); maxNumTaken_ = numTaken_; } /*! @brief Prints the addresses used by the string database */ void dump_addresses() const { Log.notice(F("%s: Pool addresses = %d to %d\n"), PRINT_FUNC, (intptr_t)pool_, (intptr_t)(pool_ + N * (S + 1) - 1)); } /*! @brief Returns the maximum possible length for a string. @return The maximum possible string length. */ int max_str_len() const { Log.verbose(F("%s\n"), PRINT_FUNC); return S; } /*! @brief Checks if an index is owned by this pool. @param idx The index to check. @return True if the index is owned by this pool, false otherwise. */ bool owns(int const & idx) { Log.verbose(F("%s\n"), PRINT_FUNC); return idx >= 0 && idx < N; } /*! @brief Check the number of available blocks left in the pool. @return The number of available blocks left in the pool. */ int available() const { Log.verbose(F("%s\n"), PRINT_FUNC); return N - numTaken_; } /*! @brief Returns the reference count for an index. @param idx The index to get the reference count for. @return The reference count for the index. If the index is invalid, -1 is returned. */ int ref_count(int const & idx) { Log.verbose(F("%s\n"), PRINT_FUNC); if (idx >=0 && idx < N) { return refCount_[idx]; } Log.warning(F("%s: Index %d did not come from pool\n"), PRINT_FUNC, idx); return -1; } /*! @brief Increases the reference count for an index. @param idx The index to increase the reference count for. @return The new reference count of the index. If the address is invalid, -1 is returned. */ int inc_ref_count(int const & idx) { Log.verbose(F("%s\n"), PRINT_FUNC); if (idx >=0 && idx < N) { ++refCount_[idx]; return refCount_[idx]; } Log.warning(F("%s: Index %d did not come from pool\n"), PRINT_FUNC, idx); return -1; } /*! @brief Decreases the reference count for an index. If this operation decreases the reference count to 0, it is not deallocated. To ensure that a decrease to 0 deallocates the index, call deallocate_idx(). @param idx The index to decrease the reference count for. @return The new reference count of the index. If the address is invalid, -1 is returned. */ int dec_ref_count(int const & idx) { Log.verbose(F("%s\n"), PRINT_FUNC); if (idx >=0 && idx < N) { --refCount_[idx]; return refCount_[idx]; } Log.warning(F("%s: Index %d did not come from pool\n"), PRINT_FUNC, idx); return -1; } /*! @brief Gets the next free index for a string. @return An index into the pool if there is space, -1 otherwise. */ int allocate_idx() { Log.verbose(F("%s\n"), PRINT_FUNC); for (int i = 0; i < N; ++i) { if (refCount_[i] == 0) { ++refCount_[i]; ++numTaken_; Log.trace(F("%s: Allocating index %d\n"), PRINT_FUNC, i); memset((void*)(pool_ + (i * (S + 1))), '\0', S + 1); if (numTaken_ > maxNumTaken_) { maxNumTaken_ = numTaken_; Log.trace(F("%s: new maxNumTaken %d\n"), PRINT_FUNC, maxNumTaken_); } return i; } } Log.warning(F("%s: No more string indices to allocate\n"), PRINT_FUNC); return -1; } /*! @brief Returns a string index to the pool @param idx The index to return to the pool @return True if the deallocation was successful, false otherwise. */ bool deallocate_idx(int const & idx) { Log.verbose(F("%s\n"), PRINT_FUNC); if (idx < 0 || idx >= N) { Log.warning(F("%s: Index %d did not come from pool\n"), PRINT_FUNC, idx); return false; } if (refCount_[idx] > 0) { --refCount_[idx]; } else { Log.warning(F("%s: Index %d has already been previously deallocated\n"), PRINT_FUNC, idx); return false; } if (refCount_[idx] == 0) { --numTaken_; Log.trace(F("%s: Index %d deallocated successfully\n"), PRINT_FUNC, idx); return true; } else { Log.trace(F("%s: Index %d is not the last reference\n"), PRINT_FUNC, idx); return true; } } /*! @brief Returns the string at a given index. @param idx The database index for the string. @return str The stored string. */ char * c_str(int const & idx) const { Log.verbose(F("%s\n"), PRINT_FUNC); if (idx >= 0 && idx < N) { return const_cast<char *>(pool_) + (idx * (S + 1)); } Log.warning(F("%s: Index %d is invalid, index range is [0, %d]\n"), PRINT_FUNC, idx, N - 1); return nullptr; } /*! @brief Sets a string in the database, with an optional index to start from. @param idx The database index for the string. @param str The incoming string. @param i The optional starting index within the string to start copying from. Default is index 0. */ void strcpy(int const & idx, char const * str, int const & i = 0) { Log.verbose(F("%s\n"), PRINT_FUNC); int copyStrLen = ::strlen(str); int lenToCopy = (S < copyStrLen ? S : copyStrLen) - i; ::strncpy(c_str(idx) + i, str, lenToCopy); *(c_str(idx) + i + lenToCopy) = '\0'; } /*! @brief Concatenates another string to the end of a string in the pool. @param idx The database index for the string. @param str The incoming string which will be concatenated onto the end. */ void strcat(int const & idx, char const * str) { Log.verbose(F("%s\n"), PRINT_FUNC); int currLen = ::strlen(c_str(idx)); int catStrLen = ::strlen(str); // Length to cat is minimum of remaining space and length of string to cat int lenToCat = ((S - currLen) < catStrLen ? (S - currLen) : catStrLen); Log.verbose(F("%s: length to cat %d\n"), PRINT_FUNC, lenToCat); strncpy(c_str(idx) + currLen, str, lenToCat); *(c_str(idx) + currLen + lenToCat) = '\0'; } private: char pool_[N * (S + 1)]; int refCount_[N]; int numTaken_; int maxNumTaken_; }; /*! @brief Returns a pointer to a stringpool. @param ptr Used to set the address to return for the very first call. Subsequent calls will return this address. @return A pointer to a stringpool. */ StringPool<Sizes::stringpool_size, Sizes::string_length> * get_stringpool(StringPool<Sizes::stringpool_size, Sizes::string_length> * ptr) { static StringPool<Sizes::stringpool_size, Sizes::string_length> * stringPool; if (ptr != nullptr) { stringPool = ptr; } return stringPool; } /*! @brief Class to perform setup of the get_stringpool function at the global scope. */ template <typename StringPool = StringPool<Sizes::stringpool_size, Sizes::string_length>> class GetStringPoolInit { public: /*! @brief Executes the setup call to get_stringpool with the given string pool. @param stringPool The string pool to setup get_stringpool with. */ explicit GetStringPoolInit(StringPool & stringPool) { get_stringpool(&stringPool); } private: }; } // namespace kty
29.860841
139
0.539395
mattheuslee
c1fbe49daca95bdaaa9b831113042e4ac43b03a6
1,863
cpp
C++
Source/Particles/Gather/GetExternalFields.cpp
rlombardini76/artemis
268f59491b263d6ea0197440abc837e1610279fc
[ "BSD-3-Clause-LBNL" ]
2
2020-12-02T15:27:51.000Z
2021-01-13T11:31:37.000Z
Source/Particles/Gather/GetExternalFields.cpp
rlombardini76/artemis
268f59491b263d6ea0197440abc837e1610279fc
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/Particles/Gather/GetExternalFields.cpp
rlombardini76/artemis
268f59491b263d6ea0197440abc837e1610279fc
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include "WarpX.H" #include "Particles/Gather/GetExternalFields.H" GetExternalEField::GetExternalEField (const WarpXParIter& a_pti, int a_offset) noexcept { auto& warpx = WarpX::GetInstance(); auto& mypc = warpx.GetPartContainer(); if (mypc.m_E_ext_particle_s=="constant" || mypc.m_E_ext_particle_s=="default") { m_type = Constant; m_field_value[0] = mypc.m_E_external_particle[0]; m_field_value[1] = mypc.m_E_external_particle[1]; m_field_value[2] = mypc.m_E_external_particle[2]; } else if (mypc.m_E_ext_particle_s=="parse_e_ext_particle_function") { m_type = Parser; m_time = warpx.gett_new(a_pti.GetLevel()); m_get_position = GetParticlePosition(a_pti, a_offset); m_xfield_partparser = getParser(mypc.m_Ex_particle_parser); m_yfield_partparser = getParser(mypc.m_Ey_particle_parser); m_zfield_partparser = getParser(mypc.m_Ez_particle_parser); } } GetExternalBField::GetExternalBField (const WarpXParIter& a_pti, int a_offset) noexcept { auto& warpx = WarpX::GetInstance(); auto& mypc = warpx.GetPartContainer(); if (mypc.m_B_ext_particle_s=="constant" || mypc.m_B_ext_particle_s=="default") { m_type = Constant; m_field_value[0] = mypc.m_B_external_particle[0]; m_field_value[1] = mypc.m_B_external_particle[1]; m_field_value[2] = mypc.m_B_external_particle[2]; } else if (mypc.m_B_ext_particle_s=="parse_b_ext_particle_function") { m_type = Parser; m_time = warpx.gett_new(a_pti.GetLevel()); m_get_position = GetParticlePosition(a_pti, a_offset); m_xfield_partparser = getParser(mypc.m_Bx_particle_parser); m_yfield_partparser = getParser(mypc.m_By_particle_parser); m_zfield_partparser = getParser(mypc.m_Bz_particle_parser); } }
39.638298
87
0.701557
rlombardini76
de00be4d0f1b03344bc2724dfe63180bcba2c6c0
22,435
cpp
C++
src/jitcat/ASTHelper.cpp
mvhooren/JitCat
8e05b51c5feda8fa9258ba443854b23c4ad8bf7c
[ "MIT" ]
14
2019-03-16T07:00:44.000Z
2021-10-20T23:36:51.000Z
src/jitcat/ASTHelper.cpp
mvhooren/JitCat
8e05b51c5feda8fa9258ba443854b23c4ad8bf7c
[ "MIT" ]
13
2019-11-22T12:43:55.000Z
2020-05-25T13:09:08.000Z
src/jitcat/ASTHelper.cpp
mvhooren/JitCat
8e05b51c5feda8fa9258ba443854b23c4ad8bf7c
[ "MIT" ]
1
2019-11-23T17:59:58.000Z
2019-11-23T17:59:58.000Z
/* This file is part of the JitCat library. Copyright (C) Machiel van Hooren 2018 Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ #include "jitcat/ASTHelper.h" #include "jitcat/CatArgumentList.h" #include "jitcat/CatAssignableExpression.h" #include "jitcat/CatBuiltInFunctionCall.h" #include "jitcat/CatIdentifier.h" #include "jitcat/CatIndirectionConversion.h" #include "jitcat/CatRuntimeContext.h" #include "jitcat/CatScopeBlock.h" #include "jitcat/CatTypedExpression.h" #include "jitcat/ExpressionErrorManager.h" #include "jitcat/FunctionSignature.h" #include "jitcat/ReflectableHandle.h" #include "jitcat/Tools.h" #include "jitcat/TypeInfo.h" #include <cassert> #include <sstream> using namespace jitcat; using namespace jitcat::AST; using namespace jitcat::Reflection; void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatScopeBlock>& uPtr, CatStatement* statement) { if (uPtr.get() != static_cast<CatScopeBlock*>(statement)) { uPtr.reset(static_cast<CatScopeBlock*>(statement)); } } void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatStatement>& uPtr, CatStatement* statement) { if (uPtr.get() != statement) { uPtr.reset(statement); } } void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatTypedExpression>& uPtr, CatStatement* expression) { if (uPtr.get() != static_cast<CatTypedExpression*>(expression)) { uPtr.reset(static_cast<CatTypedExpression*>(expression)); } } void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatAssignableExpression>& uPtr, CatStatement* expression) { if (uPtr.get() != static_cast<CatAssignableExpression*>(expression)) { uPtr.reset(static_cast<CatAssignableExpression*>(expression)); } } void ASTHelper::updatePointerIfChanged(std::unique_ptr<CatIdentifier>& uPtr, CatStatement* expression) { if (uPtr.get() != static_cast<CatIdentifier*>(expression)) { uPtr.reset(static_cast<CatIdentifier*>(expression)); } } bool ASTHelper::doTypeConversion(std::unique_ptr<CatTypedExpression>& uPtr, const CatGenericType& targetType) { CatGenericType sourceType = uPtr->getType(); //Currently, only basic type conversions are supported. if ((sourceType.isBasicType() || sourceType.isStringType()) && (targetType.isBasicType() || targetType.isStringType()) && sourceType != targetType) { CatTypedExpression* sourceExpression = uPtr.release(); CatArgumentList* arguments = new CatArgumentList(sourceExpression->getLexeme(), std::vector<CatTypedExpression*>({sourceExpression})); const char* functionName = nullptr; if (targetType.isIntType()) functionName = "toInt"; else if (targetType.isDoubleType()) functionName = "toDouble"; else if (targetType.isFloatType()) functionName = "toFloat"; else if (targetType.isBoolType()) functionName = "toBool"; else if (targetType.isStringType()) functionName = "toString"; assert(functionName != nullptr); CatBuiltInFunctionCall* functionCall = new CatBuiltInFunctionCall(functionName, sourceExpression->getLexeme(), arguments, sourceExpression->getLexeme()); uPtr.reset(functionCall); return true; } return false; } bool ASTHelper::doIndirectionConversion(std::unique_ptr<CatTypedExpression>& uPtr, const CatGenericType& expectedType, bool allowAddressOf, IndirectionConversionMode& conversionMode) { conversionMode = expectedType.getIndirectionConversion(uPtr->getType()); if (conversionMode != IndirectionConversionMode::None && isValidConversionMode(conversionMode)) { if (!isDereferenceConversionMode(conversionMode) && !allowAddressOf) { return false; } std::unique_ptr<CatTypedExpression> expression(uPtr.release()); uPtr = std::make_unique<CatIndirectionConversion>(expression->getLexeme(), expectedType, conversionMode, std::move(expression)); } return isValidConversionMode(conversionMode); } bool ASTHelper::makeSameLeastIndirection(std::unique_ptr<CatTypedExpression>& expression1, std::unique_ptr<CatTypedExpression>& expression2) { int expr1Indirection = 0; expression1->getType().removeIndirection(expr1Indirection); int expr2Indirection = 0; expression2->getType().removeIndirection(expr2Indirection); //we should conert the argument with the highest level of indirection to the same level of indirection as the other argument. if (expr1Indirection != expr2Indirection) { if (expr1Indirection > expr2Indirection) { const CatGenericType* expr1Type = &expression1->getType(); while (expr1Indirection > expr2Indirection) { expr1Type = expr1Type->getPointeeType(); expr1Indirection--; } IndirectionConversionMode mode; if (ASTHelper::doIndirectionConversion(expression1, *expr1Type, false, mode)) { return true; } } else { const CatGenericType* expr2Type = &expression2->getType(); while (expr2Indirection > expr1Indirection) { expr2Type = expr2Type->getPointeeType(); expr2Indirection--; } IndirectionConversionMode mode; if (ASTHelper::doIndirectionConversion(expression2, *expr2Type, false, mode)) { return true; } } } return false; } std::any ASTHelper::doAssignment(CatAssignableExpression* target, CatTypedExpression* source, CatRuntimeContext* context) { const CatGenericType& targetType = target->getAssignableType(); const CatGenericType* sourceType = &source->getType(); std::any targetValue = target->executeAssignable(context); std::any sourceValue; if ((targetType.isPointerToHandleType() || targetType.isPointerToPointerType()) && ( targetType.getPointeeType()->getOwnershipSemantics() == TypeOwnershipSemantics::Owned || targetType.getPointeeType()->getOwnershipSemantics() == TypeOwnershipSemantics::Shared) && (sourceType->getOwnershipSemantics() == TypeOwnershipSemantics::Owned)) { sourceValue = static_cast<CatAssignableExpression*>(source)->executeAssignable(context); sourceType = &static_cast<CatAssignableExpression*>(source)->getAssignableType(); } else { sourceValue = source->execute(context); } return doAssignment(targetValue, sourceValue, targetType, *sourceType); } std::any jitcat::AST::ASTHelper::doGetArgument(CatTypedExpression* argument, const CatGenericType& parameterType, CatRuntimeContext* context) { if (!parameterType.isPointerToReflectableObjectType() || (parameterType.getOwnershipSemantics() != TypeOwnershipSemantics::Owned && !(parameterType.getOwnershipSemantics() == TypeOwnershipSemantics::Shared && argument->getType().getOwnershipSemantics() == TypeOwnershipSemantics::Owned)) || argument->getType().getOwnershipSemantics() == TypeOwnershipSemantics::Value) { return argument->execute(context); } else { assert(argument->isAssignable()); assert(argument->getType().getOwnershipSemantics() == TypeOwnershipSemantics::Owned); std::any sourceValue = static_cast<CatAssignableExpression*>(argument)->executeAssignable(context); const CatGenericType& sourceType = static_cast<CatAssignableExpression*>(argument)->getAssignableType(); if (sourceType.isPointerToPointerType() && sourceType.getPointeeType()->getPointeeType()->isReflectableObjectType()) { unsigned char** reflectableSource = reinterpret_cast<unsigned char**>(sourceType.getRawPointer(sourceValue)); if (reflectableSource != nullptr) { unsigned char* value = *reflectableSource; *reflectableSource = nullptr; return sourceType.getPointeeType()->createFromRawPointer(reinterpret_cast<uintptr_t>(value)); } return sourceType.getPointeeType()->createNullPtr(); } else if (sourceType.isPointerToHandleType()) { ReflectableHandle* handleSource = std::any_cast<ReflectableHandle*>(sourceValue); if (handleSource != nullptr) { unsigned char* value = reinterpret_cast<unsigned char*>(handleSource->get()); *handleSource = nullptr; return sourceType.getPointeeType()->createFromRawPointer(reinterpret_cast<uintptr_t>(value)); } return sourceType.getPointeeType()->createNullPtr(); } else { assert(false); return sourceType.getPointeeType()->createNullPtr(); } } } std::any ASTHelper::doAssignment(std::any& target, std::any& source, const CatGenericType& targetType, const CatGenericType& sourceType) { if (targetType.isPointerType() && targetType.getPointeeType()->isBasicType()) { std::any convertedSource = targetType.removeIndirection().convertToType(source, sourceType); if (targetType.getPointeeType()->isIntType()) { int* intTarget = std::any_cast<int*>(target); if (intTarget != nullptr) { *intTarget = std::any_cast<int>(convertedSource); } } else if (targetType.getPointeeType()->isFloatType()) { float* floatTarget = std::any_cast<float*>(target); if (floatTarget != nullptr) { *floatTarget = std::any_cast<float>(convertedSource); } } else if (targetType.getPointeeType()->isDoubleType()) { double* doubleTarget = std::any_cast<double*>(target); if (doubleTarget != nullptr) { *doubleTarget = std::any_cast<double>(convertedSource); } } else if (targetType.getPointeeType()->isBoolType()) { bool* boolTarget = std::any_cast<bool*>(target); if (boolTarget != nullptr) { *boolTarget = std::any_cast<bool>(convertedSource); } } else if (targetType.isPointerToReflectableObjectType()) { //Not supported for now. This would need to call operator= on the target object, not all objects will have implemented this. assert(false); } return target; } else if (targetType.isStringPtrType() && sourceType.isStringPtrType()) { *std::any_cast<Configuration::CatString*>(target) = *std::any_cast<Configuration::CatString*>(source); return target; } else if (targetType.isStringPtrType() && sourceType.isStringType()) { *std::any_cast<Configuration::CatString*>(target) = std::any_cast<Configuration::CatString>(source); return target; } else if (targetType.isPointerToPointerType() && targetType.getPointeeType()->isPointerToReflectableObjectType()) { unsigned char** reflectableTarget = reinterpret_cast<unsigned char**>(targetType.getRawPointer(target)); if (reflectableTarget != nullptr) { TypeOwnershipSemantics targetOwnership = targetType.getPointeeType()->getOwnershipSemantics(); if (targetOwnership == TypeOwnershipSemantics::Owned && *reflectableTarget != nullptr) { targetType.getPointeeType()->getPointeeType()->getObjectType()->destruct(*reflectableTarget); } if (sourceType.isPointerToReflectableObjectType() || sourceType.isReflectableHandleType()) { *reflectableTarget = reinterpret_cast<unsigned char*>(sourceType.getRawPointer(source)); } else if (sourceType.isPointerToHandleType()) { TypeOwnershipSemantics sourceOwnership = sourceType.getPointeeType()->getOwnershipSemantics(); ReflectableHandle* sourceHandle = std::any_cast<ReflectableHandle*>(source); if (sourceHandle != nullptr) { *reflectableTarget = reinterpret_cast<unsigned char*>(sourceHandle->get()); if ((targetOwnership == TypeOwnershipSemantics::Owned || targetOwnership == TypeOwnershipSemantics::Shared) && sourceOwnership == TypeOwnershipSemantics::Owned) { *sourceHandle = nullptr; } } else { *reflectableTarget = nullptr; } } else if (sourceType.isPointerToPointerType() && sourceType.getPointeeType()->isPointerToReflectableObjectType()) { TypeOwnershipSemantics sourceOwnership = sourceType.getPointeeType()->getOwnershipSemantics(); unsigned char** sourcePointer = reinterpret_cast<unsigned char**>(sourceType.getRawPointer(source)); if (sourcePointer != nullptr) { *reflectableTarget = *sourcePointer; if ((targetOwnership == TypeOwnershipSemantics::Owned || targetOwnership == TypeOwnershipSemantics::Shared) && sourceOwnership == TypeOwnershipSemantics::Owned) { *sourcePointer = nullptr; } } else { *reflectableTarget = nullptr; } } } return target; } else if (targetType.isPointerToHandleType()) { ReflectableHandle* handleTarget = std::any_cast<ReflectableHandle*>(target); if (handleTarget != nullptr) { TypeOwnershipSemantics targetOwnership = targetType.getPointeeType()->getOwnershipSemantics(); if (targetOwnership == TypeOwnershipSemantics::Owned && handleTarget->getIsValid()) { targetType.getPointeeType()->getPointeeType()->getObjectType()->destruct(handleTarget->get()); } if (sourceType.isPointerToReflectableObjectType() || sourceType.isReflectableHandleType()) { handleTarget->setReflectable(reinterpret_cast<unsigned char*>(sourceType.getRawPointer(source)), sourceType.removeIndirection().getObjectType()); } else if (sourceType.isPointerToHandleType()) { ReflectableHandle* sourceHandle = std::any_cast<ReflectableHandle*>(source); if (sourceHandle != nullptr) { *handleTarget = *sourceHandle; if ((targetOwnership == TypeOwnershipSemantics::Owned || targetOwnership == TypeOwnershipSemantics::Shared) && sourceType.getPointeeType()->getOwnershipSemantics() == TypeOwnershipSemantics::Owned) { *sourceHandle = nullptr; } } else { *handleTarget = nullptr; } } else if (sourceType.isPointerToPointerType() && sourceType.getPointeeType()->isPointerToReflectableObjectType()) { unsigned char** sourcePointer = reinterpret_cast<unsigned char**>(sourceType.getRawPointer(source)); if (sourcePointer != nullptr) { handleTarget->setReflectable(*sourcePointer, sourceType.removeIndirection().getObjectType()); if ((targetOwnership == TypeOwnershipSemantics::Owned || targetOwnership == TypeOwnershipSemantics::Shared) && sourceType.getPointeeType()->getOwnershipSemantics() == TypeOwnershipSemantics::Owned) { *sourcePointer = nullptr; } } else { *handleTarget = nullptr; } } } return target; } assert(false); return std::any(); } MemberFunctionInfo* ASTHelper::memberFunctionSearch(const std::string& functionName, const std::vector<CatGenericType>& argumentTypes, TypeInfo* type, ExpressionErrorManager* errorManager, CatRuntimeContext* context, void* errorSource, const Tokenizer::Lexeme& lexeme) { SearchFunctionSignature signature(functionName, argumentTypes); MemberFunctionInfo* functionInfo = type->getMemberFunctionInfo(signature); if (functionInfo != nullptr) { return functionInfo; } else if (functionName == "init") { //If it is the constructor function, also search for the auto-generated constructor if the user-defined constructor was not found. signature.setFunctionName("__init"); functionInfo = type->getMemberFunctionInfo(signature); if (functionInfo != nullptr) { return functionInfo; } } else if (functionName == "destroy") { //If it is the constructor function, also search for the auto-generated constructor if the user-defined constructor was not found. signature.setFunctionName("__destroy"); functionInfo = type->getMemberFunctionInfo(signature); if (functionInfo != nullptr) { return functionInfo; } } //The function was not found. Generate a list of all the functions with that name (that do not match the argument types). std::vector<MemberFunctionInfo*> foundFunctions = type->getMemberFunctionsByName(functionName); if (foundFunctions.size() == 0 && functionName == "init") { foundFunctions = type->getMemberFunctionsByName("__init"); } else if (foundFunctions.size() == 0 && functionName == "detroy") { foundFunctions = type->getMemberFunctionsByName("__destroy"); } if (foundFunctions.size() == 0) { //There exist no functions of that name. errorManager->compiledWithError(Tools::append("Member function not found: ", functionName, "."), errorSource, context->getContextName(), lexeme); return nullptr; } else { MemberFunctionInfo* onlyFunction = nullptr; if (foundFunctions.size() == 1) { onlyFunction = foundFunctions[0]; } else { MemberFunctionInfo* potentialOnlyFunction; int functionsWithSameNumberOfArguments = 0; for (auto& iter : foundFunctions) { if (iter->getNumParameters() == (int)argumentTypes.size()) { functionsWithSameNumberOfArguments++; potentialOnlyFunction = iter; } } if (functionsWithSameNumberOfArguments == 1) { onlyFunction = potentialOnlyFunction; } else if (functionsWithSameNumberOfArguments > 1) { //Print an error with each potential match. std::ostringstream errorStream; errorStream << "Invalid argument(s) for function " << functionName << ". There are " << functionsWithSameNumberOfArguments << " potential candidates: \n"; for (auto& iter : foundFunctions) { if (iter->getNumParameters() == (int)argumentTypes.size()) { errorStream << "\t" << iter->getReturnType().toString() << " " << functionName << "(" << ASTHelper::getTypeListString(iter->getArgumentTypes()) << ")\n"; } } errorManager->compiledWithError(errorStream.str(), errorSource, context->getContextName(), lexeme); return nullptr; } } //There is only one function of that name, or only one function with that number of arguments. //Print errors based on number of arguments and argument types. if (onlyFunction != nullptr) { if (onlyFunction->getNumberOfArguments() != argumentTypes.size()) { errorManager->compiledWithError(Tools::append("Invalid number of arguments for function: ", functionName, " expected ", onlyFunction->getNumberOfArguments(), " arguments."), errorSource, context->getContextName(), lexeme); return nullptr; } else { for (unsigned int i = 0; i < argumentTypes.size(); i++) { if (!onlyFunction->getArgumentType(i).compare(argumentTypes[i], false, false)) { errorManager->compiledWithError(Tools::append("Invalid argument for function: ", functionName, " argument nr: ", i, " expected: ", onlyFunction->getArgumentType(i).toString()), errorSource, context->getContextName(), lexeme); return nullptr; } else if (!ASTHelper::checkOwnershipSemantics(onlyFunction->getArgumentType(i), argumentTypes[i], errorManager, context, errorSource, lexeme, "pass")) { return nullptr; } } } } else { //There are multiple functions with that name, all with a different number of arguments that the number of arguments supplied. //Print an error with each potential match. std::ostringstream errorStream; errorStream << "Invalid number of arguments for function " << functionName << ". There are " << foundFunctions.size() << " potential candidates: \n"; for (auto& iter : foundFunctions) { errorStream << "\t" << iter->getReturnType().toString() << " " << functionName << "(" << ASTHelper::getTypeListString(iter->getArgumentTypes()) << ")\n"; } errorManager->compiledWithError(errorStream.str(), errorSource, context->getContextName(), lexeme); return nullptr; } } return nullptr; } std::string jitcat::AST::ASTHelper::getTypeListString(const std::vector<CatGenericType>& types) { std::ostringstream typeListStream; for (std::size_t i = 0; i < types.size(); ++i) { if (i != 0) typeListStream << ", "; typeListStream << types[i].toString(); } return typeListStream.str(); } bool jitcat::AST::ASTHelper::checkAssignment(const CatTypedExpression* lhs, const CatTypedExpression* rhs, ExpressionErrorManager* errorManager, CatRuntimeContext* context, void* errorSource, const Tokenizer::Lexeme& lexeme) { CatGenericType leftType = lhs->getType(); CatGenericType rightType = rhs->getType(); if ((!leftType.isWritable()) || leftType.isConst() || !lhs->isAssignable()) { errorManager->compiledWithError("Assignment failed because target cannot be assigned.", errorSource, context->getContextName(), lexeme); return false; } else { if (leftType.compare(rightType, false, false)) { if (!checkOwnershipSemantics(leftType, rightType, errorManager, context, errorSource, lexeme, "assign")) { return false; } return true; } else { errorManager->compiledWithError(Tools::append("Cannot assign ", rightType.toString(), " to ", leftType.toString(), "."), errorSource, context->getContextName(), lexeme); return false; } } } bool jitcat::AST::ASTHelper::checkOwnershipSemantics(const CatGenericType& targetType, const CatGenericType& sourceType, ExpressionErrorManager* errorManager, CatRuntimeContext* context, void* errorSource, const Tokenizer::Lexeme& lexeme, const std::string& operation) { TypeOwnershipSemantics leftOwnership = targetType.getOwnershipSemantics(); TypeOwnershipSemantics rightOwnership = sourceType.getOwnershipSemantics(); if (leftOwnership == TypeOwnershipSemantics::Owned) { if (rightOwnership == TypeOwnershipSemantics::Shared) { errorManager->compiledWithError(Tools::append("Cannot ", operation, " shared ownership value to unique ownership value."), errorSource, context->getContextName(), lexeme); return false; } else if (rightOwnership == TypeOwnershipSemantics::Weak) { errorManager->compiledWithError(Tools::append("Cannot ", operation, " weakly-owned value to unique ownership value."), errorSource, context->getContextName(), lexeme); return false; } } else if (leftOwnership == TypeOwnershipSemantics::Shared) { if (rightOwnership == TypeOwnershipSemantics::Weak) { errorManager->compiledWithError(Tools::append("Cannot ", operation, " weakly-owned value to shared ownership value."), errorSource, context->getContextName(), lexeme); return false; } } /*else if (leftOwnership == TypeOwnershipSemantics::Weak) { if (rightOwnership == TypeOwnershipSemantics::Value && !sourceType.isNullptrType()) { errorManager->compiledWithError(Tools::append("Cannot ", operation, " owned temporary value to weak ownership value."), errorSource, context->getContextName(), lexeme); return false; } }*/ if (rightOwnership == TypeOwnershipSemantics::Owned && (leftOwnership == TypeOwnershipSemantics::Owned || leftOwnership == TypeOwnershipSemantics::Shared)) { if (!sourceType.isWritable() || sourceType.isConst()) { errorManager->compiledWithError("Cannot write from owned value because rhs cannot be assigned.", errorSource, context->getContextName(), lexeme); return false; } } return true; }
36.302589
268
0.727925
mvhooren
de03ff19c26b6bfe1f4b0974b048e5b9412c4953
9,211
cpp
C++
src/syntax/lambda_man.cpp
tomoki/Shiranui
0c02933d718ecf5c446ca00c0ede17fd1897f58d
[ "BSD-3-Clause" ]
12
2015-01-10T15:21:09.000Z
2021-04-09T02:53:23.000Z
src/syntax/lambda_man.cpp
tomoki/Shiranui
0c02933d718ecf5c446ca00c0ede17fd1897f58d
[ "BSD-3-Clause" ]
3
2015-01-01T04:26:07.000Z
2015-08-20T12:51:39.000Z
src/syntax/lambda_man.cpp
tomoki/Shiranui
0c02933d718ecf5c446ca00c0ede17fd1897f58d
[ "BSD-3-Clause" ]
1
2020-05-20T08:25:43.000Z
2020-05-20T08:25:43.000Z
#include "lambda_man.hpp" namespace shiranui{ namespace syntax{ void LambdaMarkerScanner::visit(ast::Identifier&){} void LambdaMarkerScanner::visit(ast::Variable&){} void LambdaMarkerScanner::visit(ast::Number&){} void LambdaMarkerScanner::visit(ast::String&){} void LambdaMarkerScanner::visit(ast::Boolean&){} void LambdaMarkerScanner::visit(ast::Enum& node){ for(auto e : node.expressions){ e->accept(*this); } } void LambdaMarkerScanner::visit(ast::Interval& node){ if(node.start != nullptr){ node.start->accept(*this); } if(node.end != nullptr){ node.end->accept(*this); } if(node.next != nullptr){ node.next->accept(*this); } } void LambdaMarkerScanner::visit(ast::Block& node){ for(auto s : node.statements){ s->accept(*this); } for(auto s : node.flymarks){ s->accept(*this); } } void LambdaMarkerScanner::visit(ast::Function& node){ // FIXME: copy is safe,BUT should not.(runtime_infomation is not shared) auto copy = std::make_shared<ast::Function>(node); where_are_you_from[node.body] = copy; if(node.lambda_id.name != ""){ marker_to_lambda[node.lambda_id] = copy; } node.body->accept(*this); } void LambdaMarkerScanner::visit(ast::FunctionCall& node){ node.function->accept(*this); for(auto a : node.arguments){ a->accept(*this); } } void LambdaMarkerScanner::visit(ast::BinaryOperator& node){ node.left->accept(*this); node.right->accept(*this); } void LambdaMarkerScanner::visit(ast::UnaryOperator& node){ node.exp->accept(*this); } void LambdaMarkerScanner::visit(ast::IfElseExpression& node){ node.pred->accept(*this); node.ife->accept(*this); node.elsee->accept(*this); } void LambdaMarkerScanner::visit(ast::Definement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::ExpressionStatement& node){ node.exp->accept(*this); } void LambdaMarkerScanner::visit(ast::ReturnStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::ProbeStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::AssertStatement& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::IfElseStatement& node){ node.pred->accept(*this); node.ifblock->accept(*this); node.elseblock->accept(*this); } // should return forstatement? void LambdaMarkerScanner::visit(ast::ForStatement& node){ node.loop_exp->accept(*this); node.block->accept(*this); } void LambdaMarkerScanner::visit(ast::Assignment& node){ node.value->accept(*this); } void LambdaMarkerScanner::visit(ast::TestFlyLine& node){ // node.left->accept(*this); } void LambdaMarkerScanner::visit(ast::IdleFlyLine& node){ // node.left->accept(*this); } void LambdaMarkerScanner::visit(ast::FlyMark&){} void LambdaMarkerScanner::visit(ast::SourceCode& node){ for(auto s : node.statements){ s->accept(*this); } // for(auto p : node.flylines){ // p->accept(*this); // } } void LambdaMarkerScanner::visit(ast::DSL::DataDSL&){} std::pair< std::map<sp<ast::Block>,sp<ast::Function> >, std::map<ast::Identifier,sp<ast::Function> > > scan_lambda_marker(ast::SourceCode& source){ LambdaMarkerScanner h; h.visit(source); return std::make_pair(h.where_are_you_from, h.marker_to_lambda); } // --------------------------------------------------------------------- LambdaFreeVariableScanner::LambdaFreeVariableScanner(){} void LambdaFreeVariableScanner::visit(ast::Identifier&){} void LambdaFreeVariableScanner::visit(ast::Variable& v){ if(is_free(v.value)){ free.insert(v.value); }else{ } } void LambdaFreeVariableScanner::visit(ast::Number&){} void LambdaFreeVariableScanner::visit(ast::String&){} void LambdaFreeVariableScanner::visit(ast::Boolean&){} void LambdaFreeVariableScanner::visit(ast::Enum& node){ for(auto e : node.expressions){ e->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::Interval& node){ if(node.start != nullptr){ node.start->accept(*this); } if(node.end != nullptr){ node.end->accept(*this); } if(node.next != nullptr){ node.next->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::Block& node){ bound.emplace(); for(auto s : node.statements){ s->accept(*this); } for(auto s : node.flymarks){ s->accept(*this); } bound.pop(); } void LambdaFreeVariableScanner::visit(ast::Function& node){ bound.emplace(); for(auto i : node.parameters){ bound.top().insert(i); } node.body->accept(*this); bound.pop(); } void LambdaFreeVariableScanner::visit(ast::FunctionCall& node){ node.function->accept(*this); for(auto a : node.arguments){ a->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::BinaryOperator& node){ node.left->accept(*this); node.right->accept(*this); } void LambdaFreeVariableScanner::visit(ast::UnaryOperator& node){ node.exp->accept(*this); } void LambdaFreeVariableScanner::visit(ast::IfElseExpression& node){ node.pred->accept(*this); node.ife->accept(*this); node.elsee->accept(*this); } void LambdaFreeVariableScanner::visit(ast::Definement& node){ // for recursive function, add here. bound.top().insert(node.id); node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ExpressionStatement& node){ node.exp->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ReturnStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::ProbeStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::AssertStatement& node){ node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::IfElseStatement& node){ node.pred->accept(*this); node.ifblock->accept(*this); node.elseblock->accept(*this); } // should return forstatement? void LambdaFreeVariableScanner::visit(ast::ForStatement& node){ node.loop_exp->accept(*this); node.block->accept(*this); } void LambdaFreeVariableScanner::visit(ast::Assignment& node){ if(is_free(node.id)){ free.insert(node.id); }else{ } node.value->accept(*this); } void LambdaFreeVariableScanner::visit(ast::TestFlyLine&){} void LambdaFreeVariableScanner::visit(ast::IdleFlyLine&){} void LambdaFreeVariableScanner::visit(ast::FlyMark&){} void LambdaFreeVariableScanner::visit(ast::SourceCode& node){ for(auto s : node.statements){ s->accept(*this); } for(auto p : node.flylines){ p->accept(*this); } } void LambdaFreeVariableScanner::visit(ast::DSL::DataDSL&){} bool LambdaFreeVariableScanner::is_free(ast::Identifier i){ auto copy = bound; while(not copy.empty()){ auto t = copy.top(); if(t.find(i) != t.end()){ return false; } copy.pop(); } return true; } std::set<ast::Identifier> scan_free_variable(ast::Function& f){ LambdaFreeVariableScanner sc; f.accept(sc); return sc.free; } std::set<ast::Identifier> scan_free_variable(sp<ast::Function> fp){ return scan_free_variable(*fp); } } }
36.551587
84
0.525676
tomoki
90024ead7d13719eb9fa2cbabebb488ad8227d5c
7,057
hpp
C++
include/multigraph/functors.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
null
null
null
include/multigraph/functors.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
null
null
null
include/multigraph/functors.hpp
YuanL12/BATS
35a32facc87e17649b7fc32225c8ffaf0301bbfa
[ "MIT" ]
null
null
null
#pragma once /* Functors from one type of diagram to another */ #include "diagram.hpp" #include <topology/data.hpp> #include <topology/cover.hpp> #include <topology/rips.hpp> #include <topology/nerve.hpp> #include <complex/simplicial_complex.hpp> #include <complex/simplicial_map.hpp> #include <chain/chain_complex.hpp> #include <chain/chain_map.hpp> #include <homology/basis.hpp> #include <homology/induced_map.hpp> #include <dgvs/dgvs.hpp> #include <dgvs/dgmap.hpp> #include <homology/dgbasis.hpp> #include <stdexcept> namespace bats { Diagram<SimplicialComplex, CellularMap> Nerve( const Diagram<bats::Cover, std::vector<size_t>> &D, const size_t dmax // maximum simplex dimension ) { size_t n = D.nnode(); size_t m = D.nedge(); // Diagram of simplicial complexes and maps Diagram<SimplicialComplex, CellularMap> TD(n, m); // apply functor to nodes #pragma omp parallel for for (size_t i = 0; i < n; i++) { TD.set_node(i, Nerve(D.node[i], dmax)); } // apply functor to edges #pragma omp parallel for for (size_t i = 0; i < m; i++) { auto s = D.elist[i].src; auto t = D.elist[i].targ; TD.set_edge(i, s, t, SimplicialMap(TD.node[s] , TD.node[t], D.edata[i]) ); } return TD; } // Create diagram of Rips complexes from subsets template <typename T, typename M> Diagram<SimplicialComplex, CellularMap> Rips( const Diagram<std::set<size_t>, std::vector<size_t>> &D, const DataSet<T> &X, const M &dist, // distance const T rmax, // maximum radius const size_t dmax // maximum simplex dimension ) { size_t n = D.nnode(); size_t m = D.nedge(); // Diagram of simplicial complexes and maps Diagram<SimplicialComplex, CellularMap> TD(n, m); // apply functor to nodes #pragma omp parallel for for (size_t i = 0; i < n; i++) { auto XI = get_subset(X, D.node[i]); TD.set_node(i, RipsComplex<SimplicialComplex>(XI, dist, rmax, dmax)); } // apply functor to edges #pragma omp parallel for for (size_t i = 0; i < m; i++) { auto s = D.elist[i].src; auto t = D.elist[i].targ; TD.set_edge(i, s, t, SimplicialMap(TD.node[s] , TD.node[t], D.edata[i]) ); } return TD; } // Create diagram of Rips complexes from subsets // uses a different rips parameter for each node template <typename T, typename M> Diagram<SimplicialComplex, CellularMap> Rips( const Diagram<std::set<size_t>, std::vector<size_t>> &D, const DataSet<T> &X, const M &dist, // distance const std::vector<T> &rmax, // maximum radius for each node const size_t dmax // maximum simplex dimension ) { size_t n = D.nnode(); size_t m = D.nedge(); // Diagram of simplicial complexes and maps Diagram<SimplicialComplex, CellularMap> TD(n, m); // apply functor to nodes #pragma omp parallel for for (size_t i = 0; i < n; i++) { auto XI = get_subset(X, D.node[i]); TD.set_node(i, RipsComplex<SimplicialComplex>(XI, dist, rmax[i], dmax)); } // apply functor to edges #pragma omp parallel for for (size_t i = 0; i < m; i++) { auto s = D.elist[i].src; auto t = D.elist[i].targ; if (rmax[t] < rmax[s]) { throw std::range_error("Rips parameter must be non-decreasing from source to target."); } TD.set_edge(i, s, t, SimplicialMap(TD.node[s] , TD.node[t], D.edata[i]) ); } return TD; } // ChainComplex functor // template over matrix type, diagram type template <typename TM, typename DT> Diagram<ChainComplex<TM>, ChainMap<TM>> ChainFunctor(const DT &D) { size_t n = D.nnode(); size_t m = D.nedge(); // Diagram of chain complexes and chain maps Diagram<ChainComplex<TM>, ChainMap<TM>> CD(n, m); // apply chain functor to nodes #pragma omp parallel for for (size_t i = 0; i < n; i++) { CD.set_node(i, ChainComplex<TM>(D.node[i])); } // apply chain functor to edges #pragma omp parallel for for (size_t j = 0; j < m; j++) { auto s = D.elist[j].src; auto t = D.elist[j].targ; CD.set_edge(j, s, t, ChainMap<TM>(D.edata[j])); } return CD; } template <typename TF, typename DT> inline auto ChainFunctor(const DT &D, TF) { using TM = ColumnMatrix<SparseVector<TF>>; return ChainFunctor<TM>(D); } // easy chain functor template <typename DT, typename T> inline auto __ChainFunctor(const DT &D, T) { using VT = SparseVector<T, size_t>; using MT = ColumnMatrix<VT>; return ChainFunctor<MT, DT>(D); } template <typename CpxT, typename T> inline auto Chain(const Diagram<CpxT, CellularMap>& D, T) { using VT = SparseVector<T, size_t>; using MT = ColumnMatrix<VT>; return ChainFunctor<MT, Diagram<CpxT, CellularMap>>(D); } // Homology functor for dimension k // template over matrix type template <typename TM> Diagram<ReducedChainComplex<TM>, TM> Hom( const Diagram<ChainComplex<TM>, ChainMap<TM>> &D, size_t k ) { size_t n = D.nnode(); size_t m = D.nedge(); // Diagram of chain complexes and chain maps Diagram<ReducedChainComplex<TM>, TM> HD(n, m); // apply hom functor to nodes #pragma omp parallel for for (size_t i = 0; i < n; i++) { HD.set_node(i, ReducedChainComplex<TM>(D.node[i])); } // apply hom functor to edges #pragma omp parallel for for (size_t j = 0; j < m; j++) { auto s = D.elist[j].src; auto t = D.elist[j].targ; HD.set_edge(j, s, t, induced_map(D.edata[j], HD.node[s], HD.node[t], k) ); } return HD; } /** Functor from topological category to category of differential graded vector spaces Chain functor is degree = -1 (default) Cochain functor is degree = +1. This is contravariant (reverses arrows) */ template <typename TM, typename DT> Diagram<DGVectorSpace<TM>, DGLinearMap<TM>> DGLinearFunctor( const DT &D, int degree=-1 ) { size_t n = D.nnode(); size_t m = D.nedge(); // Diagram of chain complexes and chain maps Diagram<DGVectorSpace<TM>, DGLinearMap<TM>> DGD(n, m); // apply chain functor to nodes #pragma omp parallel for for (size_t i = 0; i < n; i++) { DGD.set_node(i, DGVectorSpace<TM>(D.node[i], degree)); } // apply chain functor to edges #pragma omp parallel for for (size_t j = 0; j < m; j++) { auto s = (degree == -1) ? D.elist[j].src : D.elist[j].targ; auto t = (degree == -1) ? D.elist[j].targ : D.elist[j].src; DGD.set_edge(j, s, t, DGLinearMap<TM>(D.edata[j], degree)); } return DGD; } /** Homology functor for dimension k template over matrix type */ template <typename TM> Diagram<ReducedDGVectorSpace<TM>, TM> Hom( const Diagram<DGVectorSpace<TM>, DGLinearMap<TM>> &D, size_t k ) { size_t n = D.nnode(); size_t m = D.nedge(); // Diagram of chain complexes and chain maps Diagram<ReducedDGVectorSpace<TM>, TM> HD(n, m); // apply hom functor to nodes #pragma omp parallel for for (size_t i = 0; i < n; i++) { HD.set_node(i, ReducedDGVectorSpace<TM>(D.node[i])); } // apply hom functor to edges #pragma omp parallel for for (size_t j = 0; j < m; j++) { auto s = D.elist[j].src; auto t = D.elist[j].targ; HD.set_edge(j, s, t, induced_map(D.edata[j], HD.node[s], HD.node[t], k) ); } return HD; } } // namespace bats
24.848592
90
0.659912
YuanL12
9005b1e0cf6005acbdc988b40daf51ac99f3edd1
806
cpp
C++
Problema_88/Problema_88.cpp
EneRgYCZ/Problems
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
[ "MIT" ]
null
null
null
Problema_88/Problema_88.cpp
EneRgYCZ/Problems
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
[ "MIT" ]
null
null
null
Problema_88/Problema_88.cpp
EneRgYCZ/Problems
e8bf9aa4bba2b5ead25fc5ce482a36c861501f46
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <string.h> using namespace std; ifstream fin("palindrom.in"); ofstream fout("palindrom.out"); int main() { int index = 0, ok = 0; char s[256]; fin>>index; for (int i = index; i > 0; i--) { fin.getline(s, 256); int inceput = 0, sfarsit = strlen(s) - 1; for (int j = 0; j <= strlen(s) / 2; j++) { if (s[inceput] == s[sfarsit]) { ok = 1; inceput++; sfarsit--; } else { ok = 0; break; } } if (ok == 1) { fout << 1 << endl; } else { fout << 0 << endl; } ok = 0; } }
19.190476
49
0.361042
EneRgYCZ