text
stringlengths
54
60.6k
<commit_before>//===-- lldb-platform.cpp ---------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <errno.h> #if defined(__APPLE__) #include <netinet/in.h> #endif #include <signal.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if !defined(_WIN32) #include <sys/wait.h> #endif #include <fstream> #include "llvm/Support/FileSystem.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/raw_ostream.h" #include "Acceptor.h" #include "LLDBServerUtilities.h" #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h" #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/HostGetOpt.h" #include "lldb/Host/OptionParser.h" #include "lldb/Host/common/TCPSocket.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; using namespace lldb_private::lldb_server; using namespace lldb_private::process_gdb_remote; using namespace llvm; // option descriptors for getopt_long_only() static int g_debug = 0; static int g_verbose = 0; static int g_server = 0; static struct option g_long_options[] = { {"debug", no_argument, &g_debug, 1}, {"verbose", no_argument, &g_verbose, 1}, {"log-file", required_argument, nullptr, 'l'}, {"log-channels", required_argument, nullptr, 'c'}, {"listen", required_argument, nullptr, 'L'}, {"port-offset", required_argument, nullptr, 'p'}, {"gdbserver-port", required_argument, nullptr, 'P'}, {"min-gdbserver-port", required_argument, nullptr, 'm'}, {"max-gdbserver-port", required_argument, nullptr, 'M'}, {"socket-file", required_argument, nullptr, 'f'}, {"server", no_argument, &g_server, 1}, {nullptr, 0, nullptr, 0}}; #if defined(__APPLE__) #define LOW_PORT (IPPORT_RESERVED) #define HIGH_PORT (IPPORT_HIFIRSTAUTO) #else #define LOW_PORT (1024u) #define HIGH_PORT (49151u) #endif #if !defined(_WIN32) // Watch for signals static void signal_handler(int signo) { switch (signo) { case SIGHUP: // Use SIGINT first, if that does not work, use SIGHUP as a last resort. // And we should not call exit() here because it results in the global // destructors // to be invoked and wreaking havoc on the threads still running. Host::SystemLog(Host::eSystemLogWarning, "SIGHUP received, exiting lldb-server...\n"); abort(); break; } } #endif static void display_usage(const char *progname, const char *subcommand) { fprintf(stderr, "Usage:\n %s %s [--log-file log-file-name] [--log-channels " "log-channel-list] [--port-file port-file-path] --server " "--listen port\n", progname, subcommand); exit(0); } static Status save_socket_id_to_file(const std::string &socket_id, const FileSpec &file_spec) { FileSpec temp_file_spec(file_spec.GetDirectory().AsCString()); Status error(llvm::sys::fs::create_directory(temp_file_spec.GetPath())); if (error.Fail()) return Status("Failed to create directory %s: %s", temp_file_spec.GetCString(), error.AsCString()); llvm::SmallString<64> temp_file_path; temp_file_spec.AppendPathComponent("port-file.%%%%%%"); Status status; if (auto Err = handleErrors(llvm::writeFileAtomically( temp_file_path, temp_file_spec.GetPath(), socket_id), [&status, &temp_file_path, &file_spec](const AtomicFileWriteError &E) { std::string ErrorMsgBuffer; llvm::raw_string_ostream S(ErrorMsgBuffer); E.log(S); switch (E.Error) { case atomic_write_error::failed_to_create_uniq_file: status = Status("Failed to create temp file: %s", ErrorMsgBuffer.c_str()); case atomic_write_error::output_stream_error: status = Status("Failed to write to port file."); case atomic_write_error::failed_to_rename_temp_file: status = Status("Failed to rename file %s to %s: %s", ErrorMsgBuffer.c_str(), file_spec.GetPath().c_str(), ErrorMsgBuffer.c_str()); } })) { return Status("Failed to atomically write file %s", file_spec.GetPath().c_str()); } return status; } // main int main_platform(int argc, char *argv[]) { const char *progname = argv[0]; const char *subcommand = argv[1]; argc--; argv++; #if !defined(_WIN32) signal(SIGPIPE, SIG_IGN); signal(SIGHUP, signal_handler); #endif int long_option_index = 0; Status error; std::string listen_host_port; int ch; std::string log_file; StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all" GDBRemoteCommunicationServerPlatform::PortMap gdbserver_portmap; int min_gdbserver_port = 0; int max_gdbserver_port = 0; uint16_t port_offset = 0; FileSpec socket_file; bool show_usage = false; int option_error = 0; int socket_error = -1; std::string short_options(OptionParser::GetShortOptionString(g_long_options)); #if __GLIBC__ optind = 0; #else optreset = 1; optind = 1; #endif while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1) { switch (ch) { case 0: // Any optional that auto set themselves will return 0 break; case 'L': listen_host_port.append(optarg); break; case 'l': // Set Log File if (optarg && optarg[0]) log_file.assign(optarg); break; case 'c': // Log Channels if (optarg && optarg[0]) log_channels = StringRef(optarg); break; case 'f': // Socket file if (optarg && optarg[0]) socket_file.SetFile(optarg, FileSpec::Style::native); break; case 'p': { if (!llvm::to_integer(optarg, port_offset)) { llvm::errs() << "error: invalid port offset string " << optarg << "\n"; option_error = 4; break; } if (port_offset < LOW_PORT || port_offset > HIGH_PORT) { llvm::errs() << llvm::formatv("error: port offset {0} is not in the " "valid user port range of {1} - {2}\n", port_offset, LOW_PORT, HIGH_PORT); option_error = 5; } } break; case 'P': case 'm': case 'M': { uint16_t portnum; if (!llvm::to_integer(optarg, portnum)) { llvm::errs() << "error: invalid port number string " << optarg << "\n"; option_error = 2; break; } if (portnum < LOW_PORT || portnum > HIGH_PORT) { llvm::errs() << llvm::formatv("error: port number {0} is not in the " "valid user port range of {1} - {2}\n", portnum, LOW_PORT, HIGH_PORT); option_error = 1; break; } if (ch == 'P') gdbserver_portmap[portnum] = LLDB_INVALID_PROCESS_ID; else if (ch == 'm') min_gdbserver_port = portnum; else max_gdbserver_port = portnum; } break; case 'h': /* fall-through is intentional */ case '?': show_usage = true; break; } } if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0)) return -1; // Make a port map for a port range that was specified. if (min_gdbserver_port && min_gdbserver_port < max_gdbserver_port) { for (uint16_t port = min_gdbserver_port; port < max_gdbserver_port; ++port) gdbserver_portmap[port] = LLDB_INVALID_PROCESS_ID; } else if (min_gdbserver_port || max_gdbserver_port) { fprintf(stderr, "error: --min-gdbserver-port (%u) is not lower than " "--max-gdbserver-port (%u)\n", min_gdbserver_port, max_gdbserver_port); option_error = 3; } // Print usage and exit if no listening port is specified. if (listen_host_port.empty()) show_usage = true; if (show_usage || option_error) { display_usage(progname, subcommand); exit(option_error); } // Skip any options we consumed with getopt_long_only. argc -= optind; argv += optind; lldb_private::Args inferior_arguments; inferior_arguments.SetArguments(argc, const_cast<const char **>(argv)); const bool children_inherit_listen_socket = false; // the test suite makes many connections in parallel, let's not miss any. // The highest this should get reasonably is a function of the number // of target CPUs. For now, let's just use 100. const int backlog = 100; std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create( listen_host_port, children_inherit_listen_socket, error)); if (error.Fail()) { fprintf(stderr, "failed to create acceptor: %s", error.AsCString()); exit(socket_error); } error = acceptor_up->Listen(backlog); if (error.Fail()) { printf("failed to listen: %s\n", error.AsCString()); exit(socket_error); } if (socket_file) { error = save_socket_id_to_file(acceptor_up->GetLocalSocketId(), socket_file); if (error.Fail()) { fprintf(stderr, "failed to write socket id to %s: %s\n", socket_file.GetPath().c_str(), error.AsCString()); return 1; } } do { GDBRemoteCommunicationServerPlatform platform( acceptor_up->GetSocketProtocol(), acceptor_up->GetSocketScheme()); if (port_offset > 0) platform.SetPortOffset(port_offset); if (!gdbserver_portmap.empty()) { platform.SetPortMap(std::move(gdbserver_portmap)); } const bool children_inherit_accept_socket = true; Connection *conn = nullptr; error = acceptor_up->Accept(children_inherit_accept_socket, conn); if (error.Fail()) { printf("error: %s\n", error.AsCString()); exit(socket_error); } printf("Connection established.\n"); if (g_server) { // Collect child zombie processes. #if !defined(_WIN32) while (waitpid(-1, nullptr, WNOHANG) > 0) ; #endif if (fork()) { // Parent doesn't need a connection to the lldb client delete conn; // Parent will continue to listen for new connections. continue; } else { // Child process will handle the connection and exit. g_server = 0; // Listening socket is owned by parent process. acceptor_up.release(); } } else { // If not running as a server, this process will not accept // connections while a connection is active. acceptor_up.reset(); } platform.SetConnection(conn); if (platform.IsConnected()) { if (inferior_arguments.GetArgumentCount() > 0) { lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; uint16_t port = 0; std::string socket_name; Status error = platform.LaunchGDBServer(inferior_arguments, "", // hostname pid, port, socket_name); if (error.Success()) platform.SetPendingGdbServer(pid, port, socket_name); else fprintf(stderr, "failed to start gdbserver: %s\n", error.AsCString()); } // After we connected, we need to get an initial ack from... if (platform.HandshakeWithClient()) { bool interrupt = false; bool done = false; while (!interrupt && !done) { if (platform.GetPacketAndSendResponse(llvm::None, error, interrupt, done) != GDBRemoteCommunication::PacketResult::Success) break; } if (error.Fail()) { fprintf(stderr, "error: %s\n", error.AsCString()); } } else { fprintf(stderr, "error: handshake with client failed\n"); } } } while (g_server); fprintf(stderr, "lldb-server exiting...\n"); return 0; } <commit_msg>[LLDB] Add missing breaks for switch statement<commit_after>//===-- lldb-platform.cpp ---------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <errno.h> #if defined(__APPLE__) #include <netinet/in.h> #endif #include <signal.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if !defined(_WIN32) #include <sys/wait.h> #endif #include <fstream> #include "llvm/Support/FileSystem.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/raw_ostream.h" #include "Acceptor.h" #include "LLDBServerUtilities.h" #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h" #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/HostGetOpt.h" #include "lldb/Host/OptionParser.h" #include "lldb/Host/common/TCPSocket.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Status.h" using namespace lldb; using namespace lldb_private; using namespace lldb_private::lldb_server; using namespace lldb_private::process_gdb_remote; using namespace llvm; // option descriptors for getopt_long_only() static int g_debug = 0; static int g_verbose = 0; static int g_server = 0; static struct option g_long_options[] = { {"debug", no_argument, &g_debug, 1}, {"verbose", no_argument, &g_verbose, 1}, {"log-file", required_argument, nullptr, 'l'}, {"log-channels", required_argument, nullptr, 'c'}, {"listen", required_argument, nullptr, 'L'}, {"port-offset", required_argument, nullptr, 'p'}, {"gdbserver-port", required_argument, nullptr, 'P'}, {"min-gdbserver-port", required_argument, nullptr, 'm'}, {"max-gdbserver-port", required_argument, nullptr, 'M'}, {"socket-file", required_argument, nullptr, 'f'}, {"server", no_argument, &g_server, 1}, {nullptr, 0, nullptr, 0}}; #if defined(__APPLE__) #define LOW_PORT (IPPORT_RESERVED) #define HIGH_PORT (IPPORT_HIFIRSTAUTO) #else #define LOW_PORT (1024u) #define HIGH_PORT (49151u) #endif #if !defined(_WIN32) // Watch for signals static void signal_handler(int signo) { switch (signo) { case SIGHUP: // Use SIGINT first, if that does not work, use SIGHUP as a last resort. // And we should not call exit() here because it results in the global // destructors // to be invoked and wreaking havoc on the threads still running. Host::SystemLog(Host::eSystemLogWarning, "SIGHUP received, exiting lldb-server...\n"); abort(); break; } } #endif static void display_usage(const char *progname, const char *subcommand) { fprintf(stderr, "Usage:\n %s %s [--log-file log-file-name] [--log-channels " "log-channel-list] [--port-file port-file-path] --server " "--listen port\n", progname, subcommand); exit(0); } static Status save_socket_id_to_file(const std::string &socket_id, const FileSpec &file_spec) { FileSpec temp_file_spec(file_spec.GetDirectory().AsCString()); Status error(llvm::sys::fs::create_directory(temp_file_spec.GetPath())); if (error.Fail()) return Status("Failed to create directory %s: %s", temp_file_spec.GetCString(), error.AsCString()); llvm::SmallString<64> temp_file_path; temp_file_spec.AppendPathComponent("port-file.%%%%%%"); Status status; if (auto Err = handleErrors(llvm::writeFileAtomically( temp_file_path, temp_file_spec.GetPath(), socket_id), [&status, &temp_file_path, &file_spec](const AtomicFileWriteError &E) { std::string ErrorMsgBuffer; llvm::raw_string_ostream S(ErrorMsgBuffer); E.log(S); switch (E.Error) { case atomic_write_error::failed_to_create_uniq_file: status = Status("Failed to create temp file: %s", ErrorMsgBuffer.c_str()); break; case atomic_write_error::output_stream_error: status = Status("Failed to write to port file."); break; case atomic_write_error::failed_to_rename_temp_file: status = Status("Failed to rename file %s to %s: %s", ErrorMsgBuffer.c_str(), file_spec.GetPath().c_str(), ErrorMsgBuffer.c_str()); break; } })) { return Status("Failed to atomically write file %s", file_spec.GetPath().c_str()); } return status; } // main int main_platform(int argc, char *argv[]) { const char *progname = argv[0]; const char *subcommand = argv[1]; argc--; argv++; #if !defined(_WIN32) signal(SIGPIPE, SIG_IGN); signal(SIGHUP, signal_handler); #endif int long_option_index = 0; Status error; std::string listen_host_port; int ch; std::string log_file; StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all" GDBRemoteCommunicationServerPlatform::PortMap gdbserver_portmap; int min_gdbserver_port = 0; int max_gdbserver_port = 0; uint16_t port_offset = 0; FileSpec socket_file; bool show_usage = false; int option_error = 0; int socket_error = -1; std::string short_options(OptionParser::GetShortOptionString(g_long_options)); #if __GLIBC__ optind = 0; #else optreset = 1; optind = 1; #endif while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1) { switch (ch) { case 0: // Any optional that auto set themselves will return 0 break; case 'L': listen_host_port.append(optarg); break; case 'l': // Set Log File if (optarg && optarg[0]) log_file.assign(optarg); break; case 'c': // Log Channels if (optarg && optarg[0]) log_channels = StringRef(optarg); break; case 'f': // Socket file if (optarg && optarg[0]) socket_file.SetFile(optarg, FileSpec::Style::native); break; case 'p': { if (!llvm::to_integer(optarg, port_offset)) { llvm::errs() << "error: invalid port offset string " << optarg << "\n"; option_error = 4; break; } if (port_offset < LOW_PORT || port_offset > HIGH_PORT) { llvm::errs() << llvm::formatv("error: port offset {0} is not in the " "valid user port range of {1} - {2}\n", port_offset, LOW_PORT, HIGH_PORT); option_error = 5; } } break; case 'P': case 'm': case 'M': { uint16_t portnum; if (!llvm::to_integer(optarg, portnum)) { llvm::errs() << "error: invalid port number string " << optarg << "\n"; option_error = 2; break; } if (portnum < LOW_PORT || portnum > HIGH_PORT) { llvm::errs() << llvm::formatv("error: port number {0} is not in the " "valid user port range of {1} - {2}\n", portnum, LOW_PORT, HIGH_PORT); option_error = 1; break; } if (ch == 'P') gdbserver_portmap[portnum] = LLDB_INVALID_PROCESS_ID; else if (ch == 'm') min_gdbserver_port = portnum; else max_gdbserver_port = portnum; } break; case 'h': /* fall-through is intentional */ case '?': show_usage = true; break; } } if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0)) return -1; // Make a port map for a port range that was specified. if (min_gdbserver_port && min_gdbserver_port < max_gdbserver_port) { for (uint16_t port = min_gdbserver_port; port < max_gdbserver_port; ++port) gdbserver_portmap[port] = LLDB_INVALID_PROCESS_ID; } else if (min_gdbserver_port || max_gdbserver_port) { fprintf(stderr, "error: --min-gdbserver-port (%u) is not lower than " "--max-gdbserver-port (%u)\n", min_gdbserver_port, max_gdbserver_port); option_error = 3; } // Print usage and exit if no listening port is specified. if (listen_host_port.empty()) show_usage = true; if (show_usage || option_error) { display_usage(progname, subcommand); exit(option_error); } // Skip any options we consumed with getopt_long_only. argc -= optind; argv += optind; lldb_private::Args inferior_arguments; inferior_arguments.SetArguments(argc, const_cast<const char **>(argv)); const bool children_inherit_listen_socket = false; // the test suite makes many connections in parallel, let's not miss any. // The highest this should get reasonably is a function of the number // of target CPUs. For now, let's just use 100. const int backlog = 100; std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create( listen_host_port, children_inherit_listen_socket, error)); if (error.Fail()) { fprintf(stderr, "failed to create acceptor: %s", error.AsCString()); exit(socket_error); } error = acceptor_up->Listen(backlog); if (error.Fail()) { printf("failed to listen: %s\n", error.AsCString()); exit(socket_error); } if (socket_file) { error = save_socket_id_to_file(acceptor_up->GetLocalSocketId(), socket_file); if (error.Fail()) { fprintf(stderr, "failed to write socket id to %s: %s\n", socket_file.GetPath().c_str(), error.AsCString()); return 1; } } do { GDBRemoteCommunicationServerPlatform platform( acceptor_up->GetSocketProtocol(), acceptor_up->GetSocketScheme()); if (port_offset > 0) platform.SetPortOffset(port_offset); if (!gdbserver_portmap.empty()) { platform.SetPortMap(std::move(gdbserver_portmap)); } const bool children_inherit_accept_socket = true; Connection *conn = nullptr; error = acceptor_up->Accept(children_inherit_accept_socket, conn); if (error.Fail()) { printf("error: %s\n", error.AsCString()); exit(socket_error); } printf("Connection established.\n"); if (g_server) { // Collect child zombie processes. #if !defined(_WIN32) while (waitpid(-1, nullptr, WNOHANG) > 0) ; #endif if (fork()) { // Parent doesn't need a connection to the lldb client delete conn; // Parent will continue to listen for new connections. continue; } else { // Child process will handle the connection and exit. g_server = 0; // Listening socket is owned by parent process. acceptor_up.release(); } } else { // If not running as a server, this process will not accept // connections while a connection is active. acceptor_up.reset(); } platform.SetConnection(conn); if (platform.IsConnected()) { if (inferior_arguments.GetArgumentCount() > 0) { lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; uint16_t port = 0; std::string socket_name; Status error = platform.LaunchGDBServer(inferior_arguments, "", // hostname pid, port, socket_name); if (error.Success()) platform.SetPendingGdbServer(pid, port, socket_name); else fprintf(stderr, "failed to start gdbserver: %s\n", error.AsCString()); } // After we connected, we need to get an initial ack from... if (platform.HandshakeWithClient()) { bool interrupt = false; bool done = false; while (!interrupt && !done) { if (platform.GetPacketAndSendResponse(llvm::None, error, interrupt, done) != GDBRemoteCommunication::PacketResult::Success) break; } if (error.Fail()) { fprintf(stderr, "error: %s\n", error.AsCString()); } } else { fprintf(stderr, "error: handshake with client failed\n"); } } } while (g_server); fprintf(stderr, "lldb-server exiting...\n"); return 0; } <|endoftext|>
<commit_before>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "callbacks.h" #include "worker/thread.h" using namespace v8; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{out, in, &event_handler} { int err; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } void use_main_log_file(string &&main_log_file) { Logger::toFile(main_log_file.c_str()); } void handle_events() { LOGGER << "Handling events." << endl; } private: Queue in; Queue out; uv_async_t event_handler; WorkerThread worker_thread; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (!as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (!as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; Nan::MaybeLocal<Object> maybeOptions = Nan::To<Object>(info[0]); if (maybeOptions.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybeOptions.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; Nan::Callback *callback = new Nan::Callback(info[1].As<Function>()); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } callback->Call(0, 0); delete callback; } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void initialize(Local<Object> exports) { exports->Set( Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); exports->Set( Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); exports->Set( Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); } NODE_MODULE(sfw, initialize); <commit_msg>Look, boolean logic is hard<commit_after>#include <memory> #include <iostream> #include <string> #include <sstream> #include <functional> #include <nan.h> #include <v8.h> #include <uv.h> #include "log.h" #include "queue.h" #include "callbacks.h" #include "worker/thread.h" using namespace v8; using std::unique_ptr; using std::string; using std::ostringstream; using std::endl; static void handle_events_helper(uv_async_t *handle); class Main { public: Main() : worker_thread{out, in, &event_handler} { int err; err = uv_async_init(uv_default_loop(), &event_handler, handle_events_helper); if (err) return; worker_thread.run(); } void use_main_log_file(string &&main_log_file) { Logger::toFile(main_log_file.c_str()); } void handle_events() { LOGGER << "Handling events." << endl; } private: Queue in; Queue out; uv_async_t event_handler; WorkerThread worker_thread; }; static Main instance; static void handle_events_helper(uv_async_t *handle) { instance.handle_events(); } static bool get_string_option(Local<Object>& options, const char *key_name, string &out) { Nan::HandleScope scope; const Local<String> key = Nan::New<String>(key_name).ToLocalChecked(); Nan::MaybeLocal<Value> as_maybe_value = Nan::Get(options, key); if (as_maybe_value.IsEmpty()) { return true; } Local<Value> as_value = as_maybe_value.ToLocalChecked(); if (as_value->IsUndefined()) { return true; } if (!as_value->IsString()) { ostringstream message; message << "configure() option " << key_name << " must be a String"; Nan::ThrowError(message.str().c_str()); return false; } Nan::Utf8String as_string(as_value); if (*as_string == nullptr) { ostringstream message; message << "configure() option " << key_name << " must be a valid UTF-8 String"; Nan::ThrowError(message.str().c_str()); return false; } out.assign(*as_string, as_string.length()); return true; } void configure(const Nan::FunctionCallbackInfo<Value> &info) { string main_log_file; string worker_log_file; Nan::MaybeLocal<Object> maybeOptions = Nan::To<Object>(info[0]); if (maybeOptions.IsEmpty()) { Nan::ThrowError("configure() requires an option object"); return; } Local<Object> options = maybeOptions.ToLocalChecked(); if (!get_string_option(options, "mainLogFile", main_log_file)) return; if (!get_string_option(options, "workerLogFile", worker_log_file)) return; Nan::Callback *callback = new Nan::Callback(info[1].As<Function>()); if (!main_log_file.empty()) { instance.use_main_log_file(move(main_log_file)); } callback->Call(0, 0); delete callback; } void watch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void unwatch(const Nan::FunctionCallbackInfo<Value> &info) { if (info.Length() != 2) { return Nan::ThrowError("watch() requires two arguments"); } } void initialize(Local<Object> exports) { exports->Set( Nan::New<String>("configure").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(configure)).ToLocalChecked() ); exports->Set( Nan::New<String>("watch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(watch)).ToLocalChecked() ); exports->Set( Nan::New<String>("unwatch").ToLocalChecked(), Nan::GetFunction(Nan::New<FunctionTemplate>(unwatch)).ToLocalChecked() ); } NODE_MODULE(sfw, initialize); <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); // Read fiber center positions and compute related things PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; // spectrometer has to be identified from 0 to F.Npetal-1 F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F);//get neighbors of each fiber; //for each spectrometer, get list of fibers // Read plates in order they are to be observed Plates P = read_plate_centers(F); F.Nplate = P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct galaxy> T(G,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(G,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(G,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(G,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(G,P,pp,F,A); /* print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(G,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(G,P,pp,F,A); redistribute_tf(G,P,pp,F,A); redistribute_tf(G,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(G,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; //printf(" - Plate %d :",j); assign_sf_ss(j,G,P,pp,F,A); // Assign SS and SF just before an observation assign_unused(j,G,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=j-F.Analysis) update_plan_from_one_obs(G,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==2000 || j==4000) { redistribute_tf(G,P,pp,F,A); redistribute_tf(G,P,pp,F,A); improve(G,P,pp,F,A); redistribute_tf(G,P,pp,F,A); } } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,G,P,pp,F,A); // Write output display_results("doc/figs/",G,P,pp,F,A,true); if (F.Verif) A.verif(P,G,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); */ return(0); } <commit_msg>restore remainder of main.cpp<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); // Read fiber center positions and compute related things PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; // spectrometer has to be identified from 0 to F.Npetal-1 F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F);//get neighbors of each fiber; //for each spectrometer, get list of fibers // Read plates in order they are to be observed Plates P = read_plate_centers(F); F.Nplate = P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct galaxy> T(G,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(G,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(G,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(G,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(G,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(G,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(G,P,pp,F,A); redistribute_tf(G,P,pp,F,A); redistribute_tf(G,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(G,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; //printf(" - Plate %d :",j); assign_sf_ss(j,G,P,pp,F,A); // Assign SS and SF just before an observation assign_unused(j,G,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else if (0<=j-F.Analysis) update_plan_from_one_obs(G,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired if ( j==2000 || j==4000) { redistribute_tf(G,P,pp,F,A); redistribute_tf(G,P,pp,F,A); improve(G,P,pp,F,A); redistribute_tf(G,P,pp,F,A); } } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,G,P,pp,F,A); // Write output display_results("doc/figs/",G,P,pp,F,A,true); if (F.Verif) A.verif(P,G,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>#include "machine.h" #include "maitenance.h" #include "order.h" #include "task.h" #include <iostream> #include <vector> #include <algorithm> #include <string> #include <cstdlib> #include <fstream> using std::cout; using std::string; using std::fstream; using std::vector; using std::endl; int main(int argc, char* argv[]){ if (argc < 3){ cout<<"Usage: "<<argv[0]<<" <inputfile> <outputfile>"<<endl; return 1; } /* vector<Task> task_v; vector<Maitenance> maitenance_v; string inputFN, outputFN; fstream inputF, outputF; inputFN = string(argv[1]); outputFN = string(argv[2]); int e_number; inputF.open(inputFN); outputF.open(outputFN); if( inputF ){ inputF >> e_number; string tmp = ""; string tmp1, tmp2, tmp3; for(int i = 0; i < e_number; i++){ Task t; t.id = i; inputF >> tmp; tmp = tmp.substr(0, tmp.length() -1); t.set_op_time(1, atoi(tmp.c_str())); inputF >> tmp >> tmp; tmp = tmp.substr(0, tmp.length()-1); t.set_op_time(2, atoi(tmp.c_str())); inputF >> tmp >>tmp >>tmp; tmp = tmp.substr(0, tmp.length()-1); t.set_rt(atoi(tmp.c_str())); task_v.push_back(t); } while (inputF >> tmp){ inputF>>tmp1; inputF>>tmp2 >> tmp2; inputF>>tmp3 >>tmp3 >>tmp3; Maitenance m(atoi(tmp1.substr(0, tmp1.length()-1).c_str()),atoi(tmp2.substr(0, tmp2.length()-1).c_str()),atoi(tmp3.substr(0, tmp3.length()-1).c_str())) ; maitenance_v.push_back(m); } inputF.close(); }else{ cout<<"Got some error during opening the file\n"; return 1; } for(vector<Task>::size_type i = 0; i < task_v.size(); i++){ cout << task_v[i].get_id() <<";" << task_v[i].get_op_time(1) << ";" << task_v[i].get_op_time(2)<<";"<<task_v[i].get_rt()<<std::endl; } for(vector<Maitenance>::size_type i = 0; i < maitenance_v.size(); i++){ cout<<maitenance_v[i].get_id() <<";" << maitenance_v[i].get_mt() << maitenance_v[i].get_opt()<<std::endl; } //Scheduling cout<<"Scheduling:\n"; vector <int> s; int m = 2000; int temp = 0; vector <Order> orders; for(int i = 0; i < e_number; i++) s.push_back(i); for(int i = 0; i < 10; i++){ Order ord; random_shuffle(s.begin(), s.end()); ord.initialization(s, task_v, maitenance_v); orders.push_back(ord); if(ord.machine2.get_sop() < m){ m = ord.machine2.get_sop(); temp = i; } cout<< "schedule " << i << std::endl <<"\t" << ord.machine2.get_sop() << std::endl; } cout << temp << " " << m << std::endl; return 0;*/ } <commit_msg>temp main created<commit_after>#include "machine.h" #include "maitenance.h" #include "order.h" #include "task.h" #include "generations.h" #include <iostream> #include <vector> #include <algorithm> #include <string> #include <cstdlib> #include <fstream> using std::cout; using std::string; using std::fstream; using std::vector; using std::endl; int main(int argc, char* argv[]){ if (argc != 3){ cout<<"Usage: "<<argv[0]<<" <inputfile> <outputfile>"<<endl; return 1; } Generations gen(argv[1]); gen.next_generation(); gen.dump_generation(); // //do everything return 0; /* vector<Task> task_v; vector<Maitenance> maitenance_v; string inputFN, outputFN; fstream inputF, outputF; inputFN = string(argv[1]); outputFN = string(argv[2]); int e_number; inputF.open(inputFN); outputF.open(outputFN); if( inputF ){ inputF >> e_number; string tmp = ""; string tmp1, tmp2, tmp3; for(int i = 0; i < e_number; i++){ Task t; t.id = i; inputF >> tmp; tmp = tmp.substr(0, tmp.length() -1); t.set_op_time(1, atoi(tmp.c_str())); inputF >> tmp >> tmp; tmp = tmp.substr(0, tmp.length()-1); t.set_op_time(2, atoi(tmp.c_str())); inputF >> tmp >>tmp >>tmp; tmp = tmp.substr(0, tmp.length()-1); t.set_rt(atoi(tmp.c_str())); task_v.push_back(t); } while (inputF >> tmp){ inputF>>tmp1; inputF>>tmp2 >> tmp2; inputF>>tmp3 >>tmp3 >>tmp3; Maitenance m(atoi(tmp1.substr(0, tmp1.length()-1).c_str()),atoi(tmp2.substr(0, tmp2.length()-1).c_str()),atoi(tmp3.substr(0, tmp3.length()-1).c_str())) ; maitenance_v.push_back(m); } inputF.close(); }else{ cout<<"Got some error during opening the file\n"; return 1; } for(vector<Task>::size_type i = 0; i < task_v.size(); i++){ cout << task_v[i].get_id() <<";" << task_v[i].get_op_time(1) << ";" << task_v[i].get_op_time(2)<<";"<<task_v[i].get_rt()<<std::endl; } for(vector<Maitenance>::size_type i = 0; i < maitenance_v.size(); i++){ cout<<maitenance_v[i].get_id() <<";" << maitenance_v[i].get_mt() << maitenance_v[i].get_opt()<<std::endl; } //Scheduling cout<<"Scheduling:\n"; vector <int> s; int m = 2000; int temp = 0; vector <Order> orders; for(int i = 0; i < e_number; i++) s.push_back(i); for(int i = 0; i < 10; i++){ Order ord; random_shuffle(s.begin(), s.end()); ord.initialization(s, task_v, maitenance_v); orders.push_back(ord); if(ord.machine2.get_sop() < m){ m = ord.machine2.get_sop(); temp = i; } cout<< "schedule " << i << std::endl <<"\t" << ord.machine2.get_sop() << std::endl; } cout << temp << " " << m << std::endl; return 0;*/ } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 Stanford University 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. */ /*main.cpp * *The starting point of the network simulator *-Include all network header files *-initilize the network *-initialize the traffic manager and set it to run * * */ #include <sys/time.h> #include <string> #include <cstdlib> #include <iostream> #include <fstream> #ifdef USE_GUI #include <QApplication> #include "bgui.hpp" #endif #include <sstream> #include "booksim.hpp" #include "routefunc.hpp" #include "traffic.hpp" #include "booksim_config.hpp" #include "trafficmanager.hpp" #include "random_utils.hpp" #include "network.hpp" #include "injection.hpp" #include "power_module.hpp" /////////////////////////////////////////////////////////////////////////////// //include new network here// #include "singlenet.hpp" #include "kncube.hpp" #include "fly.hpp" #include "isolated_mesh.hpp" #include "cmo.hpp" #include "cmesh.hpp" #include "cmeshx2.hpp" #include "flatfly_onchip.hpp" #include "qtree.hpp" #include "tree4.hpp" #include "fattree.hpp" #include "anynet.hpp" #include "dragonfly.hpp" /////////////////////////////////////////////////////////////////////////////// //Global declarations ////////////////////// /* the current traffic manager instance */ TrafficManager * trafficManager = NULL; int GetSimTime() { return trafficManager->getTime(); } class Stats; Stats * GetStats(const std::string & name) { Stats* test = trafficManager->getStats(name); if(test == 0){ cout<<"warning statistics "<<name<<" not found"<<endl; } return test; } /* printing activity factor*/ bool _print_activity = false; int gK = 0;//radix int gN = 0;//dimension int gC = 0;//concentration /*These extra variables are necessary for correct traffic pattern generation *The difference is due to concentration, radix 4 with concentration of 4 is *equivalent to radix 8 with no concentration. Though this only really applies *under NOCs since NOCS are inheriently 2 dimension */ int realgk; int realgn; int gNodes = 0; /*These variables are used by NOCS to specify the node concentration per *router. Technically the realdgk realgn can be calculated from these *global variables, thus they maybe removed later */ int xrouter = 0; int yrouter = 0; int xcount = 0; int ycount = 0; //generate nocviewer trace bool gTrace = false; //injection functions map<string, tInjectionProcess> gInjectionProcessMap; //burst rates double gBurstAlpha; double gBurstBeta; /*number of flits per packet, when _use_read_write is false*/ int gConstPacketSize; //for on_off injections vector<int> gNodeStates; ostream * gWatchOut; bool gGUIMode = false; ///////////////////////////////////////////////////////////////////////////// bool AllocatorSim( const Configuration& config ) { vector<Network *> net; string topo; config.GetStr( "topology", topo ); short networks = config.GetInt("physical_subnetworks"); /*To include a new network, must register the network here *add an else if statement with the name of the network */ net.resize(networks); for (int i = 0; i < networks; ++i) { ostringstream name; name << "network_" << i; if ( topo == "torus" ) { KNCube::RegisterRoutingFunctions() ; net[i] = new KNCube( config, name.str(), false ); } else if ( topo == "mesh" ) { KNCube::RegisterRoutingFunctions() ; net[i] = new KNCube( config, name.str(), true ); } else if ( topo == "cmesh" ) { CMesh::RegisterRoutingFunctions() ; net[i] = new CMesh( config, name.str() ); } else if ( topo == "cmeshx2" ) { CMeshX2::RegisterRoutingFunctions() ; net[i] = new CMeshX2( config, name.str() ); } else if ( topo == "fly" ) { KNFly::RegisterRoutingFunctions() ; net[i] = new KNFly( config, name.str() ); } else if ( topo == "single" ) { SingleNet::RegisterRoutingFunctions() ; net[i] = new SingleNet( config, name.str() ); } else if ( topo == "isolated_mesh" ) { IsolatedMesh::RegisterRoutingFunctions() ; net[i] = new IsolatedMesh( config, name.str() ); } else if ( topo == "qtree" ) { QTree::RegisterRoutingFunctions() ; net[i] = new QTree( config, name.str() ); } else if ( topo == "tree4" ) { Tree4::RegisterRoutingFunctions() ; net[i] = new Tree4( config, name.str() ); } else if ( topo == "fattree" ) { FatTree::RegisterRoutingFunctions() ; net[i] = new FatTree( config, name.str() ); } else if ( topo == "flatfly" ) { FlatFlyOnChip::RegisterRoutingFunctions() ; net[i] = new FlatFlyOnChip( config, name.str() ); } else if ( topo == "cmo"){ CMO::RegisterRoutingFunctions() ; net[i] = new CMO(config, name.str()); } else if ( topo == "anynet"){ AnyNet::RegisterRoutingFunctions() ; net[i] = new AnyNet(config, name.str()); } else if ( topo == "dragonflynew"){ DragonFlyNew::RegisterRoutingFunctions() ; net[i] = new DragonFlyNew(config, name.str()); }else { cerr << "Unknown topology " << topo << endl; exit(-1); } /*legacy code that insert random faults in the networks *not sure how to use this */ if ( config.GetInt( "link_failures" ) ) { net[i]->InsertRandomFaults( config ); } } string traffic ; config.GetStr( "traffic", traffic ) ; /*tcc and characterize are legacy *not sure how to use them */ if(trafficManager){ delete trafficManager ; } trafficManager = new TrafficManager( config, net ) ; /*Start the simulation run */ double total_time; /* Amount of time we've run */ struct timeval start_time, end_time; /* Time before/after user code */ total_time = 0.0; gettimeofday(&start_time, NULL); bool result = trafficManager->Run() ; gettimeofday(&end_time, NULL); total_time = ((double)(end_time.tv_sec) + (double)(end_time.tv_usec)/1000000.0) - ((double)(start_time.tv_sec) + (double)(start_time.tv_usec)/1000000.0); cout<<"Total run time "<<total_time<<endl; ///Power analysis if(config.GetInt("sim_power")==1){ Power_Module * pnet = new Power_Module(net[0], trafficManager, config); pnet->run(); delete pnet; } for (int i=0; i<networks; ++i) delete net[i]; return result; } int main( int argc, char **argv ) { BookSimConfig config; #ifdef USE_GUI for(int i = 1; i < argc; ++i) { string arg(argv[i]); if(arg=="-g"){ gGUIMode = true; break; } } #endif if ( !ParseArgs( &config, argc, argv ) ) { #ifdef USE_GUI if(gGUIMode){ cout<< "No config file found"<<endl; cout<< "Usage: " << argv[0] << " configfile... [param=value...]" << endl; cout<< "GUI is using default parameters instead"<<endl; } else { #endif cerr << "Usage: " << argv[0] << " configfile... [param=value...]" << endl; return 0; #ifdef USE_GUI } #endif } /*initialize routing, traffic, injection functions */ InitializeRoutingMap( ); InitializeTrafficMap( ); InitializeInjectionMap( ); _print_activity = (config.GetInt("print_activity")==1); gTrace = (config.GetInt("viewer trace")==1); string watch_out_file; config.GetStr( "watch_out", watch_out_file ); if(watch_out_file == "") { gWatchOut = NULL; } else if(watch_out_file == "-") { gWatchOut = &cout; } else { gWatchOut = new ofstream(watch_out_file.c_str()); } /*configure and run the simulator */ bool result; if(!gGUIMode){ result = AllocatorSim( config ); } else { #ifdef USE_GUI cout<<"GUI Mode\n"; QApplication app(argc, argv); BooksimGUI * bs = new BooksimGUI(); //transfer all the contorl and data to the gui, go to bgui.cpp for the rest bs->RegisterAllocSim(&AllocatorSim,&config); bs->setGeometry(100, 100, 1200, 355); bs->show(); return app.exec(); #endif } PacketReplyInfo::FreePool(); Flit::FreePool(); Credit::FreePool(); return result ? -1 : 0; } <commit_msg>compile GUI-dependent code conditionally<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 Stanford University 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. */ /*main.cpp * *The starting point of the network simulator *-Include all network header files *-initilize the network *-initialize the traffic manager and set it to run * * */ #include <sys/time.h> #include <string> #include <cstdlib> #include <iostream> #include <fstream> #ifdef USE_GUI #include <QApplication> #include "bgui.hpp" #endif #include <sstream> #include "booksim.hpp" #include "routefunc.hpp" #include "traffic.hpp" #include "booksim_config.hpp" #include "trafficmanager.hpp" #include "random_utils.hpp" #include "network.hpp" #include "injection.hpp" #include "power_module.hpp" /////////////////////////////////////////////////////////////////////////////// //include new network here// #include "singlenet.hpp" #include "kncube.hpp" #include "fly.hpp" #include "isolated_mesh.hpp" #include "cmo.hpp" #include "cmesh.hpp" #include "cmeshx2.hpp" #include "flatfly_onchip.hpp" #include "qtree.hpp" #include "tree4.hpp" #include "fattree.hpp" #include "anynet.hpp" #include "dragonfly.hpp" /////////////////////////////////////////////////////////////////////////////// //Global declarations ////////////////////// /* the current traffic manager instance */ TrafficManager * trafficManager = NULL; int GetSimTime() { return trafficManager->getTime(); } class Stats; Stats * GetStats(const std::string & name) { Stats* test = trafficManager->getStats(name); if(test == 0){ cout<<"warning statistics "<<name<<" not found"<<endl; } return test; } /* printing activity factor*/ bool _print_activity = false; int gK = 0;//radix int gN = 0;//dimension int gC = 0;//concentration /*These extra variables are necessary for correct traffic pattern generation *The difference is due to concentration, radix 4 with concentration of 4 is *equivalent to radix 8 with no concentration. Though this only really applies *under NOCs since NOCS are inheriently 2 dimension */ int realgk; int realgn; int gNodes = 0; /*These variables are used by NOCS to specify the node concentration per *router. Technically the realdgk realgn can be calculated from these *global variables, thus they maybe removed later */ int xrouter = 0; int yrouter = 0; int xcount = 0; int ycount = 0; //generate nocviewer trace bool gTrace = false; //injection functions map<string, tInjectionProcess> gInjectionProcessMap; //burst rates double gBurstAlpha; double gBurstBeta; /*number of flits per packet, when _use_read_write is false*/ int gConstPacketSize; //for on_off injections vector<int> gNodeStates; ostream * gWatchOut; #ifdef USE_GUI bool gGUIMode = false; #endif ///////////////////////////////////////////////////////////////////////////// bool AllocatorSim( const Configuration& config ) { vector<Network *> net; string topo; config.GetStr( "topology", topo ); short networks = config.GetInt("physical_subnetworks"); /*To include a new network, must register the network here *add an else if statement with the name of the network */ net.resize(networks); for (int i = 0; i < networks; ++i) { ostringstream name; name << "network_" << i; if ( topo == "torus" ) { KNCube::RegisterRoutingFunctions() ; net[i] = new KNCube( config, name.str(), false ); } else if ( topo == "mesh" ) { KNCube::RegisterRoutingFunctions() ; net[i] = new KNCube( config, name.str(), true ); } else if ( topo == "cmesh" ) { CMesh::RegisterRoutingFunctions() ; net[i] = new CMesh( config, name.str() ); } else if ( topo == "cmeshx2" ) { CMeshX2::RegisterRoutingFunctions() ; net[i] = new CMeshX2( config, name.str() ); } else if ( topo == "fly" ) { KNFly::RegisterRoutingFunctions() ; net[i] = new KNFly( config, name.str() ); } else if ( topo == "single" ) { SingleNet::RegisterRoutingFunctions() ; net[i] = new SingleNet( config, name.str() ); } else if ( topo == "isolated_mesh" ) { IsolatedMesh::RegisterRoutingFunctions() ; net[i] = new IsolatedMesh( config, name.str() ); } else if ( topo == "qtree" ) { QTree::RegisterRoutingFunctions() ; net[i] = new QTree( config, name.str() ); } else if ( topo == "tree4" ) { Tree4::RegisterRoutingFunctions() ; net[i] = new Tree4( config, name.str() ); } else if ( topo == "fattree" ) { FatTree::RegisterRoutingFunctions() ; net[i] = new FatTree( config, name.str() ); } else if ( topo == "flatfly" ) { FlatFlyOnChip::RegisterRoutingFunctions() ; net[i] = new FlatFlyOnChip( config, name.str() ); } else if ( topo == "cmo"){ CMO::RegisterRoutingFunctions() ; net[i] = new CMO(config, name.str()); } else if ( topo == "anynet"){ AnyNet::RegisterRoutingFunctions() ; net[i] = new AnyNet(config, name.str()); } else if ( topo == "dragonflynew"){ DragonFlyNew::RegisterRoutingFunctions() ; net[i] = new DragonFlyNew(config, name.str()); }else { cerr << "Unknown topology " << topo << endl; exit(-1); } /*legacy code that insert random faults in the networks *not sure how to use this */ if ( config.GetInt( "link_failures" ) ) { net[i]->InsertRandomFaults( config ); } } string traffic ; config.GetStr( "traffic", traffic ) ; /*tcc and characterize are legacy *not sure how to use them */ if(trafficManager){ delete trafficManager ; } trafficManager = new TrafficManager( config, net ) ; /*Start the simulation run */ double total_time; /* Amount of time we've run */ struct timeval start_time, end_time; /* Time before/after user code */ total_time = 0.0; gettimeofday(&start_time, NULL); bool result = trafficManager->Run() ; gettimeofday(&end_time, NULL); total_time = ((double)(end_time.tv_sec) + (double)(end_time.tv_usec)/1000000.0) - ((double)(start_time.tv_sec) + (double)(start_time.tv_usec)/1000000.0); cout<<"Total run time "<<total_time<<endl; ///Power analysis if(config.GetInt("sim_power")==1){ Power_Module * pnet = new Power_Module(net[0], trafficManager, config); pnet->run(); delete pnet; } for (int i=0; i<networks; ++i) delete net[i]; return result; } int main( int argc, char **argv ) { BookSimConfig config; #ifdef USE_GUI for(int i = 1; i < argc; ++i) { string arg(argv[i]); if(arg=="-g"){ gGUIMode = true; break; } } #endif if ( !ParseArgs( &config, argc, argv ) ) { #ifdef USE_GUI if(gGUIMode){ cout<< "No config file found"<<endl; cout<< "Usage: " << argv[0] << " configfile... [param=value...]" << endl; cout<< "GUI is using default parameters instead"<<endl; } else { #endif cerr << "Usage: " << argv[0] << " configfile... [param=value...]" << endl; return 0; #ifdef USE_GUI } #endif } /*initialize routing, traffic, injection functions */ InitializeRoutingMap( ); InitializeTrafficMap( ); InitializeInjectionMap( ); _print_activity = (config.GetInt("print_activity")==1); gTrace = (config.GetInt("viewer trace")==1); string watch_out_file; config.GetStr( "watch_out", watch_out_file ); if(watch_out_file == "") { gWatchOut = NULL; } else if(watch_out_file == "-") { gWatchOut = &cout; } else { gWatchOut = new ofstream(watch_out_file.c_str()); } /*configure and run the simulator */ bool result; #ifdef USE_GUI if(!gGUIMode){ #endif result = AllocatorSim( config ); #ifdef USE_GUI } else { cout<<"GUI Mode\n"; QApplication app(argc, argv); BooksimGUI * bs = new BooksimGUI(); //transfer all the contorl and data to the gui, go to bgui.cpp for the rest bs->RegisterAllocSim(&AllocatorSim,&config); bs->setGeometry(100, 100, 1200, 355); bs->show(); return app.exec(); } #endif PacketReplyInfo::FreePool(); Flit::FreePool(); Credit::FreePool(); return result ? -1 : 0; } <|endoftext|>
<commit_before>/*[email protected]*/ #include <QtWidgets/QApplication> #include "ignsdk.h" #include <QtWebKitWidgets/QWebView> #include <QFileDialog> #include <iostream> #include "version.h" #include <QCommandLineParser> using namespace std; int main(int argc, char *argv[]){ QApplication app(argc, argv); ign ignsdk; QString url = NULL; bool file = false; QString optional; QCommandLineParser cmd_parser; cmd_parser.setApplicationDescription("IGOS Nusantara Software Development Kit"); QCommandLineOption cmd_project(QStringList() << "p" << "project", "Specify project directory", "directory"); cmd_parser.addOption(cmd_project); QCommandLineOption cmd_file(QStringList() << "f" << "file", "Load specific HTML file instead of index.html", "file"); cmd_parser.addOption(cmd_file); QCommandLineOption cmd_dev(QStringList() << "d" << "development", "Activate development mode"); cmd_parser.addOption(cmd_dev); QCommandLineOption cmd_remote(QStringList() << "r" << "remote", "Activate remote debugging", "port"); cmd_parser.addOption(cmd_remote); QCommandLineOption cmd_version(QStringList() << "v" << "version", "Show version"); cmd_parser.addOption(cmd_version); cmd_parser.addHelpOption(); cmd_parser.process(app); if (cmd_parser.isSet(cmd_version)){ printf("IGNSDK version %s (%s). Compiled on %s %s. Maintained by %s.\n", IGNSDK_VERSION, IGNSDK_CODENAME, __DATE__, __TIME__, IGNSDK_MAINTAINER); exit(0); } url = cmd_parser.value(cmd_project); if (cmd_parser.isSet(cmd_remote)){ ignsdk.setDevRemote(cmd_parser.value(cmd_remote).toInt()); } if (cmd_parser.isSet(cmd_file)){ if (cmd_parser.isSet(cmd_project)){ file = true; optional = cmd_parser.value(cmd_file); } else { qDebug() << "Error: Project directory must be specified."; exit(1); } } if (cmd_parser.isSet(cmd_dev)){ ignsdk.setDev(true); } QString opt = url; QString path = url; if (!opt.isEmpty()){ ignsdk.pathApp = opt; app.setWindowIcon(QIcon(path + "icons/app.png")); if (file){ opt += "/"; opt += optional; } else { opt += "/index.html"; } if (QFile::exists(opt)){ ignsdk.render(opt); ignsdk.config(url); ignsdk.show(); } else { qDebug() << "Error:" << opt << "is not exist."; exit(1); } } else { QFileDialog *fileDialog = new QFileDialog; #ifdef Linux QTreeView *tree = fileDialog->findChild <QTreeView*>(); tree->setRootIsDecorated(true); tree->setItemsExpandable(true); #endif fileDialog->setFileMode(QFileDialog::Directory); fileDialog->setOption(QFileDialog::ShowDirsOnly); fileDialog->setViewMode(QFileDialog::Detail); int result = fileDialog->exec(); QString directory; if (result){ directory = fileDialog->selectedFiles()[0]; if (QFile::exists(directory + "/index.html")) { ignsdk.config(directory); ignsdk.render(directory + "/index.html"); ignsdk.show(); } else { qDebug() << "Error:" << (directory + "/index.html") << "is not exist."; exit(1); } } else { exit(1); } } return app.exec(); } <commit_msg>src/main.cpp: Fix window icon bug if project's path doesn't end with slash<commit_after>/*[email protected]*/ #include <QtWidgets/QApplication> #include "ignsdk.h" #include <QtWebKitWidgets/QWebView> #include <QFileDialog> #include <iostream> #include "version.h" #include <QCommandLineParser> using namespace std; int main(int argc, char *argv[]){ QApplication app(argc, argv); ign ignsdk; QString url = NULL; bool file = false; QString optional; QCommandLineParser cmd_parser; cmd_parser.setApplicationDescription("IGOS Nusantara Software Development Kit"); QCommandLineOption cmd_project(QStringList() << "p" << "project", "Specify project directory", "directory"); cmd_parser.addOption(cmd_project); QCommandLineOption cmd_file(QStringList() << "f" << "file", "Load specific HTML file instead of index.html", "file"); cmd_parser.addOption(cmd_file); QCommandLineOption cmd_dev(QStringList() << "d" << "development", "Activate development mode"); cmd_parser.addOption(cmd_dev); QCommandLineOption cmd_remote(QStringList() << "r" << "remote", "Activate remote debugging", "port"); cmd_parser.addOption(cmd_remote); QCommandLineOption cmd_version(QStringList() << "v" << "version", "Show version"); cmd_parser.addOption(cmd_version); cmd_parser.addHelpOption(); cmd_parser.process(app); if (cmd_parser.isSet(cmd_version)){ printf("IGNSDK version %s (%s). Compiled on %s %s. Maintained by %s.\n", IGNSDK_VERSION, IGNSDK_CODENAME, __DATE__, __TIME__, IGNSDK_MAINTAINER); exit(0); } url = cmd_parser.value(cmd_project); if (cmd_parser.isSet(cmd_remote)){ ignsdk.setDevRemote(cmd_parser.value(cmd_remote).toInt()); } if (cmd_parser.isSet(cmd_file)){ if (cmd_parser.isSet(cmd_project)){ file = true; optional = cmd_parser.value(cmd_file); } else { qDebug() << "Error: Project directory must be specified."; exit(1); } } if (cmd_parser.isSet(cmd_dev)){ ignsdk.setDev(true); } QString opt = url; QString path = url; if (!opt.isEmpty()){ ignsdk.pathApp = opt; app.setWindowIcon(QIcon(path + "/icons/app.png")); if (file){ opt += "/"; opt += optional; } else { opt += "/index.html"; } if (QFile::exists(opt)){ ignsdk.render(opt); ignsdk.config(url); ignsdk.show(); } else { qDebug() << "Error:" << opt << "is not exist."; exit(1); } } else { QFileDialog *fileDialog = new QFileDialog; #ifdef Linux QTreeView *tree = fileDialog->findChild <QTreeView*>(); tree->setRootIsDecorated(true); tree->setItemsExpandable(true); #endif fileDialog->setFileMode(QFileDialog::Directory); fileDialog->setOption(QFileDialog::ShowDirsOnly); fileDialog->setViewMode(QFileDialog::Detail); int result = fileDialog->exec(); QString directory; if (result){ directory = fileDialog->selectedFiles()[0]; if (QFile::exists(directory + "/index.html")) { ignsdk.config(directory); ignsdk.render(directory + "/index.html"); ignsdk.show(); } else { qDebug() << "Error:" << (directory + "/index.html") << "is not exist."; exit(1); } } else { exit(1); } } return app.exec(); } <|endoftext|>
<commit_before>#include "chip8.h" chip8 Chip8; SDL_Window *window = nullptr; SDL_Renderer *renderer = nullptr; static const uint8_t SCREEN_WIDTH = 64; static const uint8_t SCREEN_HEIGHT = 32; static const uint8_t PIXEL_SIZE = 12; // Temporary pixel buffer uint32_t pixels[2048]; // Chip8 Keypad uint8_t keymap[16] = { SDLK_x, SDLK_1, SDLK_2, SDLK_3, SDLK_q, SDLK_w, SDLK_e, SDLK_a, SDLK_s, SDLK_d, SDLK_z, SDLK_c, SDLK_4, SDLK_r, SDLK_f, SDLK_v, }; void init_SDL() { //Initialize all SDL subsystems SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow("Chip8 Emulator", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 512, 256, NULL); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: Chip8.exe chip8application\n\n"); return 1; } init_SDL(); // Load game load: if (!Chip8.loadApplication(argv[1])) return 1; SDL_Event e; bool running = true; // Emulation loop while (running) { // Process SDL events while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) exit(0); // Process keydown events if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_ESCAPE) exit(0); if (e.key.keysym.sym == SDLK_F1) goto load; // *gasp*, a goto statement! // Used to reset/reload ROM for (int i = 0; i < 16; ++i) { if (e.key.keysym.sym == keymap[i]) { Chip8.key[i] = 1; } } } // Process keyup events if (e.type == SDL_KEYUP) { for (int i = 0; i < 16; ++i) { if (e.key.keysym.sym == keymap[i]) { Chip8.key[i] = 0; } } } } Chip8.emulateCycle(); // If draw occurred, redraw SDL screen if (Chip8.drawFlag) { // Clear screen SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); // Draw screen SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_Rect *destRect = new SDL_Rect; destRect->x = 0; destRect->y = 0; destRect->w = 8; destRect->h = 8; for (int y = 0; y < 32; y++) { for (int x = 0; x < 64; x++) { if (Chip8.gfx[(y * 64) + x] == 1) { destRect->x = x * 8; destRect->y = y * 8; SDL_RenderFillRect(renderer, destRect); } } } delete destRect; SDL_RenderPresent(renderer); Chip8.drawFlag = false; } // Sleep to slow down emulation speed std::this_thread::sleep_for(std::chrono::microseconds(1200)); } SDL_Quit(); }<commit_msg>Cleanup main.cpp<commit_after>#include "chip8.h" chip8 Chip8; SDL_Window *window = nullptr; SDL_Renderer *renderer = nullptr; static const uint8_t SCREEN_WIDTH = 64; static const uint8_t SCREEN_HEIGHT = 32; //static const uint8_t PIXEL_SIZE = 12; // Temporary pixel buffer CURRENTLY DONT USE MIGHT UPDATE LATER // uint32_t pixels[2048]; // Chip8 Keypad uint8_t keymap[16] = { SDLK_x, SDLK_1, SDLK_2, SDLK_3, SDLK_q, SDLK_w, SDLK_e, SDLK_a, SDLK_s, SDLK_d, SDLK_z, SDLK_c, SDLK_4, SDLK_r, SDLK_f, SDLK_v, }; void init_SDL() { // Initialize SDL Video // TODO: Sound SDL_Init(SDL_INIT_VIDEO); window = SDL_CreateWindow("Chip8 Emulator", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 512, 256, NULL); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: Chip8.exe chip8application\n\n"); return 1; } init_SDL(); // Load game load: if (!Chip8.loadApplication(argv[1])) return 1; SDL_Event e; bool running = true; // Emulation loop while (running) { // Process SDL events while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) exit(0); // Process keydown events if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_ESCAPE) exit(0); if (e.key.keysym.sym == SDLK_F1) goto load; // *gasp*, a goto statement! // Used to reset/reload ROM for (int i = 0; i < 16; ++i) { if (e.key.keysym.sym == keymap[i]) { Chip8.key[i] = 1; } } } // Process keyup events if (e.type == SDL_KEYUP) { for (int i = 0; i < 16; ++i) { if (e.key.keysym.sym == keymap[i]) { Chip8.key[i] = 0; } } } } Chip8.emulateCycle(); // If draw occurred, redraw SDL screen if (Chip8.drawFlag) { // Clear screen SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); // Draw screen SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); SDL_Rect *destRect = new SDL_Rect; destRect->x = 0; destRect->y = 0; destRect->w = 8; destRect->h = 8; for (int y = 0; y < 32; y++) { for (int x = 0; x < 64; x++) { if (Chip8.gfx[(y * 64) + x] == 1) { destRect->x = x * 8; destRect->y = y * 8; SDL_RenderFillRect(renderer, destRect); } } } delete destRect; SDL_RenderPresent(renderer); Chip8.drawFlag = false; } // Sleep to slow down emulation speed //std::this_thread::sleep_for(std::chrono::microseconds(1200)); } SDL_Quit(); }<|endoftext|>
<commit_before>#include "multi_traceroute.h" #include "net/enums.h" #include <vector> #include <string> #include <iostream> #include <iomanip> #include <chrono> #include <cstdlib> #include <unistd.h> using std::vector; constexpr AddressFamily DEF_AF_IN_UNKNOWN = AddressFamily::Inet; constexpr int DEF_PROBES = 3; constexpr int DEF_SENDWAIT = 10; constexpr int DEF_WAITTIME = 500; constexpr int DEF_START_TTL = 1; constexpr int DEF_MAX_TTL = 30; constexpr bool DEF_MAP_IP_TO_HOST = true; void print_routes(vector<vector<vector<ProbeInfo>>> &probes_info, vector<DestInfo> &dest, TraceOptions options) { // TTLs of last packet that sucessfully returned for each destination vector<int> last_arrived(dest.size(), options.start_ttl - 1); for (size_t d = 0; d < probes_info.size(); ++d) { for (size_t ttl = 0; ttl < probes_info[d].size(); ++ttl) { for (const auto &probe : probes_info[d][ttl]) { if (probe.did_arrive) { last_arrived[d] = ttl + options.start_ttl; } } } } for (size_t d = 0; d < probes_info.size(); ++d) { std::cout << "traceroute to " << dest[d].dest_str << " (" << dest[d].address.get_ip_str() << "), " << options.max_ttl << " hops max\n"; bool dest_reached = false; for (size_t ttl = 0; ttl + options.start_ttl <= last_arrived[d]; ++ttl) { std::cout << std::setw(2) << ttl + options.start_ttl; std::string last_ip = ""; for (size_t p = 0; p < probes_info[d][ttl].size(); ++p) { const ProbeInfo &probe = probes_info[d][ttl][p]; if (!probe.did_arrive) { std::cout << " *"; continue; } std::string ip = probe.offender.get_ip_str(); int rtt = std::chrono::duration_cast<std::chrono::microseconds>(probe.recv_time - probe.send_time).count(); if (ip != last_ip) { if (p != 0) { std::cout << "\n "; } if (options.map_ip_to_host) { std::cout << " " << probe.offender.get_hostname() << " (" << ip << ")"; } else { std::cout << " " << ip; } } std::cout << " " << std::fixed << std::setprecision(3) << static_cast<double>(rtt) / 1000 << " ms"; switch (probe.icmp_status) { case IcmpRespStatus::HostUnreachable: std::cout << " !H"; dest_reached = true; break; case IcmpRespStatus::NetworkUnreachable: std::cout << " !N"; dest_reached = true; break; case IcmpRespStatus::ProtocolUnreachable: std::cout << " !P"; dest_reached = true; break; case IcmpRespStatus::AdminProhibited: std::cout << " !X"; dest_reached = true; break; case IcmpRespStatus::EchoReply: dest_reached = true; break; default: break; } last_ip = ip; } std::cout << std::endl; } /* * Show that the destination wasn't reached * Eg.: * 16 et-17-1.fab1-1-gdc.ne1.yahoo.com (98.138.0.79) 223.473 ms 225.312 ms * 17 po-10.bas1-7-prd.ne1.yahoo.com (98.138.240.6) 225.251 ms 226.105 ms * . * * * * . * * * * 21 * * * */ if (!dest_reached && last_arrived[d] < options.max_ttl) { int dotted = std::min(options.max_ttl - last_arrived[d] - 1, 2); for (int i = 0; i < dotted; ++i) { std::cout << " . * * *\n"; } std::cout << std::setw(2) << options.max_ttl << " * * *\n"; } // Don't print newline after last destination if (d + 1 < dest.size()) { std::cout << std::endl; } } } std::string usage(const char *prog_name) { return "usage: " + std::string(prog_name) + " [46nh] [-f start_ttl] [-m max_ttl] [-p nprobes]\n" " [-z sendwait] [-w waittime] [host...]\n"; } std::string help(const char *prog_name) { return usage(prog_name) + "\n" "Mulroute - multi destination ICMP traceroute. Specify hosts as operands\n" "or write them to the standard input (whitespace separated). Application\n" "uses raw sockets so it needs to be run in a privilidged mode.\n" "\n" "Arguments:\n" " hosts Hosts to traceroute. If not provided, read\n" " them from stdin.\n" "\n" "Options:\n" " -h Show this message and exit\n" " -4 If protocol of a host is unknown use IPv4 (default)\n" " -6 If protocol of a host is unknown use IPv6\n" " -n Do not resolve IP addresses to their domain names\n" " -f start_ttl Start from the start_ttl hop (default is 1)\n" " -m max_ttl Set maximum number of hops (default is 30)\n" " -p nprobes Set the number of probes per each hop (default is 3)\n" " -z sendwait Wait sendwait milliseconds before sending next probe\n" " (default is 10)\n" " -w waittime Wait at least waittime milliseconds for the last probe\n" " response (deafult is 500)\n"; } TraceOptions get_args(int argc, char *const argv[], vector<std::string> &hosts_to_trace) { // Defaults TraceOptions options = {}; options.af_if_unknown = DEF_AF_IN_UNKNOWN; options.probes = DEF_PROBES; options.sendwait = DEF_SENDWAIT; options.waittime = DEF_WAITTIME; options.start_ttl = DEF_START_TTL; options.max_ttl = DEF_MAX_TTL; options.map_ip_to_host = DEF_MAP_IP_TO_HOST; std::string input_file; int opt; opterr = 0; while ((opt = getopt(argc, argv, "46hf:m:np:z:w:")) != -1) { switch (opt) { case '4': options.af_if_unknown = AddressFamily::Inet; break; case '6': options.af_if_unknown = AddressFamily::Inet6; break; case 'f': options.start_ttl = std::stoi(optarg); break; case 'm': options.max_ttl = std::stoi(optarg); break; case 'n': options.map_ip_to_host = false; break; case 'p': options.probes = std::stoi(optarg); break; case 'z': options.sendwait = std::stoi(optarg); break; case 'w': options.waittime = std::stoi(optarg); break; case 'h': std::cout << help(argv[0]); exit(EXIT_SUCCESS); case '?': std::cerr << usage(argv[0]) << "\nFor more info use \"" << argv[0] << " -h\"" << std::endl; exit(EXIT_FAILURE); default: abort(); } } hosts_to_trace.clear(); if (optind < argc) { for (int i = optind; i < argc; ++i) { hosts_to_trace.push_back(argv[i]); } } else { std::string host; while (std::cin >> host) { hosts_to_trace.push_back(host); } } return options; } int main(int argc, char *const argv[]) { vector<std::string> hosts_to_trace; try { TraceOptions options = get_args(argc, argv, hosts_to_trace); TraceResult res = multi_traceroute(hosts_to_trace, options); print_routes(res.probes_info_ip4, res.dest_ip4, options); print_routes(res.probes_info_ip6, res.dest_ip6, options); } catch (const std::exception &e) { std::cerr << "Caught exception: " << e.what() << std::endl; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }<commit_msg>Add validation<commit_after>#include "multi_traceroute.h" #include "net/enums.h" #include <vector> #include <string> #include <iostream> #include <iomanip> #include <chrono> #include <cstdlib> #include <unistd.h> #include <exception> using std::vector; constexpr AddressFamily DEF_AF_IN_UNKNOWN = AddressFamily::Inet; constexpr int DEF_PROBES = 3; constexpr int DEF_SENDWAIT = 10; constexpr int DEF_WAITTIME = 500; constexpr int DEF_START_TTL = 1; constexpr int DEF_MAX_TTL = 30; constexpr bool DEF_MAP_IP_TO_HOST = true; void print_routes(vector<vector<vector<ProbeInfo>>> &probes_info, vector<DestInfo> &dest, TraceOptions options) { // TTLs of last packet that sucessfully returned for each destination vector<int> last_arrived(dest.size(), options.start_ttl - 1); for (size_t d = 0; d < probes_info.size(); ++d) { for (size_t ttl = 0; ttl < probes_info[d].size(); ++ttl) { for (const auto &probe : probes_info[d][ttl]) { if (probe.did_arrive) { last_arrived[d] = ttl + options.start_ttl; } } } } for (size_t d = 0; d < probes_info.size(); ++d) { std::cout << "traceroute to " << dest[d].dest_str << " (" << dest[d].address.get_ip_str() << "), " << options.max_ttl << " hops max\n"; bool dest_reached = false; for (size_t ttl = 0; ttl + options.start_ttl <= last_arrived[d]; ++ttl) { std::cout << std::setw(2) << ttl + options.start_ttl; std::string last_ip = ""; for (size_t p = 0; p < probes_info[d][ttl].size(); ++p) { const ProbeInfo &probe = probes_info[d][ttl][p]; if (!probe.did_arrive) { std::cout << " *"; continue; } std::string ip = probe.offender.get_ip_str(); int rtt = std::chrono::duration_cast<std::chrono::microseconds>(probe.recv_time - probe.send_time).count(); if (ip != last_ip) { if (p != 0) { std::cout << "\n "; } if (options.map_ip_to_host) { std::cout << " " << probe.offender.get_hostname() << " (" << ip << ")"; } else { std::cout << " " << ip; } } std::cout << " " << std::fixed << std::setprecision(3) << static_cast<double>(rtt) / 1000 << " ms"; switch (probe.icmp_status) { case IcmpRespStatus::HostUnreachable: std::cout << " !H"; dest_reached = true; break; case IcmpRespStatus::NetworkUnreachable: std::cout << " !N"; dest_reached = true; break; case IcmpRespStatus::ProtocolUnreachable: std::cout << " !P"; dest_reached = true; break; case IcmpRespStatus::AdminProhibited: std::cout << " !X"; dest_reached = true; break; case IcmpRespStatus::EchoReply: dest_reached = true; break; default: break; } last_ip = ip; } std::cout << std::endl; } /* * Show that the destination wasn't reached * Eg.: * 16 et-17-1.fab1-1-gdc.ne1.yahoo.com (98.138.0.79) 223.473 ms 225.312 ms * 17 po-10.bas1-7-prd.ne1.yahoo.com (98.138.240.6) 225.251 ms 226.105 ms * . * * * * . * * * * 21 * * * */ if (!dest_reached && last_arrived[d] < options.max_ttl) { int dotted = std::min(options.max_ttl - last_arrived[d] - 1, 2); for (int i = 0; i < dotted; ++i) { std::cout << " . * * *\n"; } std::cout << std::setw(2) << options.max_ttl << " * * *\n"; } // Don't print newline after last destination if (d + 1 < dest.size()) { std::cout << std::endl; } } } std::string usage(const char *prog_name) { return "usage: " + std::string(prog_name) + " [46nh] [-f start_ttl] [-m max_ttl] [-p nprobes]\n" " [-z sendwait] [-w waittime] [host...]\n"; } std::string help(const char *prog_name) { return usage(prog_name) + "\n" "Mulroute - multi destination ICMP traceroute. Specify hosts as operands\n" "or write them to the standard input (whitespace separated). Application\n" "uses raw sockets so it needs to be run in a privilidged mode.\n" "\n" "Arguments:\n" " hosts Hosts to traceroute. If not provided, read\n" " them from stdin.\n" "\n" "Options:\n" " -h Show this message and exit\n" " -4 If protocol of a host is unknown use IPv4 (default)\n" " -6 If protocol of a host is unknown use IPv6\n" " -n Do not resolve IP addresses to their domain names\n" " -f start_ttl Start from the start_ttl hop (default is 1)\n" " -m max_ttl Set maximum number of hops (default is 30)\n" " -p nprobes Set the number of probes per each hop (default is 3)\n" " -z sendwait Wait sendwait milliseconds before sending next probe\n" " (default is 10)\n" " -w waittime Wait at least waittime milliseconds for the\n" " last probe response (deafult is 500)\n"; } void validate(TraceOptions options) { switch (options.af_if_unknown) { case AddressFamily::Inet: case AddressFamily::Inet6: break; default: throw std::runtime_error("Address family for \"af_if_unknown\" is corrupted"); } if (options.probes < 1) { throw std::runtime_error("Number of probes (nprobes) must be greater than 0"); } if (options.sendwait < 0) { throw std::runtime_error("sendwait must be at least 0"); } if (options.waittime < 0) { throw std::runtime_error("waittime must be at least 0"); } if (options.start_ttl < 1 || options.start_ttl > 255) { throw std::runtime_error("start_ttl must be a number in range [1, 255]"); } if (options.max_ttl < 1 || options.max_ttl > 255) { throw std::runtime_error("max_ttl must be a number in range [1, 255]"); } if (options.start_ttl > options.max_ttl) { throw std::runtime_error("start_tll must be less than or equal to max_ttl"); } } TraceOptions get_args(int argc, char *const argv[], vector<std::string> &hosts_to_trace) { // Defaults TraceOptions options = {}; options.af_if_unknown = DEF_AF_IN_UNKNOWN; options.probes = DEF_PROBES; options.sendwait = DEF_SENDWAIT; options.waittime = DEF_WAITTIME; options.start_ttl = DEF_START_TTL; options.max_ttl = DEF_MAX_TTL; options.map_ip_to_host = DEF_MAP_IP_TO_HOST; std::string input_file; int opt; opterr = 0; while ((opt = getopt(argc, argv, "46hf:m:np:z:w:")) != -1) { switch (opt) { case '4': options.af_if_unknown = AddressFamily::Inet; break; case '6': options.af_if_unknown = AddressFamily::Inet6; break; case 'f': options.start_ttl = std::stoi(optarg); break; case 'm': options.max_ttl = std::stoi(optarg); break; case 'n': options.map_ip_to_host = false; break; case 'p': options.probes = std::stoi(optarg); break; case 'z': options.sendwait = std::stoi(optarg); break; case 'w': options.waittime = std::stoi(optarg); break; case 'h': std::cout << help(argv[0]); exit(EXIT_SUCCESS); case '?': std::cerr << usage(argv[0]) << "\nFor more info use \"" << argv[0] << " -h\"" << std::endl; exit(EXIT_FAILURE); default: abort(); } } hosts_to_trace.clear(); if (optind < argc) { for (int i = optind; i < argc; ++i) { hosts_to_trace.push_back(argv[i]); } } else { std::string host; while (std::cin >> host) { hosts_to_trace.push_back(host); } } return options; } int main(int argc, char *const argv[]) { vector<std::string> hosts_to_trace; try { TraceOptions options = get_args(argc, argv, hosts_to_trace); validate(options); TraceResult res = multi_traceroute(hosts_to_trace, options); print_routes(res.probes_info_ip4, res.dest_ip4, options); print_routes(res.probes_info_ip6, res.dest_ip6, options); } catch (const std::exception &e) { std::cerr << "Caught exception: " << e.what() << std::endl; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }<|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); for(int i=0;i<8;i++){printf (" %d \n",count[i]);} // make MTL MTL M=make_MTL(G,F); for(int i=0;i<M.priority_list.size();++i){ printf(" priority %d",M.priority_list[i]); } printf(" \n"); assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); printf("Read fiber center positions and compute related things\n"); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; printf("spectrometer has to be identified from 0 to F.Npetal-1\n"); F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("get neighbors of each fiber;\n"); //for each spectrometer, get list of fibers printf("Read plates in order they are to be observed\n "); Plates P_original = read_plate_centers(F); F.Nplate=P_original.size(); printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n"); Plates P; P.resize(F.Nplate);//don't permute plates /* List permut = random_permut(F.Nplate); for (int jj=0; jj<F.Nplate; jj++){ P[jj]=P_original[permut[jj]]; } */ P=P_original printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); //diagnostic for (int j=0;j<F.Nplate;++j){ printf("\n j= %d ",j); for (int p=0;p<10;++p){ printf(" %d ",P[j].SS_as_gal[p].size()); } } // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; printf(" j = %d is next plate\n",j); assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation //assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else printf("done with assign_sf_ss for plate %d\n", j); if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired /* if ( j==1000 || j==4000) { redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); //diagnostic(M,G,F,A); } */ } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",G,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <commit_msg>new diagnostics<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read galaxies Gals G; if(F.Ascii){ G=read_galaxies_ascii(F);} else{ G = read_galaxies(F); } F.Ngal = G.size(); printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str()); std::vector<int> count; count=count_galaxies(G); for(int i=0;i<8;i++){printf (" %d \n",count[i]);} // make MTL MTL M=make_MTL(G,F); for(int i=0;i<M.priority_list.size();++i){ printf(" priority %d",M.priority_list[i]); } printf(" \n"); assign_priority_class(M); //find available SS and SF galaxies on each petal std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ count_class[M[i].priority_class]+=1; } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } printf(" number of MTL galaxies %d\n",M.size()); printf("Read fiber center positions and compute related things\n"); PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; printf("spectrometer has to be identified from 0 to F.Npetal-1\n"); F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); printf("get neighbors of each fiber;\n"); //for each spectrometer, get list of fibers printf("Read plates in order they are to be observed\n "); Plates P_original = read_plate_centers(F); F.Nplate=P_original.size(); printf("This takes the place of Opsim or NextFieldSelector; will be replaced by appropriate code\n"); Plates P; P.resize(F.Nplate);//don't permute plates /* List permut = random_permut(F.Nplate); for (int jj=0; jj<F.Nplate; jj++){ P[jj]=P_original[permut[jj]]; } */ P=P_original; printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); //diagnostic for (int j=0;j<F.Nplate;++j){ printf("\n j= %d ",j); for (int p=0;p<10;++p){ printf(" %d ",P[j].SS_av_gal[p].size()); } } // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf("before assignment\n"); Assignment A(M,F); print_time(t,"# Start assignment at : "); // Make a plan ---------------------------------------------------- //new_assign_fibers(G,P,pp,F,A); // Plans whole survey without sky fibers, standard stars // assumes maximum number of observations needed for QSOs, LRGs printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); simple_assign(M,P,pp,F,A); diagnostic(M,G,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Hist of unused fibs // Want to have even distribution of unused fibers // so we can put in sky fibers and standard stars // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A);// more iterations will improve performance slightly for (int i=0; i<1; i++) { // more iterations will improve performance slightly improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); } for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A); print_hist("Unused fibers",5,histogram(A.unused_fbp(pp,F),5),false); // Still not updated, so all QSO targets have multiple observations etc // Apply and update the plan -------------------------------------- init_time_at(time,"# Begin real time assignment",t); for (int jj=0; jj<F.Nplate; jj++) { int j = A.next_plate; printf(" j = %d is next plate\n",j); assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF just before an observation //assign_unused(j,M,P,pp,F,A); //if (j%2000==0) pyplotTile(j,"doc/figs",G,P,pp,F,A); // Picture of positioners, galaxies //printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl(); // Update corrects all future occurrences of wrong QSOs etc and tries to observe something else printf("done with assign_sf_ss for plate %d\n", j); if (0<=j-F.Analysis) update_plan_from_one_obs(G,M,P,pp,F,A,F.Nplate-1); else printf("\n"); A.next_plate++; // Redistribute and improve on various occasions add more times if desired /* if ( j==1000 || j==4000) { redistribute_tf(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); improve(M,P,pp,F,A); redistribute_tf(M,P,pp,F,A); //diagnostic(M,G,F,A); } */ } print_time(time,"# ... took :"); // Results ------------------------------------------------------- if (F.Output) for (int j=0; j<F.Nplate; j++) write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); // Write output display_results("doc/figs/",G,M,P,pp,F,A,true); if (F.Verif) A.verif(P,M,pp,F); // Verification that the assignment is sane print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>////////////// // Includes // #include <SDL.h> #include <iostream> ////////// // Code // // Entry point! int main() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "Failed to initialize SDL." << std::endl; return 1; } SDL_Window* window = SDL_CreateWindow( "Horizontally Challenged", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN ); if (window == nullptr) { std::cout << "Failed to open an SDL_Window." << std::endl; SDL_Quit(); return 1; } SDL_Delay(2000); SDL_DestroyWindow(window); SDL_Quit(); return 0; } <commit_msg>Made it close better-er<commit_after>////////////// // Includes // #include <SDL.h> #include <iostream> ////////// // Code // // Entry point! int main() { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cout << "Failed to initialize SDL." << std::endl; return 1; } SDL_Window* window = SDL_CreateWindow( "Horizontally Challenged", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_SHOWN ); if (window == nullptr) { std::cout << "Failed to open an SDL_Window." << std::endl; SDL_Quit(); return 1; } SDL_Event e; while (SDL_WaitEvent(&e)) { if (e.type == SDL_QUIT) break; } SDL_DestroyWindow(window); SDL_Quit(); return 0; } <|endoftext|>
<commit_before>// stdc++ #include <iostream> #include <mutex> #include <thread> #include <vector> #include <fstream> #include <future> #define qDebug 1 // mutex_adaptors #include "mutex_adaptors.hpp" /******************************************************************************/ using namespace muads; /******************************************************************************/ using hytex_t = hybrid_adaptor<std::mutex>; using avtex_t = avert_hybrid_adaptor<std::mutex>; /******************************************************************************/ template <typename T> const char* pretty_type(); template <> const char* pretty_type<hytex_t>() { return "hytex_t"; } template <> const char* pretty_type<avtex_t>() { return "avtex_t"; } /******************************************************************************/ inline void probe_log(std::ofstream& out, std::size_t& n_total, std::size_t& n_blocked, bool did_block, tp_diff_t new_p, tp_diff_t new_b) { ++n_total; if (did_block) ++n_blocked; out << static_cast<int>(did_block) << ',' << new_p << ',' << new_b << '\n'; } template <typename Mutex, std::size_t N> void n_slow_probe(bool did_block, tp_diff_t new_p, tp_diff_t new_b) { static std::ofstream out_s(pretty_type<Mutex>() + std::string("_") + std::to_string(N) + "_slow.csv"); static std::size_t n_total_s{0}; static std::size_t n_blocked_s{0}; static bool first_s{false}; if (first_s) { first_s = false; out_s << "blok_phas,time_spin,time_blok\n"; } probe_log(out_s, n_total_s, n_blocked_s, did_block, new_p, new_b); } template <typename Mutex> void n_slow_worker(Mutex& mutex, std::size_t i, std::size_t max) { bool is_slow{i < max}; for (std::size_t i(0); i < 100; ++i) { std::lock_guard<Mutex> lock(mutex); if (is_slow) { static const timespec slow_k{0, 3 * 1000000}; nanosleep(&slow_k, nullptr); } } } template <typename Mutex, std::size_t N> void test_mutex_n_slow() { std::vector<std::future<void>> futures; Mutex mutex; mutex._probe = &n_slow_probe<Mutex, N>; std::cerr << pretty_type<Mutex>() << " " << N << " slow\n"; for (std::size_t i(0); i < 5; ++i) futures.emplace_back(std::async(n_slow_worker<Mutex>, std::ref(mutex), i, N)); } template <typename Mutex> void text_mutex_type() { test_mutex_n_slow<Mutex, 0>(); test_mutex_n_slow<Mutex, 1>(); test_mutex_n_slow<Mutex, 2>(); test_mutex_n_slow<Mutex, 3>(); test_mutex_n_slow<Mutex, 4>(); test_mutex_n_slow<Mutex, 5>(); } int main(int argc, char** argv) { text_mutex_type<hytex_t>(); text_mutex_type<avtex_t>(); } <commit_msg>report headers<commit_after>// stdc++ #include <iostream> #include <mutex> #include <thread> #include <vector> #include <fstream> #include <future> #define qDebug 1 // mutex_adaptors #include "mutex_adaptors.hpp" /******************************************************************************/ using namespace muads; /******************************************************************************/ using hytex_t = hybrid_adaptor<std::mutex>; using avtex_t = avert_hybrid_adaptor<std::mutex>; /******************************************************************************/ template <typename T> const char* pretty_type(); template <> const char* pretty_type<hytex_t>() { return "hytex_t"; } template <> const char* pretty_type<avtex_t>() { return "avtex_t"; } /******************************************************************************/ inline void probe_log(std::ofstream& out, std::size_t& n_total, std::size_t& n_blocked, bool did_block, tp_diff_t new_p, tp_diff_t new_b) { ++n_total; if (did_block) ++n_blocked; out << static_cast<int>(did_block) << ',' << new_p << ',' << new_b << '\n'; } template <typename Mutex, std::size_t N> void n_slow_probe(bool did_block, tp_diff_t new_p, tp_diff_t new_b) { static std::ofstream out_s(pretty_type<Mutex>() + std::string("_") + std::to_string(N) + "_slow.csv"); static std::size_t n_total_s{0}; static std::size_t n_blocked_s{0}; static bool first_s{true}; if (first_s) { first_s = false; out_s << "blok_phas,time_spin,time_blok\n"; } probe_log(out_s, n_total_s, n_blocked_s, did_block, new_p, new_b); } template <typename Mutex> void n_slow_worker(Mutex& mutex, std::size_t i, std::size_t max) { bool is_slow{i < max}; for (std::size_t i(0); i < 100; ++i) { std::lock_guard<Mutex> lock(mutex); if (is_slow) { static const timespec slow_k{0, 3 * 1000000}; nanosleep(&slow_k, nullptr); } } } template <typename Mutex, std::size_t N> void test_mutex_n_slow() { std::vector<std::future<void>> futures; Mutex mutex; mutex._probe = &n_slow_probe<Mutex, N>; std::cerr << pretty_type<Mutex>() << " " << N << " slow\n"; for (std::size_t i(0); i < 5; ++i) futures.emplace_back(std::async(n_slow_worker<Mutex>, std::ref(mutex), i, N)); } template <typename Mutex> void text_mutex_type() { test_mutex_n_slow<Mutex, 0>(); test_mutex_n_slow<Mutex, 1>(); test_mutex_n_slow<Mutex, 2>(); test_mutex_n_slow<Mutex, 3>(); test_mutex_n_slow<Mutex, 4>(); test_mutex_n_slow<Mutex, 5>(); } int main(int argc, char** argv) { text_mutex_type<hytex_t>(); text_mutex_type<avtex_t>(); } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <atomic> #include <chrono> #include <iostream> #include "dll/rbm/rbm.hpp" #include "dll/dbn.hpp" #include "dll/neural/dense_layer.hpp" #include "dll/trainer/stochastic_gradient_descent.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" namespace { constexpr const size_t K = 3; template <typename C> float distance_knn(const C& lhs, const C& rhs) { return etl::sum((lhs - rhs) >> (lhs - rhs)); } struct distance_t { float dist; uint32_t label; }; size_t vote_knn(const std::vector<distance_t>& distances) { size_t votes[10]{}; for (size_t k = 0; k < K; ++k) { ++votes[distances[k].label]; } size_t label = 0; for (size_t k = 1; k < 10; ++k) { if (votes[k] > votes[label]) { label = k; } } return label; } template <typename C, typename L> double evaluate_knn(const C& training, const C& test, const L& training_labels, const L& test_labels) { std::atomic<size_t> correct; correct = 0; cpp::default_thread_pool<> pool(8); cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) { std::vector<distance_t> distances(training.size()); for (size_t j = 0; j < training.size(); ++j) { float d = distance_knn(test[i], training[j]); distances[j] = {d, training_labels[j]}; } std::sort(distances.begin(), distances.end(), [](const distance_t& lhs, const distance_t& rhs) { return lhs.dist < rhs.dist; }); if (vote_knn(distances) == test_labels[i]) { ++correct; } }); return correct / double(test.size()); } template <size_t I, typename N, typename D> double evaluate_knn_net(const N& net, const D& dataset) { std::vector<etl::dyn_vector<float>> training(dataset.training_images.size()); std::vector<etl::dyn_vector<float>> test(dataset.test_images.size()); cpp::default_thread_pool<> pool(8); cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) { training[i] = net->template features_sub<I>(dataset.training_images[i]); }); cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) { test[i] = net->template features_sub<I>(dataset.test_images[i]); }); return evaluate_knn(training, test, dataset.training_labels, dataset.test_labels); } template <typename R, typename D> double evaluate_knn_rbm(const R& rbm, const D& dataset) { std::vector<etl::dyn_vector<float>> training(dataset.training_images.size()); std::vector<etl::dyn_vector<float>> test(dataset.test_images.size()); cpp::default_thread_pool<> pool(8); cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) { training[i] = rbm->features(dataset.training_images[i]); }); cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) { test[i] = rbm->features(dataset.test_images[i]); }); return evaluate_knn(training, test, dataset.training_labels, dataset.test_labels); } } // end of anonymous int main(int argc, char* argv[]) { std::string model = "raw"; if (argc > 1) { model = argv[1]; } auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_vector<float>>(); if (model == "raw") { double accuracy = evaluate_knn(dataset.training_images, dataset.test_images, dataset.training_labels, dataset.test_labels); std::cout << "Raw: " << accuracy << std::endl; } else if (model == "dense") { mnist::binarize_dataset(dataset); static constexpr size_t epochs = 100; static constexpr size_t batch_size = 100; #define SINGLE_RBM(N) \ { \ using rbm_t = dll::rbm_desc< \ 28 * 28, N, \ dll::batch_size<batch_size>, \ dll::momentum>::layer_t; \ auto rbm = std::make_unique<rbm_t>(); \ rbm->learning_rate = 0.1; \ rbm->initial_momentum = 0.9; \ rbm->final_momentum = 0.9; \ auto error = rbm->train(dataset.training_images, epochs); \ std::cout << "pretrain_error:" << error << std::endl; \ std::cout << "__result__: dense_rbm_" << N << ":" \ << evaluate_knn_rbm(rbm, dataset) << std::endl; \ } #define SINGLE_AE(N) \ { \ using network_t = \ dll::dbn_desc<dll::dbn_layers<dll::dense_desc<28 * 28, N>::layer_t, \ dll::dense_desc<N, 28 * 28>::layer_t>, \ dll::momentum, dll::trainer<dll::sgd_trainer>, \ dll::batch_size<batch_size>>::dbn_t; \ auto ae = std::make_unique<network_t>(); \ ae->learning_rate = 0.1; \ ae->initial_momentum = 0.9; \ ae->final_momentum = 0.9; \ auto ft_error = ae->fine_tune_ae(dataset.training_images, epochs); \ std::cout << "ft_error:" << ft_error << std::endl; \ std::cout << "__result__: dense_ae_" << N << ":" \ << evaluate_knn_net<1>(ae, dataset) << std::endl; \ } SINGLE_RBM(100); SINGLE_RBM(200); SINGLE_RBM(400); SINGLE_RBM(600); SINGLE_RBM(800); SINGLE_RBM(1000); SINGLE_AE(100); SINGLE_AE(200); SINGLE_AE(400); SINGLE_AE(600); SINGLE_AE(800); SINGLE_AE(1000); } return 0; } <commit_msg>Test smaller layers<commit_after>//======================================================================= // Copyright (c) 2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <atomic> #include <chrono> #include <iostream> #include "dll/rbm/rbm.hpp" #include "dll/dbn.hpp" #include "dll/neural/dense_layer.hpp" #include "dll/trainer/stochastic_gradient_descent.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" namespace { constexpr const size_t K = 3; template <typename C> float distance_knn(const C& lhs, const C& rhs) { return etl::sum((lhs - rhs) >> (lhs - rhs)); } struct distance_t { float dist; uint32_t label; }; size_t vote_knn(const std::vector<distance_t>& distances) { size_t votes[10]{}; for (size_t k = 0; k < K; ++k) { ++votes[distances[k].label]; } size_t label = 0; for (size_t k = 1; k < 10; ++k) { if (votes[k] > votes[label]) { label = k; } } return label; } template <typename C, typename L> double evaluate_knn(const C& training, const C& test, const L& training_labels, const L& test_labels) { std::atomic<size_t> correct; correct = 0; cpp::default_thread_pool<> pool(8); cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) { std::vector<distance_t> distances(training.size()); for (size_t j = 0; j < training.size(); ++j) { float d = distance_knn(test[i], training[j]); distances[j] = {d, training_labels[j]}; } std::sort(distances.begin(), distances.end(), [](const distance_t& lhs, const distance_t& rhs) { return lhs.dist < rhs.dist; }); if (vote_knn(distances) == test_labels[i]) { ++correct; } }); return correct / double(test.size()); } template <size_t I, typename N, typename D> double evaluate_knn_net(const N& net, const D& dataset) { std::vector<etl::dyn_vector<float>> training(dataset.training_images.size()); std::vector<etl::dyn_vector<float>> test(dataset.test_images.size()); cpp::default_thread_pool<> pool(8); cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) { training[i] = net->template features_sub<I>(dataset.training_images[i]); }); cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) { test[i] = net->template features_sub<I>(dataset.test_images[i]); }); return evaluate_knn(training, test, dataset.training_labels, dataset.test_labels); } template <typename R, typename D> double evaluate_knn_rbm(const R& rbm, const D& dataset) { std::vector<etl::dyn_vector<float>> training(dataset.training_images.size()); std::vector<etl::dyn_vector<float>> test(dataset.test_images.size()); cpp::default_thread_pool<> pool(8); cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) { training[i] = rbm->features(dataset.training_images[i]); }); cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) { test[i] = rbm->features(dataset.test_images[i]); }); return evaluate_knn(training, test, dataset.training_labels, dataset.test_labels); } } // end of anonymous int main(int argc, char* argv[]) { std::string model = "raw"; if (argc > 1) { model = argv[1]; } auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_vector<float>>(); if (model == "raw") { double accuracy = evaluate_knn(dataset.training_images, dataset.test_images, dataset.training_labels, dataset.test_labels); std::cout << "Raw: " << accuracy << std::endl; } else if (model == "dense") { mnist::binarize_dataset(dataset); static constexpr size_t epochs = 100; static constexpr size_t batch_size = 100; #define SINGLE_RBM(N) \ { \ using rbm_t = dll::rbm_desc< \ 28 * 28, N, \ dll::batch_size<batch_size>, \ dll::momentum>::layer_t; \ auto rbm = std::make_unique<rbm_t>(); \ rbm->learning_rate = 0.1; \ rbm->initial_momentum = 0.9; \ rbm->final_momentum = 0.9; \ auto error = rbm->train(dataset.training_images, epochs); \ std::cout << "pretrain_error:" << error << std::endl; \ std::cout << "__result__: dense_rbm_" << N << ":" \ << evaluate_knn_rbm(rbm, dataset) << std::endl; \ } #define SINGLE_AE(N) \ { \ using network_t = \ dll::dbn_desc<dll::dbn_layers<dll::dense_desc<28 * 28, N>::layer_t, \ dll::dense_desc<N, 28 * 28>::layer_t>, \ dll::momentum, dll::trainer<dll::sgd_trainer>, \ dll::batch_size<batch_size>>::dbn_t; \ auto ae = std::make_unique<network_t>(); \ ae->learning_rate = 0.1; \ ae->initial_momentum = 0.9; \ ae->final_momentum = 0.9; \ auto ft_error = ae->fine_tune_ae(dataset.training_images, epochs); \ std::cout << "ft_error:" << ft_error << std::endl; \ std::cout << "__result__: dense_ae_" << N << ":" \ << evaluate_knn_net<1>(ae, dataset) << std::endl; \ } SINGLE_RBM(50); SINGLE_RBM(100); SINGLE_RBM(200); SINGLE_RBM(400); SINGLE_RBM(600); SINGLE_RBM(800); SINGLE_RBM(1000); SINGLE_AE(50); SINGLE_AE(100); SINGLE_AE(200); SINGLE_AE(400); SINGLE_AE(600); SINGLE_AE(800); SINGLE_AE(1000); } return 0; } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh_builder_hair.h" #include "bvh_builder_hair_old.h" #include "../builders/primrefgen.h" #include "../geometry/bezier1v.h" #include "../geometry/bezier1i.h" #if defined(EMBREE_GEOMETRY_HAIR) namespace embree { namespace isa { template<int N, typename Primitive> struct BVHNHairBuilderSAH : public Builder { typedef BVHN<N> BVH; typedef typename BVH::AlignedNode AlignedNode; typedef typename BVH::UnalignedNode UnalignedNode; typedef typename BVH::NodeRef NodeRef; typedef HeuristicArrayBinningSAH<BezierPrim,NUM_OBJECT_BINS> HeuristicBinningSAH; BVH* bvh; Scene* scene; mvector<BezierPrim> prims; BVHNHairBuilderSAH (BVH* bvh, Scene* scene) : bvh(bvh), scene(scene), prims(scene->device) {} void build(size_t, size_t) { /* progress monitor */ auto progress = [&] (size_t dn) { bvh->scene->progressMonitor(double(dn)); }; auto virtualprogress = BuildProgressMonitorFromClosure(progress); /* fast path for empty BVH */ const size_t numPrimitives = scene->getNumPrimitives<BezierCurves,false>(); if (numPrimitives == 0) { prims.clear(); bvh->set(BVH::emptyNode,empty,0); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH" + toString(N) + "BuilderHairSAH"); //profile(1,5,numPrimitives,[&] (ProfileTimer& timer) { /* create primref array */ bvh->alloc.init_estimate(numPrimitives*sizeof(Primitive)); prims.resize(numPrimitives); const PrimInfo pinfo = createBezierRefArray(scene,prims,virtualprogress); /* builder settings */ BVHNBuilderHair::Settings settings; settings.branchingFactor = N; settings.maxDepth = BVH::maxBuildDepthLeaf; settings.logBlockSize = 0; settings.minLeafSize = 1; settings.maxLeafSize = BVH::maxLeafBlocks; /* build hierarchy */ typename BVH::NodeRef root = BVHNBuilderHair::build<N> ( typename BVH::CreateAlloc(bvh), typename BVH::AlignedNode::Create(), typename BVH::AlignedNode::Set(), typename BVH::UnalignedNode::Create(), typename BVH::UnalignedNode::Set(), [&] (size_t depth, const PrimInfo& pinfo, FastAllocator::ThreadLocal2* alloc) -> NodeRef { size_t items = pinfo.size(); size_t start = pinfo.begin; Primitive* accel = (Primitive*) alloc->alloc1->malloc(items*sizeof(Primitive)); NodeRef node = bvh->encodeLeaf((char*)accel,items); for (size_t i=0; i<items; i++) { accel[i].fill(prims.data(),start,pinfo.end,bvh->scene); } return node; }, progress, prims.data(),pinfo,settings); bvh->set(root,LBBox3fa(pinfo.geomBounds),pinfo.size()); //}); /* clear temporary data for static geometry */ if (scene->isStatic()) { prims.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims.clear(); } }; template<int N, typename Primitive> struct BVHNHairMBBuilderSAH : public Builder { typedef BVHN<N> BVH; typedef typename BVH::AlignedNodeMB AlignedNodeMB; typedef typename BVH::UnalignedNodeMB UnalignedNodeMB; typedef typename BVH::NodeRef NodeRef; typedef HeuristicArrayBinningSAH<BezierPrim,NUM_OBJECT_BINS> HeuristicBinningSAH; BVH* bvh; Scene* scene; mvector<BezierPrim> prims; BVHNHairMBBuilderSAH (BVH* bvh, Scene* scene) : bvh(bvh), scene(scene), prims(scene->device) {} void build(size_t, size_t) { /* progress monitor */ auto progress = [&] (size_t dn) { bvh->scene->progressMonitor(double(dn)); }; auto virtualprogress = BuildProgressMonitorFromClosure(progress); /* fast path for empty BVH */ const size_t numPrimitives = scene->getNumPrimitives<BezierCurves,true>(); if (numPrimitives == 0) { prims.clear(); bvh->set(BVH::emptyNode,empty,0); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH" + toString(N) + "BuilderMBHairSAH"); //profile(1,5,numPrimitives,[&] (ProfileTimer& timer) { /* create primref array */ bvh->numTimeSteps = scene->getNumTimeSteps<BezierCurves,true>(); const size_t numTimeSegments = bvh->numTimeSteps-1; assert(bvh->numTimeSteps > 1); prims.resize(numPrimitives); bvh->alloc.init_estimate(numPrimitives*sizeof(Primitive)*numTimeSegments); NodeRef* roots = (NodeRef*) bvh->alloc.threadLocal()->malloc(sizeof(NodeRef)*numTimeSegments,BVH::byteNodeAlignment); /* build BVH for each timestep */ avector<BBox3fa> bounds(bvh->numTimeSteps); size_t num_bvh_primitives = 0; for (size_t t=0; t<numTimeSegments; t++) { /* call BVH builder */ const PrimInfo pinfo = createBezierRefArrayMBlur(t,bvh->numTimeSteps,scene,prims,virtualprogress); const LBBox3fa lbbox = HeuristicBinningSAH(prims.begin()).computePrimInfoMB(t,bvh->numTimeSteps,scene,pinfo); NodeRef root = bvh_obb_builder_binned_sah<N> ( [&] () { return bvh->alloc.threadLocal2(); }, [&] (const PrimInfo* children, const size_t numChildren, HeuristicBinningSAH alignedHeuristic, FastAllocator::ThreadLocal2* alloc) -> AlignedNodeMB* { AlignedNodeMB* node = (AlignedNodeMB*) alloc->alloc0->malloc(sizeof(AlignedNodeMB),BVH::byteNodeAlignment); node->clear(); for (size_t i=0; i<numChildren; i++) { LBBox3fa bounds = alignedHeuristic.computePrimInfoMB(t,bvh->numTimeSteps,scene,children[i]); node->set(i,bounds); } return node; }, [&] (const PrimInfo* children, const size_t numChildren, UnalignedHeuristicArrayBinningSAH<BezierPrim,NUM_OBJECT_BINS> unalignedHeuristic, FastAllocator::ThreadLocal2* alloc) -> UnalignedNodeMB* { UnalignedNodeMB* node = (UnalignedNodeMB*) alloc->alloc0->malloc(sizeof(UnalignedNodeMB),BVH::byteNodeAlignment); node->clear(); for (size_t i=0; i<numChildren; i++) { const AffineSpace3fa space = unalignedHeuristic.computeAlignedSpaceMB(scene,children[i]); UnalignedHeuristicArrayBinningSAH<BezierPrim,NUM_OBJECT_BINS>::PrimInfoMB pinfo = unalignedHeuristic.computePrimInfoMB(t,bvh->numTimeSteps,scene,children[i],space); node->set(i,space,pinfo.s0t0,pinfo.s1t1); } return node; }, [&] (size_t depth, const PrimInfo& pinfo, FastAllocator::ThreadLocal2* alloc) -> NodeRef { size_t items = pinfo.size(); size_t start = pinfo.begin; Primitive* accel = (Primitive*) alloc->alloc1->malloc(items*sizeof(Primitive)); NodeRef node = bvh->encodeLeaf((char*)accel,items); for (size_t i=0; i<items; i++) { accel[i].fill(prims.data(),start,pinfo.end,bvh->scene); } return node; }, progress, prims.data(),pinfo,N,BVH::maxBuildDepthLeaf,1,1,BVH::maxLeafBlocks); roots[t] = root; bounds[t+0] = lbbox.bounds0; bounds[t+1] = lbbox.bounds1; num_bvh_primitives = max(num_bvh_primitives,pinfo.size()); } bvh->set(NodeRef((size_t)roots),LBBox3fa(bounds),num_bvh_primitives); bvh->msmblur = true; //}); /* clear temporary data for static geometry */ if (scene->isStatic()) { prims.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims.clear(); } }; /*! entry functions for the builder */ Builder* BVH4Bezier1vBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairBuilderSAH<4,Bezier1v>((BVH4*)bvh,scene); } Builder* BVH4Bezier1iBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairBuilderSAH<4,Bezier1i>((BVH4*)bvh,scene); } Builder* BVH4Bezier1iMBBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairMBBuilderSAH<4,Bezier1i>((BVH4*)bvh,scene); } #if defined(__AVX__) Builder* BVH8Bezier1vBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairBuilderSAH<8,Bezier1v>((BVH8*)bvh,scene); } Builder* BVH8Bezier1iBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairBuilderSAH<8,Bezier1i>((BVH8*)bvh,scene); } Builder* BVH8Bezier1iMBBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairMBBuilderSAH<8,Bezier1i>((BVH8*)bvh,scene); } #endif } } #endif <commit_msg>cleanups to hair builder<commit_after>// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh_builder_hair.h" #include "bvh_builder_hair_old.h" #include "../builders/primrefgen.h" #include "../geometry/bezier1v.h" #include "../geometry/bezier1i.h" #if defined(EMBREE_GEOMETRY_HAIR) namespace embree { namespace isa { template<int N, typename Primitive> struct BVHNHairBuilderSAH : public Builder { typedef BVHN<N> BVH; typedef typename BVH::AlignedNode AlignedNode; typedef typename BVH::UnalignedNode UnalignedNode; typedef typename BVH::NodeRef NodeRef; typedef HeuristicArrayBinningSAH<BezierPrim,NUM_OBJECT_BINS> HeuristicBinningSAH; BVH* bvh; Scene* scene; mvector<BezierPrim> prims; BVHNHairBuilderSAH (BVH* bvh, Scene* scene) : bvh(bvh), scene(scene), prims(scene->device) {} void build(size_t, size_t) { /* fast path for empty BVH */ const size_t numPrimitives = scene->getNumPrimitives<BezierCurves,false>(); if (numPrimitives == 0) { prims.clear(); bvh->set(BVH::emptyNode,empty,0); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH" + toString(N) + "BuilderHairSAH"); //profile(1,5,numPrimitives,[&] (ProfileTimer& timer) { /* create primref array */ bvh->alloc.init_estimate(numPrimitives*sizeof(Primitive)); prims.resize(numPrimitives); const PrimInfo pinfo = createBezierRefArray(scene,prims,scene->progressInterface); /* builder settings */ BVHNBuilderHair::Settings settings; settings.branchingFactor = N; settings.maxDepth = BVH::maxBuildDepthLeaf; settings.logBlockSize = 0; settings.minLeafSize = 1; settings.maxLeafSize = BVH::maxLeafBlocks; /* creates a leaf node */ auto createLeaf = [&] (size_t depth, const PrimInfo& pinfo, FastAllocator::ThreadLocal2* alloc) -> NodeRef { size_t start = pinfo.begin; size_t items = pinfo.size(); Primitive* accel = (Primitive*) alloc->alloc1->malloc(items*sizeof(Primitive)); for (size_t i=0; i<items; i++) { accel[i].fill(prims.data(),start,pinfo.end,bvh->scene); } return bvh->encodeLeaf((char*)accel,items); }; /* build hierarchy */ typename BVH::NodeRef root = BVHNBuilderHair::build<N> ( typename BVH::CreateAlloc(bvh), typename BVH::AlignedNode::Create(), typename BVH::AlignedNode::Set(), typename BVH::UnalignedNode::Create(), typename BVH::UnalignedNode::Set(), createLeaf,scene->progressInterface,prims.data(),pinfo,settings); bvh->set(root,LBBox3fa(pinfo.geomBounds),pinfo.size()); //}); /* clear temporary data for static geometry */ if (scene->isStatic()) { prims.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims.clear(); } }; template<int N, typename Primitive> struct BVHNHairMBBuilderSAH : public Builder { typedef BVHN<N> BVH; typedef typename BVH::AlignedNodeMB AlignedNodeMB; typedef typename BVH::UnalignedNodeMB UnalignedNodeMB; typedef typename BVH::NodeRef NodeRef; typedef HeuristicArrayBinningSAH<BezierPrim,NUM_OBJECT_BINS> HeuristicBinningSAH; BVH* bvh; Scene* scene; mvector<BezierPrim> prims; BVHNHairMBBuilderSAH (BVH* bvh, Scene* scene) : bvh(bvh), scene(scene), prims(scene->device) {} void build(size_t, size_t) { /* progress monitor */ auto progress = [&] (size_t dn) { bvh->scene->progressMonitor(double(dn)); }; auto virtualprogress = BuildProgressMonitorFromClosure(progress); /* fast path for empty BVH */ const size_t numPrimitives = scene->getNumPrimitives<BezierCurves,true>(); if (numPrimitives == 0) { prims.clear(); bvh->set(BVH::emptyNode,empty,0); return; } double t0 = bvh->preBuild(TOSTRING(isa) "::BVH" + toString(N) + "BuilderMBHairSAH"); //profile(1,5,numPrimitives,[&] (ProfileTimer& timer) { /* create primref array */ bvh->numTimeSteps = scene->getNumTimeSteps<BezierCurves,true>(); const size_t numTimeSegments = bvh->numTimeSteps-1; assert(bvh->numTimeSteps > 1); prims.resize(numPrimitives); bvh->alloc.init_estimate(numPrimitives*sizeof(Primitive)*numTimeSegments); NodeRef* roots = (NodeRef*) bvh->alloc.threadLocal()->malloc(sizeof(NodeRef)*numTimeSegments,BVH::byteNodeAlignment); /* build BVH for each timestep */ avector<BBox3fa> bounds(bvh->numTimeSteps); size_t num_bvh_primitives = 0; for (size_t t=0; t<numTimeSegments; t++) { /* call BVH builder */ const PrimInfo pinfo = createBezierRefArrayMBlur(t,bvh->numTimeSteps,scene,prims,virtualprogress); const LBBox3fa lbbox = HeuristicBinningSAH(prims.begin()).computePrimInfoMB(t,bvh->numTimeSteps,scene,pinfo); NodeRef root = bvh_obb_builder_binned_sah<N> ( [&] () { return bvh->alloc.threadLocal2(); }, [&] (const PrimInfo* children, const size_t numChildren, HeuristicBinningSAH alignedHeuristic, FastAllocator::ThreadLocal2* alloc) -> AlignedNodeMB* { AlignedNodeMB* node = (AlignedNodeMB*) alloc->alloc0->malloc(sizeof(AlignedNodeMB),BVH::byteNodeAlignment); node->clear(); for (size_t i=0; i<numChildren; i++) { LBBox3fa bounds = alignedHeuristic.computePrimInfoMB(t,bvh->numTimeSteps,scene,children[i]); node->set(i,bounds); } return node; }, [&] (const PrimInfo* children, const size_t numChildren, UnalignedHeuristicArrayBinningSAH<BezierPrim,NUM_OBJECT_BINS> unalignedHeuristic, FastAllocator::ThreadLocal2* alloc) -> UnalignedNodeMB* { UnalignedNodeMB* node = (UnalignedNodeMB*) alloc->alloc0->malloc(sizeof(UnalignedNodeMB),BVH::byteNodeAlignment); node->clear(); for (size_t i=0; i<numChildren; i++) { const AffineSpace3fa space = unalignedHeuristic.computeAlignedSpaceMB(scene,children[i]); UnalignedHeuristicArrayBinningSAH<BezierPrim,NUM_OBJECT_BINS>::PrimInfoMB pinfo = unalignedHeuristic.computePrimInfoMB(t,bvh->numTimeSteps,scene,children[i],space); node->set(i,space,pinfo.s0t0,pinfo.s1t1); } return node; }, [&] (size_t depth, const PrimInfo& pinfo, FastAllocator::ThreadLocal2* alloc) -> NodeRef { size_t items = pinfo.size(); size_t start = pinfo.begin; Primitive* accel = (Primitive*) alloc->alloc1->malloc(items*sizeof(Primitive)); NodeRef node = bvh->encodeLeaf((char*)accel,items); for (size_t i=0; i<items; i++) { accel[i].fill(prims.data(),start,pinfo.end,bvh->scene); } return node; }, progress, prims.data(),pinfo,N,BVH::maxBuildDepthLeaf,1,1,BVH::maxLeafBlocks); roots[t] = root; bounds[t+0] = lbbox.bounds0; bounds[t+1] = lbbox.bounds1; num_bvh_primitives = max(num_bvh_primitives,pinfo.size()); } bvh->set(NodeRef((size_t)roots),LBBox3fa(bounds),num_bvh_primitives); bvh->msmblur = true; //}); /* clear temporary data for static geometry */ if (scene->isStatic()) { prims.clear(); bvh->shrink(); } bvh->cleanup(); bvh->postBuild(t0); } void clear() { prims.clear(); } }; /*! entry functions for the builder */ Builder* BVH4Bezier1vBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairBuilderSAH<4,Bezier1v>((BVH4*)bvh,scene); } Builder* BVH4Bezier1iBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairBuilderSAH<4,Bezier1i>((BVH4*)bvh,scene); } Builder* BVH4Bezier1iMBBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairMBBuilderSAH<4,Bezier1i>((BVH4*)bvh,scene); } #if defined(__AVX__) Builder* BVH8Bezier1vBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairBuilderSAH<8,Bezier1v>((BVH8*)bvh,scene); } Builder* BVH8Bezier1iBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairBuilderSAH<8,Bezier1i>((BVH8*)bvh,scene); } Builder* BVH8Bezier1iMBBuilder_OBB_New (void* bvh, Scene* scene, size_t mode) { return new BVHNHairMBBuilderSAH<8,Bezier1i>((BVH8*)bvh,scene); } #endif } } #endif <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // name: ofck.cpp // desc: openframeworks <=> ChucK bridge // // @author Ge Wang // @author Tim O'Brien // @author Kitty Shi // @author Madeline Huberth // // @date Fall 2015 //------------------------------------------------------------------------------ #include "ofck.h" #include "chuck_dl.h" #include "chuck_def.h" // general includes #include <stdio.h> #include <limits.h> // declaration of chugin constructor CK_DLL_CTOR(ofck_ctor); // declaration of chugin desctructor CK_DLL_DTOR(ofck_dtor); // VREntity CK_DLL_SFUN(vrentity_location); CK_DLL_SFUN(vrentity_rotation); CK_DLL_SFUN(vrentity_scaling); CK_DLL_SFUN(vrentity_rgb); CK_DLL_SFUN(vrentity_rgba); CK_DLL_SFUN(vrentity_addEntity); CK_DLL_SFUN(vrentity_removeEntity); // VR CK_DLL_SFUN(vr_object); CK_DLL_SFUN(vr_setInt); CK_DLL_SFUN(vr_getInt); CK_DLL_SFUN(vr_setFloat); CK_DLL_SFUN(vr_getFloat); CK_DLL_SFUN(vr_setString); CK_DLL_SFUN(vr_getString); CK_DLL_SFUN(vr_setVec3); CK_DLL_SFUN(vr_getVec3); CK_DLL_SFUN(vr_setVec4); CK_DLL_SFUN(vr_getVec4); CK_DLL_SFUN(vr_displaySync); // this is a special offset reserved for Chugin internal data t_CKINT ofck_data_offset = 0; // defintion class VREntity { public: // constructor VREntity( t_CKFLOAT fs) { m_param = 0; } // set parameter example float setParam( t_CKFLOAT p ) { m_param = p; return p; } // get parameter example float getParam() { return m_param; } private: // instance data float m_param; }; // query function: chuck calls this when loading the Chugin // NOTE: developer will need to modify this function to // add additional functions to this Chugin DLL_QUERY ofck_query( Chuck_DL_Query * QUERY ) { // hmm, don't change this... QUERY->setname(QUERY, "VR"); // begin the class definition QUERY->begin_class(QUERY, "VREntity", "Object"); { // vec3 VREntity.location() QUERY->add_sfun(QUERY, vrentity_location, "vec3", "location"); // vec3 VREntity.rotation() QUERY->add_sfun(QUERY, vrentity_rotation, "vec3", "rotation"); // vec3 VREntity.scaling() QUERY->add_sfun(QUERY, vrentity_scaling, "vec3", "scaling"); // vec3 VREntity.rgb() QUERY->add_sfun(QUERY, vrentity_rgb, "vec3", "rgb"); // vec4 VREntity.rgb() QUERY->add_sfun(QUERY, vrentity_rgba, "vec4", "rgba"); } // end the class definition QUERY->end_class(QUERY); // begin the class definition QUERY->begin_class(QUERY, "VR", "Object"); { // VRObject VR.object(name) // retrive objects QUERY->add_sfun(QUERY, vr_object, "VRObject", "object"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "name"); // int VR.setInt(key,value) // set QUERY->add_sfun(QUERY, vr_setInt, "int", "setInt"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "int", "value"); // float VR.setFloat(key,value) // set QUERY->add_sfun(QUERY, vr_getInt, "int", "getInt"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // float VR.setFloat(key,value) // set QUERY->add_sfun(QUERY, vr_setFloat, "float", "setFloat"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "int", "value"); // float VR.getFloat(key,value) // set QUERY->add_sfun(QUERY, vr_getFloat, "float", "getFloat"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // float VR.setString(key,value) // set QUERY->add_sfun(QUERY, vr_setFloat, "string", "setString"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "value"); // string VR.getString(key,value) // set QUERY->add_sfun(QUERY, vr_getString, "string", "getString"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // vec3 VR.setVec3(key,value) // set QUERY->add_sfun(QUERY, vr_setVec3, "vec3", "setVec3"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "vec3", "value"); // vec3 VR.getVec3(key,value) // set QUERY->add_sfun(QUERY, vr_getString, "vec3", "getVec3"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // vec4 VR.setVec4(key,value) // set QUERY->add_sfun(QUERY, vr_setVec4, "vec4", "setVec4"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "vec4", "value"); // vec4 VR.getVec4(key,value) // set QUERY->add_sfun(QUERY, vr_getString, "vec4", "getVec4"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // Event VR.displaySync // event for display QUERY->add_sfun(QUERY, vr_object, "Event", "displaySync"); } // end the class definition QUERY->end_class(QUERY); // wasn't that a breeze? return TRUE; } // implementation for the constructor CK_DLL_CTOR(ofck_ctor) { // get the offset where we'll store our internal c++ class pointer OBJ_MEMBER_INT(SELF, ofck_data_offset) = 0; // instantiate our internal c++ class representation ofck * o_obj = new ofck(API->vm->get_srate()); // store the pointer in the ChucK object member OBJ_MEMBER_INT(SELF, ofck_data_offset) = (t_CKINT) o_obj; } // implementation for the destructor CK_DLL_DTOR(ofck_dtor) { // get our c++ class pointer ofck * o_obj = (ofck *) OBJ_MEMBER_INT(SELF, ofck_data_offset); // check it if( o_obj ) { // clean up delete o_obj; OBJ_MEMBER_INT(SELF, ofck_data_offset) = 0; o_obj = NULL; } } // example implementation for setter CK_DLL_MFUN(ofck_setParam) { // get our c++ class pointer ofck * o_obj = (ofck *) OBJ_MEMBER_INT(SELF, ofck_data_offset); // set the return value RETURN->v_float = o_obj->setParam(GET_NEXT_FLOAT(ARGS)); } // example implementation for getter CK_DLL_MFUN(ofck_getParam) { // get our c++ class pointer ofck * o_obj = (ofck *) OBJ_MEMBER_INT(SELF, ofck_data_offset); // set the return value RETURN->v_float = o_obj->getParam(); } <commit_msg>functions renamed get/set<commit_after>//------------------------------------------------------------------------------ // name: ofck.cpp // desc: openframeworks <=> ChucK bridge // // @author Ge Wang // @author Tim O'Brien // @author Kitty Shi // @author Madeline Huberth // // @date Fall 2015 //------------------------------------------------------------------------------ #include "ofck.h" #include "chuck_dl.h" #include "chuck_def.h" // general includes #include <stdio.h> #include <limits.h> // declaration of chugin constructor CK_DLL_CTOR(ofck_ctor); // declaration of chugin desctructor CK_DLL_DTOR(ofck_dtor); // VREntity CK_DLL_SFUN(vrentity_getLocation); CK_DLL_SFUN(vrentity_setLocation); CK_DLL_SFUN(vrentity_getRotation); CK_DLL_SFUN(vrentity_setRotation); CK_DLL_SFUN(vrentity_getScaling); CK_DLL_SFUN(vrentity_setScaling); CK_DLL_SFUN(vrentity_getRGB); CK_DLL_SFUN(vrentity_setRGB); CK_DLL_SFUN(vrentity_getRGBA); CK_DLL_SFUN(vrentity_setRGBA); CK_DLL_SFUN(vrentity_addEntity); CK_DLL_SFUN(vrentity_removeEntity); // VR CK_DLL_SFUN(vr_object); CK_DLL_SFUN(vr_setInt); CK_DLL_SFUN(vr_getInt); CK_DLL_SFUN(vr_setFloat); CK_DLL_SFUN(vr_getFloat); CK_DLL_SFUN(vr_setString); CK_DLL_SFUN(vr_getString); CK_DLL_SFUN(vr_setVec3); CK_DLL_SFUN(vr_getVec3); CK_DLL_SFUN(vr_setVec4); CK_DLL_SFUN(vr_getVec4); CK_DLL_SFUN(vr_displaySync); // this is a special offset reserved for Chugin internal data t_CKINT ofck_data_offset = 0; // defintion class VREntity { public: // constructor VREntity( t_CKFLOAT fs) { m_param = 0; } // set parameter example float setParam( t_CKFLOAT p ) { m_param = p; return p; } // get parameter example float getParam() { return m_param; } private: // instance data float m_param; }; // query function: chuck calls this when loading the Chugin // NOTE: developer will need to modify this function to // add additional functions to this Chugin DLL_QUERY ofck_query( Chuck_DL_Query * QUERY ) { // hmm, don't change this... QUERY->setname(QUERY, "VR"); // begin the class definition QUERY->begin_class(QUERY, "VREntity", "Object"); { // vec3 VREntity.location() QUERY->add_sfun(QUERY, vrentity_getLocation, "vec3", "location"); QUERY->add_sfun(QUERY, vrentity_setLocation, "vec3", "location"); QUERY->add_arg(QUERY, "vec3", "loc"); // vec3 VREntity.rotation() QUERY->add_sfun(QUERY, vrentity_getRotation, "vec3", "rotation"); QUERY->add_sfun(QUERY, vrentity_setRotation, "vec3", "rotation"); QUERY->add_arg(QUERY, "vec3", "rot"); // vec3 VREntity.scaling() QUERY->add_sfun(QUERY, vrentity_getScaling, "vec3", "scaling"); QUERY->add_sfun(QUERY, vrentity_setScaling, "vec3", "scaling"); QUERY->add_arg(QUERY, "vec3", "sca"); // vec3 VREntity.rgb() QUERY->add_sfun(QUERY, vrentity_getRGB, "vec3", "rgb"); QUERY->add_sfun(QUERY, vrentity_setRGB, "vec3", "rgb"); QUERY->add_arg(QUERY, "vec3", "col"); // vec4 VREntity.rgb() QUERY->add_sfun(QUERY, vrentity_getRGBA, "vec4", "rgba"); QUERY->add_sfun(QUERY, vrentity_setRGBA, "vec4", "rgba"); QUERY->add_arg(QUERY, "vec4", "rgba"); } // end the class definition QUERY->end_class(QUERY); // begin the class definition QUERY->begin_class(QUERY, "VR", "Object"); { // VRObject VR.object(name) // retrive objects QUERY->add_sfun(QUERY, vr_object, "VRObject", "object"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "name"); // int VR.setInt(key,value) // set QUERY->add_sfun(QUERY, vr_setInt, "int", "setInt"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "int", "value"); // float VR.setFloat(key,value) // set QUERY->add_sfun(QUERY, vr_getInt, "int", "getInt"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // float VR.setFloat(key,value) // set QUERY->add_sfun(QUERY, vr_setFloat, "float", "setFloat"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "int", "value"); // float VR.getFloat(key,value) // set QUERY->add_sfun(QUERY, vr_getFloat, "float", "getFloat"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // float VR.setString(key,value) // set QUERY->add_sfun(QUERY, vr_setFloat, "string", "setString"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "value"); // string VR.getString(key,value) // set QUERY->add_sfun(QUERY, vr_getString, "string", "getString"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // vec3 VR.setVec3(key,value) // set QUERY->add_sfun(QUERY, vr_setVec3, "vec3", "setVec3"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "vec3", "value"); // vec3 VR.getVec3(key,value) // set QUERY->add_sfun(QUERY, vr_getString, "vec3", "getVec3"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // vec4 VR.setVec4(key,value) // set QUERY->add_sfun(QUERY, vr_setVec4, "vec4", "setVec4"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // name of object to retrieve QUERY->add_arg(QUERY, "vec4", "value"); // vec4 VR.getVec4(key,value) // set QUERY->add_sfun(QUERY, vr_getString, "vec4", "getVec4"); // name of object to retrieve QUERY->add_arg(QUERY, "string", "key"); // Event VR.displaySync // event for display QUERY->add_sfun(QUERY, vr_object, "Event", "displaySync"); } // end the class definition QUERY->end_class(QUERY); // wasn't that a breeze? return TRUE; } CK_DLL_SFUN(vrentity_getLocation) { } CK_DLL_SFUN(vrentity_setLocation); CK_DLL_SFUN(vrentity_getRotation); CK_DLL_SFUN(vrentity_setRotation); CK_DLL_SFUN(vrentity_getScaling); CK_DLL_SFUN(vrentity_setScaling); CK_DLL_SFUN(vrentity_getRGB); CK_DLL_SFUN(vrentity_setRGB); CK_DLL_SFUN(vrentity_getRGBA); CK_DLL_SFUN(vrentity_setRGBA); CK_DLL_SFUN(vrentity_addEntity); CK_DLL_SFUN(vrentity_removeEntity); <|endoftext|>
<commit_before>// Include standard headers #include <stdio.h> #include <stdlib.h> #include <vector> #include <string> // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif GLFWwindow* window; // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include <glm/gtc/matrix_transform.hpp> using namespace std; #include "common/shader.hpp" #include "common/texture.hpp" #include "common/controls.hpp" #include "common/objloader.hpp" #include "common/vboindexer.hpp" #include "common/text2D.hpp" #define WINDOW_WIDTH 1600 #define WINDOW_HEIGHT 900 #define TEXT_SIZE 40 #define FONT_SIZE 16 #define PI 3.14159265359f // font texture file format: bmp/... std::string g_font_texture_file_format = "bmp"; // font texture filename. // std::string g_font_texture_filename = "Holstein.DDS"; std::string g_font_texture_filename = "Holstein.bmp"; int main(void) { // Initial position : on +Z position = glm::vec3(1.5f, 0.0f, 3.75f); // Initial horizontal angle : toward -Z horizontalAngle = -3.0f; // Initial vertical angle : none // verticalAngle = PI / 2; verticalAngle = 0.0f; // Initial Field of View initialFoV = 45.0f; // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); // Open a window and create its OpenGL context window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Several models", NULL, NULL); if (window == NULL) { fprintf (stderr, "Failed to open GLFW window.\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Initialize GLEW if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetCursorPos(window, (WINDOW_WIDTH / 2), (WINDOW_HEIGHT / 2)); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); // Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE); // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders("StandardShading.vertexshader", "StandardShading.fragmentshader"); // Get a handle for our "MVP" uniform GLuint MatrixID = glGetUniformLocation(programID, "MVP"); GLuint ViewMatrixID = glGetUniformLocation(programID, "V"); GLuint ModelMatrixID = glGetUniformLocation(programID, "M"); // Get a handle for our buffers GLuint vertexPosition_modelspaceID = glGetAttribLocation(programID, "vertexPosition_modelspace"); GLuint vertexUVID = glGetAttribLocation(programID, "vertexUV"); GLuint vertexNormal_modelspaceID = glGetAttribLocation(programID, "vertexNormal_modelspace"); // Load the texture GLuint Texture = loadDDS("uvmap.DDS"); // Get a handle for our "myTextureSampler" uniform GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler"); // Read our .obj file std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; bool res = load_OBJ("suzanne.obj", vertices, uvs, normals); std::vector<GLuint> indices; std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_uvs; std::vector<glm::vec3> indexed_normals; indexVBO(vertices, uvs, normals, indices, indexed_vertices, indexed_uvs, indexed_normals); // Load it into a VBO GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW); GLuint uvbuffer; glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(glm::vec2), &indexed_uvs[0], GL_STATIC_DRAW); GLuint normalbuffer; glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW); // Generate a buffer for the indices as well GLuint elementbuffer; glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0] , GL_STATIC_DRAW); // Get a handle for our "LightPosition" uniform glUseProgram(programID); GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace"); // Initialize our little text library with the Holstein font const char *char_g_font_texture_filename = g_font_texture_filename.c_str(); const char *char_g_font_texture_file_format = g_font_texture_file_format.c_str(); initText2D(WINDOW_WIDTH, WINDOW_HEIGHT, char_g_font_texture_filename, char_g_font_texture_file_format); // For speed computation double lastTime = glfwGetTime(); int nbFrames = 0; do { // Measure speed double currentTime = glfwGetTime(); nbFrames++; if (currentTime - lastTime >= 1.0){ // If last prinf() was more than 1sec ago // printf and reset printf("%f ms/frame\n", 1000.0/double(nbFrames)); nbFrames = 0; lastTime += 1.0; } // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Compute the MVP matrix from keyboard and mouse input computeMatricesFromInputs(); glm::mat4 ProjectionMatrix = getProjectionMatrix(); glm::mat4 ViewMatrix = getViewMatrix(); ////// Start of the rendering of the first object ////// // Use our shader glUseProgram(programID); glm::vec3 lightPos = glm::vec3(4,4,4); glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); // This one doesn't change between objects, so this can be done once for all objects that use "programID" glm::mat4 ModelMatrix1 = glm::mat4(1.0); glm::mat4 MVP1 = ProjectionMatrix * ViewMatrix * ModelMatrix1; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP1[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix1[0][0]); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(TextureID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(vertexPosition_modelspaceID); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( vertexPosition_modelspaceID, // The attribute we want to configure 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(vertexUVID); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer( vertexUVID, // The attribute we want to configure 2, // size : U+V => 2 GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // 3rd attribute buffer : normals glEnableVertexAttribArray(vertexNormal_modelspaceID); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer( vertexNormal_modelspaceID, // The attribute we want to configure 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode indices.size(), // count GL_UNSIGNED_INT, // type (void*) 0 // element array buffer offset ); ////// End of rendering of the first object ////// ////// Start of the rendering of the second object ////// // In our very specific case, the 2 objects use the same shader. // So it's useless to re-bind the "programID" shader, since it's already the current one. //glUseProgram(programID); // Similarly : don't re-set the light position and camera matrix in programID, // it's still valid ! // *** You would have to do it if you used another shader ! *** //glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); //glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); // This one doesn't change between objects, so this can be done once for all objects that use "programID" // Again : this is already done, but this only works because we use the same shader. //// Bind our texture in Texture Unit 0 //glActiveTexture(GL_TEXTURE0); //glBindTexture(GL_TEXTURE_2D, Texture); //// Set our "myTextureSampler" sampler to user Texture Unit 0 //glUniform1i(TextureID, 0); // BUT the Model matrix is different (and the MVP too) glm::mat4 ModelMatrix2 = glm::mat4(1.0); ModelMatrix2 = glm::translate(ModelMatrix2, glm::vec3(2.0f, 0.0f, 0.0f)); glm::mat4 MVP2 = ProjectionMatrix * ViewMatrix * ModelMatrix2; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP2[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix2[0][0]); // The rest is exactly the same as the first object // 1st attribute buffer : vertices // glEnableVertexAttribArray(vertexPosition_modelspaceID); // Already enabled glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(vertexPosition_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); // 2nd attribute buffer : UVs // glEnableVertexAttribArray(vertexUVID); // Already enabled glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); // 3rd attribute buffer : normals // glEnableVertexAttribArray(vertexNormal_modelspaceID); // Already enabled glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer(vertexNormal_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); // Draw the triangles ! glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, (void*)0); ////// End of rendering of the second object ////// glDisableVertexAttribArray(vertexPosition_modelspaceID); glDisableVertexAttribArray(vertexUVID); glDisableVertexAttribArray(vertexNormal_modelspaceID); PrintingStruct printing_struct; printing_struct.screen_width = WINDOW_WIDTH; printing_struct.screen_height = WINDOW_HEIGHT; printing_struct.text_size = TEXT_SIZE; printing_struct.font_size = FONT_SIZE; printing_struct.char_font_texture_file_format = "bmp"; char coordinates_text[256]; sprintf(coordinates_text, "(%.2f,%.2f,%.2f) (%.2f,%.2f)", position.x, position.y, position.z, horizontalAngle, verticalAngle); printing_struct.x = 0; printing_struct.y = 0; printing_struct.text = coordinates_text; printing_struct.horizontal_alignment = "left"; printing_struct.vertical_alignment = "bottom"; printText2D(printing_struct); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); // Cleanup VBO and shader glDeleteBuffers(1, &vertexbuffer); glDeleteBuffers(1, &uvbuffer); glDeleteBuffers(1, &normalbuffer); glDeleteBuffers(1, &elementbuffer); glDeleteProgram(programID); glDeleteTextures(1, &Texture); // Delete the text's VBO, the shader and the texture cleanupText2D(); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; } <commit_msg>`void*)0` -> `void*) 0`.<commit_after>// Include standard headers #include <stdio.h> #include <stdlib.h> #include <vector> #include <string> // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <glfw3.h> #endif GLFWwindow* window; // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include <glm/gtc/matrix_transform.hpp> using namespace std; #include "common/shader.hpp" #include "common/texture.hpp" #include "common/controls.hpp" #include "common/objloader.hpp" #include "common/vboindexer.hpp" #include "common/text2D.hpp" #define WINDOW_WIDTH 1600 #define WINDOW_HEIGHT 900 #define TEXT_SIZE 40 #define FONT_SIZE 16 #define PI 3.14159265359f // font texture file format: bmp/... std::string g_font_texture_file_format = "bmp"; // font texture filename. // std::string g_font_texture_filename = "Holstein.DDS"; std::string g_font_texture_filename = "Holstein.bmp"; int main(void) { // Initial position : on +Z position = glm::vec3(1.5f, 0.0f, 3.75f); // Initial horizontal angle : toward -Z horizontalAngle = -3.0f; // Initial vertical angle : none // verticalAngle = PI / 2; verticalAngle = 0.0f; // Initial Field of View initialFoV = 45.0f; // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); // Open a window and create its OpenGL context window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Several models", NULL, NULL); if (window == NULL) { fprintf (stderr, "Failed to open GLFW window.\n"); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Initialize GLEW if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetCursorPos(window, (WINDOW_WIDTH / 2), (WINDOW_HEIGHT / 2)); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); // Cull triangles which normal is not towards the camera glEnable(GL_CULL_FACE); // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders("StandardShading.vertexshader", "StandardShading.fragmentshader"); // Get a handle for our "MVP" uniform GLuint MatrixID = glGetUniformLocation(programID, "MVP"); GLuint ViewMatrixID = glGetUniformLocation(programID, "V"); GLuint ModelMatrixID = glGetUniformLocation(programID, "M"); // Get a handle for our buffers GLuint vertexPosition_modelspaceID = glGetAttribLocation(programID, "vertexPosition_modelspace"); GLuint vertexUVID = glGetAttribLocation(programID, "vertexUV"); GLuint vertexNormal_modelspaceID = glGetAttribLocation(programID, "vertexNormal_modelspace"); // Load the texture GLuint Texture = loadDDS("uvmap.DDS"); // Get a handle for our "myTextureSampler" uniform GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler"); // Read our .obj file std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; bool res = load_OBJ("suzanne.obj", vertices, uvs, normals); std::vector<GLuint> indices; std::vector<glm::vec3> indexed_vertices; std::vector<glm::vec2> indexed_uvs; std::vector<glm::vec3> indexed_normals; indexVBO(vertices, uvs, normals, indices, indexed_vertices, indexed_uvs, indexed_normals); // Load it into a VBO GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_vertices.size() * sizeof(glm::vec3), &indexed_vertices[0], GL_STATIC_DRAW); GLuint uvbuffer; glGenBuffers(1, &uvbuffer); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_uvs.size() * sizeof(glm::vec2), &indexed_uvs[0], GL_STATIC_DRAW); GLuint normalbuffer; glGenBuffers(1, &normalbuffer); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glBufferData(GL_ARRAY_BUFFER, indexed_normals.size() * sizeof(glm::vec3), &indexed_normals[0], GL_STATIC_DRAW); // Generate a buffer for the indices as well GLuint elementbuffer; glGenBuffers(1, &elementbuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0] , GL_STATIC_DRAW); // Get a handle for our "LightPosition" uniform glUseProgram(programID); GLuint LightID = glGetUniformLocation(programID, "LightPosition_worldspace"); // Initialize our little text library with the Holstein font const char *char_g_font_texture_filename = g_font_texture_filename.c_str(); const char *char_g_font_texture_file_format = g_font_texture_file_format.c_str(); initText2D(WINDOW_WIDTH, WINDOW_HEIGHT, char_g_font_texture_filename, char_g_font_texture_file_format); // For speed computation double lastTime = glfwGetTime(); int nbFrames = 0; do { // Measure speed double currentTime = glfwGetTime(); nbFrames++; if (currentTime - lastTime >= 1.0){ // If last prinf() was more than 1sec ago // printf and reset printf("%f ms/frame\n", 1000.0/double(nbFrames)); nbFrames = 0; lastTime += 1.0; } // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Compute the MVP matrix from keyboard and mouse input computeMatricesFromInputs(); glm::mat4 ProjectionMatrix = getProjectionMatrix(); glm::mat4 ViewMatrix = getViewMatrix(); ////// Start of the rendering of the first object ////// // Use our shader glUseProgram(programID); glm::vec3 lightPos = glm::vec3(4,4,4); glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); // This one doesn't change between objects, so this can be done once for all objects that use "programID" glm::mat4 ModelMatrix1 = glm::mat4(1.0); glm::mat4 MVP1 = ProjectionMatrix * ViewMatrix * ModelMatrix1; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP1[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix1[0][0]); // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture); // Set our "myTextureSampler" sampler to user Texture Unit 0 glUniform1i(TextureID, 0); // 1rst attribute buffer : vertices glEnableVertexAttribArray(vertexPosition_modelspaceID); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( vertexPosition_modelspaceID, // The attribute we want to configure 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // 2nd attribute buffer : UVs glEnableVertexAttribArray(vertexUVID); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer( vertexUVID, // The attribute we want to configure 2, // size : U+V => 2 GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // 3rd attribute buffer : normals glEnableVertexAttribArray(vertexNormal_modelspaceID); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer( vertexNormal_modelspaceID, // The attribute we want to configure 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); // Draw the triangles ! glDrawElements( GL_TRIANGLES, // mode indices.size(), // count GL_UNSIGNED_INT, // type (void*) 0 // element array buffer offset ); ////// End of rendering of the first object ////// ////// Start of the rendering of the second object ////// // In our very specific case, the 2 objects use the same shader. // So it's useless to re-bind the "programID" shader, since it's already the current one. //glUseProgram(programID); // Similarly : don't re-set the light position and camera matrix in programID, // it's still valid ! // *** You would have to do it if you used another shader ! *** //glUniform3f(LightID, lightPos.x, lightPos.y, lightPos.z); //glUniformMatrix4fv(ViewMatrixID, 1, GL_FALSE, &ViewMatrix[0][0]); // This one doesn't change between objects, so this can be done once for all objects that use "programID" // Again : this is already done, but this only works because we use the same shader. //// Bind our texture in Texture Unit 0 //glActiveTexture(GL_TEXTURE0); //glBindTexture(GL_TEXTURE_2D, Texture); //// Set our "myTextureSampler" sampler to user Texture Unit 0 //glUniform1i(TextureID, 0); // BUT the Model matrix is different (and the MVP too) glm::mat4 ModelMatrix2 = glm::mat4(1.0); ModelMatrix2 = glm::translate(ModelMatrix2, glm::vec3(2.0f, 0.0f, 0.0f)); glm::mat4 MVP2 = ProjectionMatrix * ViewMatrix * ModelMatrix2; // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP2[0][0]); glUniformMatrix4fv(ModelMatrixID, 1, GL_FALSE, &ModelMatrix2[0][0]); // The rest is exactly the same as the first object // 1st attribute buffer : vertices // glEnableVertexAttribArray(vertexPosition_modelspaceID); // Already enabled glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer(vertexPosition_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0); // 2nd attribute buffer : UVs // glEnableVertexAttribArray(vertexUVID); // Already enabled glBindBuffer(GL_ARRAY_BUFFER, uvbuffer); glVertexAttribPointer(vertexUVID, 2, GL_FLOAT, GL_FALSE, 0, (void*) 0); // 3rd attribute buffer : normals // glEnableVertexAttribArray(vertexNormal_modelspaceID); // Already enabled glBindBuffer(GL_ARRAY_BUFFER, normalbuffer); glVertexAttribPointer(vertexNormal_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*) 0); // Index buffer glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer); // Draw the triangles ! glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, (void*) 0); ////// End of rendering of the second object ////// glDisableVertexAttribArray(vertexPosition_modelspaceID); glDisableVertexAttribArray(vertexUVID); glDisableVertexAttribArray(vertexNormal_modelspaceID); PrintingStruct printing_struct; printing_struct.screen_width = WINDOW_WIDTH; printing_struct.screen_height = WINDOW_HEIGHT; printing_struct.text_size = TEXT_SIZE; printing_struct.font_size = FONT_SIZE; printing_struct.char_font_texture_file_format = "bmp"; char coordinates_text[256]; sprintf(coordinates_text, "(%.2f,%.2f,%.2f) (%.2f,%.2f)", position.x, position.y, position.z, horizontalAngle, verticalAngle); printing_struct.x = 0; printing_struct.y = 0; printing_struct.text = coordinates_text; printing_struct.horizontal_alignment = "left"; printing_struct.vertical_alignment = "bottom"; printText2D(printing_struct); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); // Cleanup VBO and shader glDeleteBuffers(1, &vertexbuffer); glDeleteBuffers(1, &uvbuffer); glDeleteBuffers(1, &normalbuffer); glDeleteBuffers(1, &elementbuffer); glDeleteProgram(programID); glDeleteTextures(1, &Texture); // Delete the text's VBO, the shader and the texture cleanupText2D(); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; } <|endoftext|>
<commit_before>/* * George Papanikolaou CEID 2014 * Shortest Augmenting Path Maximum Flow algorithm implementation * aka "Edmonds–Karp algorithm" */ #include <map> #include "boost-types.h" #include <boost/graph/breadth_first_search.hpp> int shortest_aug_path(BoostGraph& BG, std::vector<BoostEdge> ret_flow) { // TODO } <commit_msg>add some structure for the bfs<commit_after>/* * George Papanikolaou CEID 2014 * Shortest Augmenting Path Maximum Flow algorithm implementation * aka "Edmonds–Karp algorithm" */ #include <map> #include "boost-types.h" #include <boost/graph/breadth_first_search.hpp> /* * subclassing the default visitor for our own needs */ class MyVisitor : public boost::default_dfs_visitor { public: void discover_vertex(BoostVertex v, const BoostGraph& g) const { // TODO something when discovering the node return; } }; /* * this file's core function */ int shortest_aug_path(BoostGraph& BG, std::vector<BoostEdge> ret_flow) { MyVisitor vis breadth_first_search(BG, boost::visitor(vis)); // add second argument the intial core if desired } <|endoftext|>
<commit_before>// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <stdio.h> #ifdef WINCE # include <types.h> #else # include <direct.h> # include <sys/types.h> # include <sys/stat.h> #endif // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsDirWnt::OsDirWnt(const char* pathname) : OsDirBase(pathname) { } OsDirWnt::OsDirWnt(const OsPathWnt& pathname) : OsDirBase(pathname.data()) { } // Copy constructor OsDirWnt::OsDirWnt(const OsDirWnt& rOsDirWnt) : OsDirBase(rOsDirWnt.mDirName.data()) { } // Destructor OsDirWnt::~OsDirWnt() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDirWnt& OsDirWnt::operator=(const OsDirWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsStatus OsDirWnt::create() const { OsStatus ret = OS_INVALID; OsPathBase path; if (mDirName.getNativePath(path) == OS_SUCCESS) { int err = _mkdir((const char *)path.data()); if (err != -1) { ret = OS_SUCCESS; } } return ret; } OsStatus OsDirWnt::rename(const char* name) { OsStatus ret = OS_INVALID; OsPathBase path; if (mDirName.getNativePath(path) == OS_SUCCESS) { int err = ::rename(path.data(),name); if (err != -1) { ret = OS_SUCCESS; //make this object point to new path mDirName = name; } } return ret; } /* ============================ ACCESSORS ================================= */ //static OsTime FileTimeToOsTime(FILETIME ft) //{ // __int64 ll = (((__int64)ft.dwHighDateTime << 32) | // ft.dwLowDateTime) - 116444736000000000; // // See http://support.microsoft.com/?scid=kb%3Ben-us%3B167296&x=14&y=17 // // return OsTime((long)(ll / 10000000), (long)((ll / 10) % 1000000)); //} OsStatus OsDirWnt::getFileInfo(OsFileInfoBase& fileinfo) const { OsStatus ret = OS_INVALID; WIN32_FILE_ATTRIBUTE_DATA w32data; BOOL bRes = GetFileAttributesEx(mDirName.data(), GetFileExInfoStandard, &w32data); if (bRes) { ret = OS_SUCCESS; fileinfo.mbIsDirectory = (w32data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? TRUE : FALSE; fileinfo.mbIsReadOnly = (w32data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? TRUE : FALSE; fileinfo.mSize = ((ULONGLONG)w32data.nFileSizeHigh << 32) | w32data.nFileSizeLow; fileinfo.mCreateTime = OsFileWnt::fileTimeToOsTime(w32data.ftCreationTime); fileinfo.mModifiedTime = OsFileWnt::fileTimeToOsTime(w32data.ftLastWriteTime); } return ret; } /* ============================ INQUIRY =================================== */ UtlBoolean OsDirWnt::exists() { UtlBoolean stat = FALSE; OsFileInfoWnt info; OsStatus retval = getFileInfo(info); if (retval == OS_SUCCESS) stat = TRUE; return stat; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <commit_msg>Remove some unnecessary commented out code.<commit_after>// // Copyright (C) 2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <stdio.h> #ifdef WINCE # include <types.h> #else # include <direct.h> # include <sys/types.h> # include <sys/stat.h> #endif // APPLICATION INCLUDES #include "os/OsFS.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor OsDirWnt::OsDirWnt(const char* pathname) : OsDirBase(pathname) { } OsDirWnt::OsDirWnt(const OsPathWnt& pathname) : OsDirBase(pathname.data()) { } // Copy constructor OsDirWnt::OsDirWnt(const OsDirWnt& rOsDirWnt) : OsDirBase(rOsDirWnt.mDirName.data()) { } // Destructor OsDirWnt::~OsDirWnt() { } /* ============================ MANIPULATORS ============================== */ // Assignment operator OsDirWnt& OsDirWnt::operator=(const OsDirWnt& rhs) { if (this == &rhs) // handle the assignment to self case return *this; return *this; } OsStatus OsDirWnt::create() const { OsStatus ret = OS_INVALID; OsPathBase path; if (mDirName.getNativePath(path) == OS_SUCCESS) { int err = _mkdir((const char *)path.data()); if (err != -1) { ret = OS_SUCCESS; } } return ret; } OsStatus OsDirWnt::rename(const char* name) { OsStatus ret = OS_INVALID; OsPathBase path; if (mDirName.getNativePath(path) == OS_SUCCESS) { int err = ::rename(path.data(),name); if (err != -1) { ret = OS_SUCCESS; //make this object point to new path mDirName = name; } } return ret; } /* ============================ ACCESSORS ================================= */ OsStatus OsDirWnt::getFileInfo(OsFileInfoBase& fileinfo) const { OsStatus ret = OS_INVALID; WIN32_FILE_ATTRIBUTE_DATA w32data; BOOL bRes = GetFileAttributesEx(mDirName.data(), GetFileExInfoStandard, &w32data); if (bRes) { ret = OS_SUCCESS; fileinfo.mbIsDirectory = (w32data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? TRUE : FALSE; fileinfo.mbIsReadOnly = (w32data.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? TRUE : FALSE; fileinfo.mSize = ((ULONGLONG)w32data.nFileSizeHigh << 32) | w32data.nFileSizeLow; fileinfo.mCreateTime = OsFileWnt::fileTimeToOsTime(w32data.ftCreationTime); fileinfo.mModifiedTime = OsFileWnt::fileTimeToOsTime(w32data.ftLastWriteTime); } return ret; } /* ============================ INQUIRY =================================== */ UtlBoolean OsDirWnt::exists() { UtlBoolean stat = FALSE; OsFileInfoWnt info; OsStatus retval = getFileInfo(info); if (retval == OS_SUCCESS) stat = TRUE; return stat; } /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>#ifdef _WIN32 #define _USE_MATH_DEFINES #endif #include <iostream> #include <list> #include "core/Halite.hpp" inline std::istream& operator>>(std::istream& i, std::pair<signed int, signed int>& p) { i >> p.first >> p.second; return i; } inline std::ostream& operator<<(std::ostream& o, const std::pair<signed int, signed int>& p) { o << p.first << ' ' << p.second; return o; } #include <tclap/CmdLine.h> namespace TCLAP { template<> struct ArgTraits<std::pair<signed int, signed int> > { typedef TCLAP::ValueLike ValueCategory; }; } bool quiet_output = false; //Need to be passed to a bunch of classes; extern is cleaner. Halite* my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors. Networking promptNetworking(); void promptDimensions(unsigned short& w, unsigned short& h); int main(int argc, char** argv) { srand(time(NULL)); //For all non-seeded randomness. Networking networking; std::vector<std::string>* names = NULL; auto id = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::high_resolution_clock().now().time_since_epoch()).count(); TCLAP::CmdLine cmd("Halite Game Environment", ' ', "1.2"); //Switch Args. TCLAP::SwitchArg quietSwitch("q", "quiet", "Runs game in quiet mode, producing machine-parsable output.", cmd, false); TCLAP::SwitchArg overrideSwitch("o", "override", "Overrides player-sent names using cmd args [SERVER ONLY].", cmd, false); TCLAP::SwitchArg timeoutSwitch("t", "timeout", "Causes game environment to ignore timeouts (give all bots infinite time).", cmd, false); TCLAP::SwitchArg noReplaySwitch ("r", "noreplay", "Turns off the replay generation.", cmd, false); //Value Args TCLAP::ValueArg<unsigned int> nPlayersArg("n", "nplayers", "Create a map that will accommodate n players [SINGLE PLAYER MODE ONLY].", false, 1, "{1,2,3,4,5,6}", cmd); TCLAP::ValueArg<std::pair<signed int, signed int> > dimensionArgs("d", "dimensions", "The dimensions of the map.", false, { 0, 0 }, "a string containing two space-seprated positive integers", cmd); TCLAP::ValueArg<unsigned int> seedArg("s", "seed", "The seed for the map generator.", false, 0, "positive integer", cmd); TCLAP::ValueArg<std::string> replayDirectoryArg("i", "replaydirectory", "The path to directory for replay output.", false, ".", "path to directory", cmd); TCLAP::ValueArg<std::string> constantsArg( "", "constantsfile", "JSON file containing runtime constants to use.", false, "", "path to file", cmd ); TCLAP::SwitchArg printConstantsSwitch( "", "print-constants", "Print out the default constants and exit.", cmd, false ); //Remaining Args, be they start commands and/or override names. Description only includes start commands since it will only be seen on local testing. TCLAP::UnlabeledMultiArg<std::string> otherArgs("NonspecifiedArgs", "Start commands for bots.", false, "Array of strings", cmd); cmd.parse(argc, argv); unsigned short mapWidth = dimensionArgs.getValue().first; unsigned short mapHeight = dimensionArgs.getValue().second; unsigned int seed; if (seedArg.getValue() != 0) seed = seedArg.getValue(); else seed = (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count() % 4294967295); unsigned short n_players_for_map_creation = nPlayersArg.getValue(); quiet_output = quietSwitch.getValue(); bool override_names = overrideSwitch.getValue(); bool ignore_timeout = timeoutSwitch.getValue(); if (printConstantsSwitch.getValue()) { std::cout << hlt::GameConstants::get().to_json().dump(4) << '\n'; return 0; } // Update the game constants. if (constantsArg.isSet()) { std::ifstream constants_file(constantsArg.getValue()); nlohmann::json constants_json; constants_file >> constants_json; auto& constants = hlt::GameConstants::get_mut(); constants.from_json(constants_json); if (!quiet_output) { std::cout << "Game constants: \n" << constants.to_json().dump(4) << '\n'; } } else { if (!quiet_output) { std::cout << "Game constants: all default\n"; } } std::vector<std::string> unlabeledArgsVector = otherArgs.getValue(); std::list<std::string> unlabeledArgs; for (auto a = unlabeledArgsVector.begin(); a != unlabeledArgsVector.end(); a++) { unlabeledArgs.push_back(*a); } if (mapWidth == 0 && mapHeight == 0) { std::vector<unsigned short> mapSizeChoices = { 100, 125, 128, 150, 175, 200, 225, 250, 256 }; std::mt19937 prg(seed); std::uniform_int_distribution<unsigned short> size_dist(0, mapSizeChoices.size() - 1); auto random_choice = size_dist(prg); mapWidth = mapSizeChoices[random_choice]; mapHeight = mapWidth; } const auto override_factor = overrideSwitch.getValue() ? 2 : 1; if (unlabeledArgs.size() != 1 && unlabeledArgs.size() != 2 * override_factor && unlabeledArgs.size() != 4 * override_factor) { std::cout << "Must have either 2 or 4 players, or a solo player.\n"; return 1; } if (unlabeledArgs.size() == 1 && n_players_for_map_creation != 2 && n_players_for_map_creation != 4) { // Limiation of solar system map generator used std::cout << "Must have either 2 or 4 players for map creation.\n"; return 1; } if (override_names) { if (unlabeledArgs.size() < 4 || unlabeledArgs.size() % 2 != 0) { std::cout << "Invalid number of player parameters with override switch enabled. Override intended for server use only." << std::endl; exit(1); } else { try { names = new std::vector<std::string>(); while (!unlabeledArgs.empty()) { networking.launch_bot(unlabeledArgs.front()); unlabeledArgs.pop_front(); names->push_back(unlabeledArgs.front()); unlabeledArgs.pop_front(); } } catch (...) { std::cout << "Invalid player parameters with override switch enabled. Override intended for server use only." << std::endl; delete names; names = NULL; exit(1); } } } else { if (unlabeledArgs.size() < 1) { std::cout << "Please provide the launch command string for at least one bot." << std::endl << "Use the --help flag for usage details.\n"; exit(1); } try { while (!unlabeledArgs.empty()) { networking.launch_bot(unlabeledArgs.front()); unlabeledArgs.pop_front(); } } catch (...) { std::cout << "One or more of your bot launch command strings failed. Please check for correctness and try again." << std::endl; exit(1); } } if (networking.player_count() > 1 && n_players_for_map_creation != 1) { std::cout << std::endl << "Only single-player mode enables specified n-player maps. When entering multiple bots, please do not try to specify n." << std::endl << std::endl; exit(1); } if (networking.player_count() > 1) n_players_for_map_creation = networking.player_count(); if (n_players_for_map_creation > 6 || n_players_for_map_creation < 1) { std::cout << std::endl << "A map can only accommodate between 1 and 6 players." << std::endl << std::endl; exit(1); } //Create game. Null parameters will be ignored. my_game = new Halite(mapWidth, mapHeight, seed, n_players_for_map_creation, networking, ignore_timeout); std::string outputFilename = replayDirectoryArg.getValue(); #ifdef _WIN32 if(outputFilename.back() != '\\') outputFilename.push_back('\\'); #else if (outputFilename.back() != '/') outputFilename.push_back('/'); #endif GameStatistics stats = my_game->run_game(names, id, !noReplaySwitch.getValue(), outputFilename); if (names != NULL) delete names; std::string victoryOut; if (!quiet_output) { for (unsigned int player_id = 0; player_id < stats.player_statistics.size(); player_id++) { auto& player_stats = stats.player_statistics[player_id]; std::cout << "Player #" << player_stats.tag << ", " << my_game->get_name(player_stats.tag) << ", came in rank #" << player_stats.rank << " and was last alive on frame #" << player_stats.last_frame_alive << ", producing " << player_stats.total_ship_count << " ships" << " and dealing " << player_stats.damage_dealt << " damage" << "!\n"; } } delete my_game; return 0; } <commit_msg>Tweak environment map sizes to match competition environment<commit_after>#ifdef _WIN32 #define _USE_MATH_DEFINES #endif #include <iostream> #include <list> #include "core/Halite.hpp" inline std::istream& operator>>(std::istream& i, std::pair<signed int, signed int>& p) { i >> p.first >> p.second; return i; } inline std::ostream& operator<<(std::ostream& o, const std::pair<signed int, signed int>& p) { o << p.first << ' ' << p.second; return o; } #include <tclap/CmdLine.h> namespace TCLAP { template<> struct ArgTraits<std::pair<signed int, signed int> > { typedef TCLAP::ValueLike ValueCategory; }; } bool quiet_output = false; //Need to be passed to a bunch of classes; extern is cleaner. Halite* my_game; //Is a pointer to avoid problems with assignment, dynamic memory, and default constructors. Networking promptNetworking(); void promptDimensions(unsigned short& w, unsigned short& h); int main(int argc, char** argv) { srand(time(NULL)); //For all non-seeded randomness. Networking networking; std::vector<std::string>* names = NULL; auto id = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::high_resolution_clock().now().time_since_epoch()).count(); TCLAP::CmdLine cmd("Halite Game Environment", ' ', "1.2"); //Switch Args. TCLAP::SwitchArg quietSwitch("q", "quiet", "Runs game in quiet mode, producing machine-parsable output.", cmd, false); TCLAP::SwitchArg overrideSwitch("o", "override", "Overrides player-sent names using cmd args [SERVER ONLY].", cmd, false); TCLAP::SwitchArg timeoutSwitch("t", "timeout", "Causes game environment to ignore timeouts (give all bots infinite time).", cmd, false); TCLAP::SwitchArg noReplaySwitch ("r", "noreplay", "Turns off the replay generation.", cmd, false); //Value Args TCLAP::ValueArg<unsigned int> nPlayersArg("n", "nplayers", "Create a map that will accommodate n players [SINGLE PLAYER MODE ONLY].", false, 1, "{1,2,3,4,5,6}", cmd); TCLAP::ValueArg<std::pair<signed int, signed int> > dimensionArgs("d", "dimensions", "The dimensions of the map.", false, { 0, 0 }, "a string containing two space-seprated positive integers", cmd); TCLAP::ValueArg<unsigned int> seedArg("s", "seed", "The seed for the map generator.", false, 0, "positive integer", cmd); TCLAP::ValueArg<std::string> replayDirectoryArg("i", "replaydirectory", "The path to directory for replay output.", false, ".", "path to directory", cmd); TCLAP::ValueArg<std::string> constantsArg( "", "constantsfile", "JSON file containing runtime constants to use.", false, "", "path to file", cmd ); TCLAP::SwitchArg printConstantsSwitch( "", "print-constants", "Print out the default constants and exit.", cmd, false ); //Remaining Args, be they start commands and/or override names. Description only includes start commands since it will only be seen on local testing. TCLAP::UnlabeledMultiArg<std::string> otherArgs("NonspecifiedArgs", "Start commands for bots.", false, "Array of strings", cmd); cmd.parse(argc, argv); unsigned short mapWidth = dimensionArgs.getValue().first; unsigned short mapHeight = dimensionArgs.getValue().second; unsigned int seed; if (seedArg.getValue() != 0) seed = seedArg.getValue(); else seed = (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count() % 4294967295); unsigned short n_players_for_map_creation = nPlayersArg.getValue(); quiet_output = quietSwitch.getValue(); bool override_names = overrideSwitch.getValue(); bool ignore_timeout = timeoutSwitch.getValue(); if (printConstantsSwitch.getValue()) { std::cout << hlt::GameConstants::get().to_json().dump(4) << '\n'; return 0; } // Update the game constants. if (constantsArg.isSet()) { std::ifstream constants_file(constantsArg.getValue()); nlohmann::json constants_json; constants_file >> constants_json; auto& constants = hlt::GameConstants::get_mut(); constants.from_json(constants_json); if (!quiet_output) { std::cout << "Game constants: \n" << constants.to_json().dump(4) << '\n'; } } else { if (!quiet_output) { std::cout << "Game constants: all default\n"; } } std::vector<std::string> unlabeledArgsVector = otherArgs.getValue(); std::list<std::string> unlabeledArgs; for (auto a = unlabeledArgsVector.begin(); a != unlabeledArgsVector.end(); a++) { unlabeledArgs.push_back(*a); } if (mapWidth == 0 && mapHeight == 0) { std::vector<unsigned short> mapSizeChoices = { 160, 160, 192, 192, 192, 256, 256, 256, 256, 384, 384, 384 }; std::mt19937 prg(seed); std::uniform_int_distribution<unsigned short> size_dist(0, mapSizeChoices.size() - 1); mapWidth = mapSizeChoices[size_dist(prg)]; mapHeight = mapSizeChoices[size_dist(prg)]; if (mapHeight > mapWidth) { auto temp = mapWidth; mapWidth = mapHeight; mapHeight = temp; } } const auto override_factor = overrideSwitch.getValue() ? 2 : 1; if (unlabeledArgs.size() != 1 && unlabeledArgs.size() != 2 * override_factor && unlabeledArgs.size() != 4 * override_factor) { std::cout << "Must have either 2 or 4 players, or a solo player.\n"; return 1; } if (unlabeledArgs.size() == 1 && n_players_for_map_creation != 2 && n_players_for_map_creation != 4) { // Limiation of solar system map generator used std::cout << "Must have either 2 or 4 players for map creation.\n"; return 1; } if (override_names) { if (unlabeledArgs.size() < 4 || unlabeledArgs.size() % 2 != 0) { std::cout << "Invalid number of player parameters with override switch enabled. Override intended for server use only." << std::endl; exit(1); } else { try { names = new std::vector<std::string>(); while (!unlabeledArgs.empty()) { networking.launch_bot(unlabeledArgs.front()); unlabeledArgs.pop_front(); names->push_back(unlabeledArgs.front()); unlabeledArgs.pop_front(); } } catch (...) { std::cout << "Invalid player parameters with override switch enabled. Override intended for server use only." << std::endl; delete names; names = NULL; exit(1); } } } else { if (unlabeledArgs.size() < 1) { std::cout << "Please provide the launch command string for at least one bot." << std::endl << "Use the --help flag for usage details.\n"; exit(1); } try { while (!unlabeledArgs.empty()) { networking.launch_bot(unlabeledArgs.front()); unlabeledArgs.pop_front(); } } catch (...) { std::cout << "One or more of your bot launch command strings failed. Please check for correctness and try again." << std::endl; exit(1); } } if (networking.player_count() > 1 && n_players_for_map_creation != 1) { std::cout << std::endl << "Only single-player mode enables specified n-player maps. When entering multiple bots, please do not try to specify n." << std::endl << std::endl; exit(1); } if (networking.player_count() > 1) n_players_for_map_creation = networking.player_count(); if (n_players_for_map_creation > 6 || n_players_for_map_creation < 1) { std::cout << std::endl << "A map can only accommodate between 1 and 6 players." << std::endl << std::endl; exit(1); } //Create game. Null parameters will be ignored. my_game = new Halite(mapWidth, mapHeight, seed, n_players_for_map_creation, networking, ignore_timeout); std::string outputFilename = replayDirectoryArg.getValue(); #ifdef _WIN32 if(outputFilename.back() != '\\') outputFilename.push_back('\\'); #else if (outputFilename.back() != '/') outputFilename.push_back('/'); #endif GameStatistics stats = my_game->run_game(names, id, !noReplaySwitch.getValue(), outputFilename); if (names != NULL) delete names; std::string victoryOut; if (!quiet_output) { for (unsigned int player_id = 0; player_id < stats.player_statistics.size(); player_id++) { auto& player_stats = stats.player_statistics[player_id]; std::cout << "Player #" << player_stats.tag << ", " << my_game->get_name(player_stats.tag) << ", came in rank #" << player_stats.rank << " and was last alive on frame #" << player_stats.last_frame_alive << ", producing " << player_stats.total_ship_count << " ships" << " and dealing " << player_stats.damage_dealt << " damage" << "!\n"; } } delete my_game; return 0; } <|endoftext|>
<commit_before>#include "pipe.hpp" #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <string> #include <stdio.h> Pipe::Pipe() {} bool Pipe::execute(const vector<string> &cmd, string &input) { int pid; int pipes[2]; //pass in commands to args char* args[512]; for (unsigned i = 0; i < cmd.size() - 1; i++) { args[i] = (char*)cmd[i].c_str(); } //set file descriptors int in = open(input.c_str(), O_RDONLY); pipes[0] = in; pipes[1] = STDOUT_FILENO; //set output destination string filename = cmd[cmd.size() - 1]; int newOut = open(filename.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666); //create pipe pipe(pipes); pid = fork(); if (pid == -1) { perror("fork"); exit(1); } if (pid == 0) { dup2(pipes[0], 0); close(pipes[1]); if (execvp(args[0], args) == -1) { perror("exec"); exit(1); } } else { dup2(pipes[1], newOut); close(pipes[0]); if (execvp(args[0], args) == -1) { perror("exec"); exit(1); } } return true; }<commit_msg>finished everything<commit_after>#include "pipe.hpp" #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <string> #include <stdio.h> Pipe::Pipe() {} bool Pipe::execute(const vector<string> &cmd, string &input) { int pid; int pipes[2]; //pass in commands to args char* args[512]; for (unsigned i = 0; i < cmd.size() - 1; i++) { args[i] = (char*)cmd[i].c_str(); } //set file descriptors int in = open(input.c_str(), O_RDONLY); pipes[0] = in; pipes[1] = STDOUT_FILENO; //set output destination string filename = cmd[cmd.size() - 1]; int newOut = open(filename.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0666); //create pipe pipe(pipes); pid = fork(); if (pid == -1) { perror("fork"); exit(1); } if (pid == 0) { dup2(pipes[0], 0); close(pipes[1]); if (execvp(args[0], args) == -1) { perror("exec"); exit(1); } } else { dup2(pipes[1], newOut); close(pipes[0]); if (execvp(args[0], args) == -1) { perror("exec"); exit(1); } } return true; } <|endoftext|>
<commit_before>//== GRTransferFuncs.cpp - Path-Sens. Transfer Functions Interface -*- C++ -*--= // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines GRTransferFuncs, which provides a base-class that // defines an interface for transfer functions used by GRExprEngine. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/GRTransferFuncs.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" using namespace clang; void GRTransferFuncs::RegisterChecks(GRExprEngine& Eng) {} void GRTransferFuncs::EvalStore(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, Expr* E, ExplodedNode<GRState>* Pred, const GRState* St, SVal TargetLV, SVal Val) { // This code basically matches the "safety-net" logic of GRExprEngine: // bind Val to TargetLV, and create a new node. We replicate it here // because subclasses of GRTransferFuncs may wish to call it. assert (!TargetLV.isUndef()); if (TargetLV.isUnknown()) Builder.MakeNode(Dst, E, Pred, St); else Builder.MakeNode(Dst, E, Pred, Eng.getStateManager().SetSVal(St, cast<Loc>(TargetLV), Val)); } void GRTransferFuncs::EvalBinOpNN(GRStateSet& OStates, GRStateManager& StateMgr, const GRState *St, Expr* Ex, BinaryOperator::Opcode Op, NonLoc L, NonLoc R) { OStates.Add(StateMgr.SetSVal(St, Ex, DetermEvalBinOpNN(StateMgr, Op, L, R))); } <commit_msg>Fix 80-col.<commit_after>//== GRTransferFuncs.cpp - Path-Sens. Transfer Functions Interface -*- C++ -*--= // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines GRTransferFuncs, which provides a base-class that // defines an interface for transfer functions used by GRExprEngine. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/GRTransferFuncs.h" #include "clang/Analysis/PathSensitive/GRExprEngine.h" using namespace clang; void GRTransferFuncs::RegisterChecks(GRExprEngine& Eng) {} void GRTransferFuncs::EvalStore(ExplodedNodeSet<GRState>& Dst, GRExprEngine& Eng, GRStmtNodeBuilder<GRState>& Builder, Expr* E, ExplodedNode<GRState>* Pred, const GRState* St, SVal TargetLV, SVal Val) { // This code basically matches the "safety-net" logic of GRExprEngine: // bind Val to TargetLV, and create a new node. We replicate it here // because subclasses of GRTransferFuncs may wish to call it. assert (!TargetLV.isUndef()); if (TargetLV.isUnknown()) Builder.MakeNode(Dst, E, Pred, St); else Builder.MakeNode(Dst, E, Pred, Eng.getStateManager().SetSVal(St, cast<Loc>(TargetLV), Val)); } void GRTransferFuncs::EvalBinOpNN(GRStateSet& OStates, GRStateManager& StateMgr, const GRState *St, Expr* Ex, BinaryOperator::Opcode Op, NonLoc L, NonLoc R) { OStates.Add(StateMgr.SetSVal(St, Ex, DetermEvalBinOpNN(StateMgr, Op, L, R))); } <|endoftext|>
<commit_before>include <iostream> #include <climits> using namespace std; class edge; class vertex { public: int value; edge *arry[6]; bool visited; vertex() { value = INT_MAX; visited = false; for(int i = 0; i < 6; i++) { arry[i] = NULL; } } }; class edge { public: int weight; vertex *to; edge() { to = NULL; } }; bool FindSmallest(vertex *vrry[6], int &index) { bool allvisited = true; int smallest; bool onlyonce = false; for(int i = 0; i < 6; i++) { if(vrry[i]->visited == false) { allvisited = false; if(onlyonce == false) { smallest = vrry[i]->value; onlyonce = true; index = i; } if(vrry[i]->value < smallest) { index = i; smallest = vrry[i]->value; } } } return !allvisited; } int main() { //Array to hold vertex vertex *vrry[6]; //Create the graph //Create f vertex *f = new vertex(); //Add f vrry[0] = f; //Create d vertex *d = new vertex(); edge *ed1 = new edge(); ed1->weight = 2; ed1->to = f; d->arry[0] = ed1; //Add d vrry[1] = d; //Create e vertex *e = new vertex(); edge *ee1 = new edge(); ee1->weight = 2; ee1->to = f; e->arry[0] = ee1; edge *ee2 = new edge(); ee2->weight = 3; ee2->to = d; e->arry[1] = ee2; //Add e vrry[2] = e; //Create c vertex *c = new vertex(); edge *ec1 = new edge(); ec1->weight = 3; ec1->to = e; c->arry[0] = ec1; //Add c vrry[3] = c; //Create b vertex *b = new vertex(); edge *eb1 = new edge(); eb1->weight = 4; eb1->to = d; b->arry[0] = eb1; edge *eb2 = new edge(); eb2->weight = 2; eb2->to = e; b->arry[1] = eb2; edge *eb3 = new edge(); eb3->weight = 1; eb3->to = c; b->arry[2] = eb3; //Add b vrry[4] = b; //Create a vertex *a = new vertex(); a->value = 0; edge *ea1 = new edge(); ea1->weight = 2; ea1->to = b; a->arry[0] = ea1; edge *ea2 = new edge(); ea2->weight = 4; ea2->to = c; a->arry[1] = ea2; //Add d vrry[5] = a; //while array is not all visited bool allvisited = false; while(allvisited == false) { //find the smallest value vertex int smallest = 0; if(FindSmallest(vrry, smallest)) { vrry[smallest]->visited = true; //relax the values of vertex int j = 0; while(vrry[smallest]->arry[j] != NULL) { if(vrry[smallest]->value + vrry[smallest]->arry[j]->weight < vrry[smallest]->arry[j]->to->value) { vrry[smallest]->arry[j]->to->value = vrry[smallest]->value + vrry[smallest]->arry[j]->weight; } j++; } } else { allvisited = true; } } cout<<"Done finding shortest paths"<<endl; cout<<c->value; return 0; } <commit_msg>Update dijkstra_simple.cpp<commit_after>#include <iostream> #include <climits> using namespace std; class edge; class vertex { public: int value; edge *arry[6]; bool visited; vertex() { value = INT_MAX; visited = false; for(int i = 0; i < 6; i++) { arry[i] = NULL; } } }; class edge { public: int weight; vertex *to; edge() { to = NULL; } }; bool FindSmallest(vertex *vrry[6], int &index) { bool allvisited = true; int smallest; bool onlyonce = false; for(int i = 0; i < 6; i++) { if(vrry[i]->visited == false) { allvisited = false; if(onlyonce == false) { smallest = vrry[i]->value; onlyonce = true; index = i; } if(vrry[i]->value < smallest) { index = i; smallest = vrry[i]->value; } } } return !allvisited; } int main() { //Array to hold vertex vertex *vrry[6]; //Create the graph //Create f vertex *f = new vertex(); //Add f vrry[0] = f; //Create d vertex *d = new vertex(); edge *ed1 = new edge(); ed1->weight = 2; ed1->to = f; d->arry[0] = ed1; //Add d vrry[1] = d; //Create e vertex *e = new vertex(); edge *ee1 = new edge(); ee1->weight = 2; ee1->to = f; e->arry[0] = ee1; edge *ee2 = new edge(); ee2->weight = 3; ee2->to = d; e->arry[1] = ee2; //Add e vrry[2] = e; //Create c vertex *c = new vertex(); edge *ec1 = new edge(); ec1->weight = 3; ec1->to = e; c->arry[0] = ec1; //Add c vrry[3] = c; //Create b vertex *b = new vertex(); edge *eb1 = new edge(); eb1->weight = 4; eb1->to = d; b->arry[0] = eb1; edge *eb2 = new edge(); eb2->weight = 2; eb2->to = e; b->arry[1] = eb2; edge *eb3 = new edge(); eb3->weight = 1; eb3->to = c; b->arry[2] = eb3; //Add b vrry[4] = b; //Create a vertex *a = new vertex(); a->value = 0; edge *ea1 = new edge(); ea1->weight = 2; ea1->to = b; a->arry[0] = ea1; edge *ea2 = new edge(); ea2->weight = 4; ea2->to = c; a->arry[1] = ea2; //Add d vrry[5] = a; //while array is not all visited bool allvisited = false; while(allvisited == false) { //find the smallest value vertex int smallest = 0; if(FindSmallest(vrry, smallest)) { vrry[smallest]->visited = true; //relax the values of vertex int j = 0; while(vrry[smallest]->arry[j] != NULL) { if(vrry[smallest]->value + vrry[smallest]->arry[j]->weight < vrry[smallest]->arry[j]->to->value) { vrry[smallest]->arry[j]->to->value = vrry[smallest]->value + vrry[smallest]->arry[j]->weight; } j++; } } else { allvisited = true; } } cout<<"Done finding shortest paths"<<endl; cout<<c->value; return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbSensorModelAdapter.h" #include <cassert> #include "otbMacro.h" #include "otbImageKeywordlist.h" #include "projection/ossimProjection.h" #include "projection/ossimSensorModelFactory.h" #include "ossim/ossimPluginProjectionFactory.h" namespace otb { SensorModelAdapter::SensorModelAdapter(): m_SensorModel(NULL), m_UseDEM(false), m_Epsilon(0.0001), m_NbIter(1) // FIXME keeping the original value but... { m_DEMHandler = DEMHandler::New(); } SensorModelAdapter::~SensorModelAdapter() { if (m_SensorModel != NULL) { delete m_SensorModel; m_SensorModel = NULL; } } void SensorModelAdapter::CreateProjection(const ImageKeywordlist& image_kwl) { ossimKeywordlist geom; image_kwl.convertToOSSIMKeywordlist(geom); otbMsgDevMacro(<< "CreateProjection()"); otbMsgDevMacro(<< "* type: " << geom.find("type")); m_SensorModel = ossimSensorModelFactory::instance()->createProjection(geom); if (m_SensorModel == NULL) { m_SensorModel = ossimplugins::ossimPluginProjectionFactory::instance()->createProjection(geom); } } bool SensorModelAdapter::IsValidSensorModel() { if (m_SensorModel == NULL) { return false; } else { return true; } } void SensorModelAdapter::SetDEMDirectory(const std::string& directory) { m_DEMHandler->OpenDEMDirectory(directory); m_UseDEM = true; } void SensorModelAdapter::ForwardTransformPoint(double x, double y, double z, double& lon, double& lat, double& h) const { ossimDpt ossimPoint(x, y); // Calculation ossimGpt ossimGPoint; if (this->m_SensorModel == NULL) { itkExceptionMacro(<< "ForwardTransformPoint(): Invalid Model pointer m_SensorModel == NULL !"); } //Use of DEM: need iteration to reach the correct point if (this->m_UseDEM) { this->m_SensorModel->lineSampleToWorld(ossimPoint, ossimGPoint); lon = ossimGPoint.lon; lat = ossimGPoint.lat; ossimGpt ossimGPointRef = ossimGPoint; double height(0.), heightTmp(0.); double diffHeight = 100; // arbitrary value itk::Point<double, 2> currentPoint; int nbIter = 0; otbMsgDevMacro(<< "USING DEM ! "); while ((diffHeight > m_Epsilon) && (nbIter < m_NbIter)) { otbMsgDevMacro(<< "Iter " << nbIter); if (nbIter != 0) height = heightTmp; heightTmp = this->m_DEMHandler->GetHeightAboveMSL(lon, lat); this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, heightTmp, ossimGPointRef); diffHeight = fabs(heightTmp - height); ++nbIter; } ossimGPoint = ossimGPointRef; } //Altitude of the point is provided (in the sensor coordinate) could be an //average elevation else if (z != -32768) { this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, z, ossimGPoint); } //Otherwise, just don't consider the altitude else { otbMsgDevMacro("The given altitude is corresponds to NoData (value is -32768. We will use 0 as altitude."); this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, 0, ossimGPoint); } lon = ossimGPoint.lon; lat = ossimGPoint.lat; h = ossimGPoint.hgt; } void SensorModelAdapter::InverseTransformPoint(double lon, double lat, double h, double& x, double& y, double& z) const { ossimGpt ossimGPoint(lat, lon); if (this->m_UseDEM) { double height = this->m_DEMHandler->GetHeightAboveMSL(lon, lat); ossimGPoint.height(height); } else if (h != -32768) { ossimGPoint.height(h); } else { otbMsgDevMacro("The given altitude is corresponds to NoData (value is -32768. We will use 0 as altitude."); ossimGPoint.height(0); } ossimDpt ossimDPoint; if (this->m_SensorModel == NULL) { itkExceptionMacro(<< "InverseTransformPoint(): Invalid Model pointer m_SensorModel == NULL !"); } if (ossimGPoint.hgt == -32768) { ossimGPoint.hgt = ossim::nan(); } // Note: the -32768 is only here to show unknown altitude and should never be // passed to ossim assert(ossim::isnan(ossimGPoint.hgt) || (ossimGPoint.hgt > -1000)); this->m_SensorModel->worldToLineSample(ossimGPoint, ossimDPoint); //"worldToLineSample" call "lineSampleHeightToWorld" method for take in care elevation information. x = ossimDPoint.x; y = ossimDPoint.y; z = ossimGPoint.height(); } ossimProjection* SensorModelAdapter::GetOssimModel() //FIXME temporary only { return m_SensorModel; } } <commit_msg>ENH: ossim DEMHandler never returns -32768 + revert use of 0 elevation in ForwardModel and use 2D transform instead<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbSensorModelAdapter.h" #include <cassert> #include "otbMacro.h" #include "otbImageKeywordlist.h" #include "projection/ossimProjection.h" #include "projection/ossimSensorModelFactory.h" #include "ossim/ossimPluginProjectionFactory.h" namespace otb { SensorModelAdapter::SensorModelAdapter(): m_SensorModel(NULL), m_UseDEM(false), m_Epsilon(0.0001), m_NbIter(1) // FIXME keeping the original value but... { m_DEMHandler = DEMHandler::New(); } SensorModelAdapter::~SensorModelAdapter() { if (m_SensorModel != NULL) { delete m_SensorModel; m_SensorModel = NULL; } } void SensorModelAdapter::CreateProjection(const ImageKeywordlist& image_kwl) { ossimKeywordlist geom; image_kwl.convertToOSSIMKeywordlist(geom); otbMsgDevMacro(<< "CreateProjection()"); otbMsgDevMacro(<< "* type: " << geom.find("type")); m_SensorModel = ossimSensorModelFactory::instance()->createProjection(geom); if (m_SensorModel == NULL) { m_SensorModel = ossimplugins::ossimPluginProjectionFactory::instance()->createProjection(geom); } } bool SensorModelAdapter::IsValidSensorModel() { if (m_SensorModel == NULL) { return false; } else { return true; } } void SensorModelAdapter::SetDEMDirectory(const std::string& directory) { m_DEMHandler->OpenDEMDirectory(directory); m_UseDEM = true; } void SensorModelAdapter::ForwardTransformPoint(double x, double y, double z, double& lon, double& lat, double& h) const { ossimDpt ossimPoint(x, y); // Calculation ossimGpt ossimGPoint; if (this->m_SensorModel == NULL) { itkExceptionMacro(<< "ForwardTransformPoint(): Invalid Model pointer m_SensorModel == NULL !"); } //Use of DEM: need iteration to reach the correct point if (this->m_UseDEM) { this->m_SensorModel->lineSampleToWorld(ossimPoint, ossimGPoint); lon = ossimGPoint.lon; lat = ossimGPoint.lat; ossimGpt ossimGPointRef = ossimGPoint; double height(0.), heightTmp(0.); double diffHeight = 100; // arbitrary value itk::Point<double, 2> currentPoint; int nbIter = 0; otbMsgDevMacro(<< "USING DEM ! "); while ((diffHeight > m_Epsilon) && (nbIter < m_NbIter)) { otbMsgDevMacro(<< "Iter " << nbIter); if (nbIter != 0) height = heightTmp; heightTmp = this->m_DEMHandler->GetHeightAboveMSL(lon, lat); this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, heightTmp, ossimGPointRef); diffHeight = fabs(heightTmp - height); ++nbIter; } ossimGPoint = ossimGPointRef; } //Altitude of the point is provided (in the sensor coordinate) could be an //average elevation else if (z != -32768) { this->m_SensorModel->lineSampleHeightToWorld(ossimPoint, z, ossimGPoint); } //Otherwise, just don't consider the altitude else { this->m_SensorModel->lineSampleToWorld(ossimPoint, ossimGPoint); } lon = ossimGPoint.lon; lat = ossimGPoint.lat; h = ossimGPoint.hgt; } void SensorModelAdapter::InverseTransformPoint(double lon, double lat, double h, double& x, double& y, double& z) const { // Initialize with value from the function parameters ossimGpt ossimGPoint(lat, lon, h); // In case a DEM is used, override the elevation parameter by the DEM value if (this->m_UseDEM) { double height = this->m_DEMHandler->GetHeightAboveMSL(lon, lat); // If the DEM handler cannot give the height for the (lon,lat) point, // either because the tile is not available or the value in the tile are all -32768, // it will return ossim::nan() ossimGPoint.height(height); } // If the 'h' parameter is -32768 (case where OTB classes use a default AverageElevation value) if (ossimGPoint.height() == -32768) { otbMsgDevMacro(<< "The given altitude corresponds to NoData (value is -32768)"); ossimGPoint.height( ossim::nan() ); } ossimDpt ossimDPoint; if (this->m_SensorModel == NULL) { itkExceptionMacro(<< "InverseTransformPoint(): Invalid Model pointer m_SensorModel == NULL !"); } // Note: the -32768 is only here to show unknown altitude and should never be // passed to ossim. // We should either have a NaN, either a valid elevation value assert(ossim::isnan(ossimGPoint.height()) || (ossimGPoint.height() > -1000)); this->m_SensorModel->worldToLineSample(ossimGPoint, ossimDPoint); //"worldToLineSample" call "lineSampleHeightToWorld" method for take in care elevation information. x = ossimDPoint.x; y = ossimDPoint.y; z = ossimGPoint.height(); } ossimProjection* SensorModelAdapter::GetOssimModel() //FIXME temporary only { return m_SensorModel; } } <|endoftext|>
<commit_before>#define CDM_CONFIGURE_NAMESPACE a0038876 #include "../../cdm/application/using_boost/cdm.hpp" #include "log.hpp" #include "temporary.hpp" #include <boost/test/unit_test.hpp> #include <silicium/sink/ostream_sink.hpp> #include <ventura/file_operations.hpp> #include <cdm/locate_cache.hpp> namespace { ventura::absolute_path const this_file = *ventura::absolute_path::create(__FILE__); ventura::absolute_path const test = *ventura::parent(this_file); ventura::absolute_path const repository = *ventura::parent(test); } BOOST_AUTO_TEST_CASE(test_using_boost) { cdm::travis_keep_alive_printer keep_travis_alive; ventura::absolute_path const app_source = repository / "application/using_boost"; ventura::absolute_path const tmp = cdm::get_temporary_root_for_testing() / "test_using_boost"; ventura::recreate_directories(tmp, Si::throw_); ventura::absolute_path const module_temporaries = tmp / "build"; ventura::create_directories(module_temporaries, Si::throw_); ventura::absolute_path const application_build_dir = tmp / "using_boost"; ventura::create_directories(application_build_dir, Si::throw_); std::unique_ptr<std::ofstream> log_file = cdm::open_log(application_build_dir / "test_using_boost.txt"); auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(*log_file)); unsigned const cpu_parallelism = #if CDM_TESTS_RUNNING_ON_TRAVIS_CI 2; #else boost::thread::hardware_concurrency(); #endif CDM_CONFIGURE_NAMESPACE::configure( module_temporaries, cdm::locate_cache_for_this_binary(), app_source, application_build_dir, cpu_parallelism, cdm::detect_this_binary_operating_system(CDM_TESTS_RUNNING_ON_TRAVIS_CI, CDM_TESTS_RUNNING_ON_APPVEYOR), cdm::approximate_configuration_of_this_binary(), output); { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_OS_STR("--build")); arguments.emplace_back(SILICIUM_OS_STR(".")); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit)); } { std::vector<Si::os_string> arguments; ventura::relative_path const relative( #ifdef _MSC_VER "Debug/" #endif "using_boost" #ifdef _MSC_VER ".exe" #endif ); BOOST_REQUIRE_EQUAL(0, ventura::run_process(application_build_dir / relative, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit)); } } <commit_msg>shorten a path for Windows<commit_after>#define CDM_CONFIGURE_NAMESPACE a0038876 #include "../../cdm/application/using_boost/cdm.hpp" #include "log.hpp" #include "temporary.hpp" #include <boost/test/unit_test.hpp> #include <silicium/sink/ostream_sink.hpp> #include <ventura/file_operations.hpp> #include <cdm/locate_cache.hpp> namespace { ventura::absolute_path const this_file = *ventura::absolute_path::create(__FILE__); ventura::absolute_path const test = *ventura::parent(this_file); ventura::absolute_path const repository = *ventura::parent(test); } BOOST_AUTO_TEST_CASE(test_using_boost) { cdm::travis_keep_alive_printer keep_travis_alive; ventura::absolute_path const app_source = repository / "application/using_boost"; ventura::absolute_path const tmp = cdm::get_temporary_root_for_testing() / "tub"; ventura::recreate_directories(tmp, Si::throw_); ventura::absolute_path const module_temporaries = tmp / "build"; ventura::create_directories(module_temporaries, Si::throw_); ventura::absolute_path const application_build_dir = tmp / "using_boost"; ventura::create_directories(application_build_dir, Si::throw_); std::unique_ptr<std::ofstream> log_file = cdm::open_log(application_build_dir / "test_using_boost.txt"); auto output = cdm::make_program_output_printer(Si::ostream_ref_sink(*log_file)); unsigned const cpu_parallelism = #if CDM_TESTS_RUNNING_ON_TRAVIS_CI 2; #else boost::thread::hardware_concurrency(); #endif CDM_CONFIGURE_NAMESPACE::configure( module_temporaries, cdm::locate_cache_for_this_binary(), app_source, application_build_dir, cpu_parallelism, cdm::detect_this_binary_operating_system(CDM_TESTS_RUNNING_ON_TRAVIS_CI, CDM_TESTS_RUNNING_ON_APPVEYOR), cdm::approximate_configuration_of_this_binary(), output); { std::vector<Si::os_string> arguments; arguments.emplace_back(SILICIUM_OS_STR("--build")); arguments.emplace_back(SILICIUM_OS_STR(".")); BOOST_REQUIRE_EQUAL(0, ventura::run_process(ventura::cmake_exe, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit)); } { std::vector<Si::os_string> arguments; ventura::relative_path const relative( #ifdef _MSC_VER "Debug/" #endif "using_boost" #ifdef _MSC_VER ".exe" #endif ); BOOST_REQUIRE_EQUAL(0, ventura::run_process(application_build_dir / relative, arguments, application_build_dir, output, std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(), ventura::environment_inheritance::inherit)); } } <|endoftext|>
<commit_before>/* Siconos-sample , Copyright INRIA 2005-2011. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY [email protected] */ /*!\file BouncingBallSchatzmanPaoli.cpp \brief A Ball bouncing on the ground. Direct description of the model without XML input. Simulation with a Time-Stepping scheme. */ #include "SiconosKernel.hpp" using namespace std; int main(int argc, char* argv[]) { try { // ================= Creation of the model ======================= // User-defined main parameters unsigned int nDof = 3; // degrees of freedom for the ball double t0 = 0; // initial computation time double T = 10.0; // final computation time double h = 0.005; // time step double position_init = 1.0; // initial position for lowest bead. double velocity_init = 0.0; // initial velocity for lowest bead. double theta = 0.5; // theta for SP integrator double R = 0.1; // Ball radius double m = 1; // Ball mass double g = 9.81; // Gravity // ------------------------- // --- Dynamical systems --- // ------------------------- cout << "====> Model loading ..." << endl << endl; SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof)); (*Mass)(0, 0) = m; (*Mass)(1, 1) = m; (*Mass)(2, 2) = 3. / 5 * m * R * R; // -- Initial positions and velocities -- SP::SimpleVector q0(new SimpleVector(nDof)); SP::SimpleVector v0(new SimpleVector(nDof)); (*q0)(0) = position_init; (*v0)(0) = velocity_init; // -- The dynamical system -- SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass)); // -- Set external forces (weight) -- SP::SimpleVector weight(new SimpleVector(nDof)); (*weight)(0) = -m * g; ball->setFExtPtr(weight); // -------------------- // --- Interactions --- // -------------------- // -- nslaw -- double e = 0.9; // Interaction ball-floor // SP::SiconosMatrix H(new SimpleMatrix(1, nDof)); (*H)(0, 0) = 1.0; SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e)); SP::Relation relation(new LagrangianLinearTIR(H)); SP::Interaction inter(new Interaction(1, nslaw, relation)); // ------------- // --- Model --- // ------------- SP::Model bouncingBall(new Model(t0, T)); // add the dynamical system in the non smooth dynamical system bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball); // link the interaction and the dynamical system bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball); // ------------------ // --- Simulation --- // ------------------x // -- (1) OneStepIntegrators -- SP::SchatzmanPaoli OSI(new SchatzmanPaoli(ball, theta)); // -- (2) Time discretisation -- SP::TimeDiscretisation t(new TimeDiscretisation(t0, h)); // -- (3) one step non smooth problem SP::OneStepNSProblem osnspb(new LCP()); // -- (4) Simulation setup with (1) (2) (3) SP::TimeStepping s(new TimeStepping(t, OSI, osnspb)); // =========================== End of model definition =========================== // ================================= Computation ================================= // --- Simulation initialization --- cout << "====> Initialisation ..." << endl << endl; bouncingBall->initialize(s); int N = (int)((T - t0) / h); // Number of time steps // --- Get the values to be plotted --- // -> saved in a matrix dataPlot unsigned int outputSize = 5; SimpleMatrix dataPlot(N + 1, outputSize); SP::SiconosVector q = ball->q(); SP::SiconosVector v = ball->velocity(); SP::SiconosVector p = ball->p(0); SP::SiconosVector lambda = inter->lambda(0); //SP::SiconosVector p = ball->q(); //SP::SiconosVector lambda = ball->q() ; dataPlot(0, 0) = bouncingBall->t0(); dataPlot(0, 1) = (*q)(0); dataPlot(0, 2) = (*v)(0); dataPlot(0, 3) = (*p)(0); dataPlot(0, 4) = (*lambda)(0); // --- Time loop --- cout << "====> Start computation ... " << endl << endl; // ==== Simulation loop - Writing without explicit event handling ===== int k = 1; boost::progress_display show_progress(N); boost::timer time; time.restart(); while (s->nextTime() < T) { cout << "iteration " << k << endl; s->computeOneStep(); osnspb->display(); ball->velocity()->display(); // --- Get values to be plotted --- dataPlot(k, 0) = s->nextTime(); dataPlot(k, 1) = (*q)(0); dataPlot(k, 2) = (*v)(0); dataPlot(k, 3) = (*p)(0); dataPlot(k, 4) = (*lambda)(0); s->nextStep(); ++show_progress; k++; } cout << endl << "End of computation - Number of iterations done: " << k - 1 << endl; cout << "Computation Time " << time.elapsed() << endl; // --- Output files --- cout << "====> Output file writing ..." << endl; ioMatrix io("result.dat", "ascii"); dataPlot.resize(k, outputSize); io.write(dataPlot, "NoDim"); // Comparison with a reference file SimpleMatrix dataPlotRef(dataPlot); dataPlotRef.zero(); ioMatrix ref("BouncingBallSchatzmanPaoli.ref", "ascii"); ref.read(dataPlotRef); if ((dataPlot - dataPlotRef).normInf() > 1e-12) { std::cout << "Warning. The results is rather different from the reference file." << std::endl; return 1; } } catch (SiconosException e) { cout << e.report() << endl; } catch (...) { cout << "Exception caught in BouncingBallTS.cpp" << endl; } } <commit_msg>Example less verbose<commit_after>/* Siconos-sample , Copyright INRIA 2005-2011. * Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * Siconos is a free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * Siconos is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Siconos; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Contact: Vincent ACARY [email protected] */ /*!\file BouncingBallSchatzmanPaoli.cpp \brief A Ball bouncing on the ground. Direct description of the model without XML input. Simulation with a Time-Stepping scheme. */ #include "SiconosKernel.hpp" using namespace std; int main(int argc, char* argv[]) { try { // ================= Creation of the model ======================= // User-defined main parameters unsigned int nDof = 3; // degrees of freedom for the ball double t0 = 0; // initial computation time double T = 10.0; // final computation time double h = 0.005; // time step double position_init = 1.0; // initial position for lowest bead. double velocity_init = 0.0; // initial velocity for lowest bead. double theta = 0.5; // theta for SP integrator double R = 0.1; // Ball radius double m = 1; // Ball mass double g = 9.81; // Gravity // ------------------------- // --- Dynamical systems --- // ------------------------- cout << "====> Model loading ..." << endl << endl; SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof)); (*Mass)(0, 0) = m; (*Mass)(1, 1) = m; (*Mass)(2, 2) = 3. / 5 * m * R * R; // -- Initial positions and velocities -- SP::SimpleVector q0(new SimpleVector(nDof)); SP::SimpleVector v0(new SimpleVector(nDof)); (*q0)(0) = position_init; (*v0)(0) = velocity_init; // -- The dynamical system -- SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass)); // -- Set external forces (weight) -- SP::SimpleVector weight(new SimpleVector(nDof)); (*weight)(0) = -m * g; ball->setFExtPtr(weight); // -------------------- // --- Interactions --- // -------------------- // -- nslaw -- double e = 0.9; // Interaction ball-floor // SP::SiconosMatrix H(new SimpleMatrix(1, nDof)); (*H)(0, 0) = 1.0; SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e)); SP::Relation relation(new LagrangianLinearTIR(H)); SP::Interaction inter(new Interaction(1, nslaw, relation)); // ------------- // --- Model --- // ------------- SP::Model bouncingBall(new Model(t0, T)); // add the dynamical system in the non smooth dynamical system bouncingBall->nonSmoothDynamicalSystem()->insertDynamicalSystem(ball); // link the interaction and the dynamical system bouncingBall->nonSmoothDynamicalSystem()->link(inter, ball); // ------------------ // --- Simulation --- // ------------------x // -- (1) OneStepIntegrators -- SP::SchatzmanPaoli OSI(new SchatzmanPaoli(ball, theta)); // -- (2) Time discretisation -- SP::TimeDiscretisation t(new TimeDiscretisation(t0, h)); // -- (3) one step non smooth problem SP::OneStepNSProblem osnspb(new LCP()); // -- (4) Simulation setup with (1) (2) (3) SP::TimeStepping s(new TimeStepping(t, OSI, osnspb)); // =========================== End of model definition =========================== // ================================= Computation ================================= // --- Simulation initialization --- cout << "====> Initialisation ..." << endl << endl; bouncingBall->initialize(s); OSI->interactions()->display(); int N = (int)((T - t0) / h); // Number of time steps // --- Get the values to be plotted --- // -> saved in a matrix dataPlot unsigned int outputSize = 5; SimpleMatrix dataPlot(N + 1, outputSize); SP::SiconosVector q = ball->q(); SP::SiconosVector v = ball->velocity(); SP::SiconosVector p = ball->p(0); SP::SiconosVector lambda = inter->lambda(0); //SP::SiconosVector p = ball->q(); //SP::SiconosVector lambda = ball->q() ; dataPlot(0, 0) = bouncingBall->t0(); dataPlot(0, 1) = (*q)(0); dataPlot(0, 2) = (*v)(0); dataPlot(0, 3) = (*p)(0); dataPlot(0, 4) = (*lambda)(0); // --- Time loop --- cout << "====> Start computation ... " << endl << endl; // ==== Simulation loop - Writing without explicit event handling ===== int k = 1; boost::progress_display show_progress(N); boost::timer time; time.restart(); while (s->nextTime() < T) { //cout << "iteration " << k <<endl; s->computeOneStep(); // osnspb->display(); // ball->velocity()->display(); // inter->display(); // --- Get values to be plotted --- dataPlot(k, 0) = s->nextTime(); dataPlot(k, 1) = (*q)(0); dataPlot(k, 2) = (*v)(0); dataPlot(k, 3) = (*p)(0); dataPlot(k, 4) = (*lambda)(0); s->nextStep(); ++show_progress; k++; } cout << endl << "End of computation - Number of iterations done: " << k - 1 << endl; cout << "Computation Time " << time.elapsed() << endl; // --- Output files --- cout << "====> Output file writing ..." << endl; ioMatrix io("result.dat", "ascii"); dataPlot.resize(k, outputSize); io.write(dataPlot, "noDim"); // Comparison with a reference file SimpleMatrix dataPlotRef(dataPlot); dataPlotRef.zero(); ioMatrix ref("BouncingBallSchatzmanPaoli.ref", "ascii"); ref.read(dataPlotRef); if ((dataPlot - dataPlotRef).normInf() > 1e-12) { std::cout << "Warning. The results is rather different from the reference file." << std::endl; std::cout << "Error = " << (dataPlot - dataPlotRef).normInf() << std::endl; (dataPlot - dataPlotRef).display(); return 1; } } catch (SiconosException e) { cout << e.report() << endl; } catch (...) { cout << "Exception caught in BouncingBallTS.cpp" << endl; } } <|endoftext|>
<commit_before>// Paul Smith 1 March 2005 // Uses ffmpeg libraries to play most types of video file #include <string> #include <sstream> #include <cvd/exceptions.h> #include <cvd/videofilebuffer.h> using namespace std; namespace CVD { using namespace Exceptions::VideoFileBuffer; // // EXCEPTIONS // Exceptions::VideoFileBuffer::FileOpen::FileOpen(const std::string& name, const string& error) { what = "RawVideoFileBuffer: Error opening file \"" + name + "\": " + error; } Exceptions::VideoFileBuffer::BadFrameAlloc::BadFrameAlloc() { what = "RawVideoFileBuffer: Unable to allocate video frame."; } Exceptions::VideoFileBuffer::BadDecode::BadDecode(double t) { ostringstream os; os << "RawVideoFileBuffer: Error decoding video frame at time " << t << "."; what = os.str(); } Exceptions::VideoFileBuffer::EndOfFile::EndOfFile() { what = "RawVideoFileBuffer: Tried to read off the end of the file."; } Exceptions::VideoFileBuffer::BadSeek::BadSeek(double t) { ostringstream ss; ss << "RawVideoFileBuffer: Seek to time " << t << "s failed."; what = ss.str(); } namespace VFB { // // CONSTRUCTOR // RawVideoFileBuffer::RawVideoFileBuffer(const std::string& file, bool rgbp) : end_of_buffer_behaviour(VideoBufferFlags::RepeatLastFrame), pFormatContext(0), pCodecContext(0), pFrame(0), pFrameRGB(0), //buffer(0), frame_time(0.0), is_rgb(rgbp) { try { // Register the formats and codecs av_register_all(); // Now open the video file (and read the header, if present) if(av_open_input_file(&pFormatContext, file.c_str(), NULL, 0, NULL) != 0) throw FileOpen(file, "File could not be opened."); // Read the beginning of the file to get stream information (in case there is no header) if(av_find_stream_info(pFormatContext) < 0) throw FileOpen(file, "Stream information could not be read."); // Dump details of the video to standard error dump_format(pFormatContext, 0, file.c_str(), false); // We shall just use the first video stream video_stream = -1; for(int i=0; i < pFormatContext->nb_streams && video_stream == -1; i++) { if(pFormatContext->streams[i]->codec.codec_type == CODEC_TYPE_VIDEO) video_stream = i; // Found one! } if(video_stream == -1) throw FileOpen(file, "No video stream found."); // Get the codec context for this video stream pCodecContext = &(pFormatContext->streams[video_stream]->codec); // Find the decoder for the video stream AVCodec* pCodec = avcodec_find_decoder(pCodecContext->codec_id); if(pCodec == NULL) { pCodecContext = 0; // Since it's not been opened yet throw FileOpen(file, "No appropriate codec could be found."); } // Open codec if(avcodec_open(pCodecContext, pCodec) < 0) { pCodecContext = 0; // Since it's not been opened yet throw FileOpen(file, string(pCodec->name) + " codec could not be initialised."); } // Hack to fix wrong frame rates if(pCodecContext->frame_rate > 1000 && pCodecContext->frame_rate_base == 1) pCodecContext->frame_rate_base = 1000; // Allocate video frame pFrame = avcodec_alloc_frame(); if(pFrame == NULL) throw BadFrameAlloc(); // And a frame to hold the RGB version pFrameRGB = avcodec_alloc_frame(); if(pFrameRGB == NULL) throw BadFrameAlloc(); // How big is the buffer? //long num_bytes = avpicture_get_size(PIX_FMT_RGB24, pCodecContext->width, pCodecContext->height); my_size = ImageRef(pCodecContext->width, pCodecContext->height); // And allocate a contiguous buffer //buffer = new CVD::Rgb<CVD::byte>[my_size.x * my_size.y]; // Assign this buffer to image planes in pFrameRGB //avpicture_fill((AVPicture *)pFrameRGB, reinterpret_cast<uint8_t*>(buffer), PIX_FMT_RGB24, pCodecContext->width, pCodecContext->height); // Now read the first frame if(!read_next_frame()) throw EndOfFile(); start_time = 0; frame_ready = true; } catch(CVD::Exceptions::All) { // Tidy things up on the heap if we failed part-way through constructing if(pFormatContext != 0) av_close_input_file(pFormatContext); if(pCodecContext != 0) avcodec_close(pCodecContext); if(pFrame != 0) av_free(pFrame); if(pFrameRGB != 0) av_free(pFrameRGB); //if(buffer != 0) // delete[] buffer; // Now re-throw throw; } } // // DESTRUCTOR // RawVideoFileBuffer::~RawVideoFileBuffer() { //delete [] buffer; av_free(pFrameRGB); av_free(pFrame); avcodec_close(pCodecContext); av_close_input_file(pFormatContext); } // // READ NEXT FRAME // bool RawVideoFileBuffer::read_next_frame() { //Make next_frame point to a new block of data, getting the sizes correct. if(is_rgb) { Image<Rgb<byte> > tmp(my_size); next_frame = (reinterpret_cast<Image<byte>&>(tmp)); } else { Image<byte> tmp(my_size); next_frame = tmp; } //Assign this new memory block avpicture_fill((AVPicture *)pFrameRGB, reinterpret_cast<uint8_t*>(next_frame.data()), is_rgb?PIX_FMT_RGB24:PIX_FMT_GRAY8, pCodecContext->width, pCodecContext->height); AVPacket packet; packet.stream_index = -1; // How many frames do we read looking for our video stream? // If we assume our streams are interlaced, and some might be interlaced // 2:1, this should probably do const int max_loop = MAX_STREAMS * 2; int i; for(i = 0; packet.stream_index != video_stream && i < max_loop; i++) { if(av_read_frame(pFormatContext, &packet) < 0) return false; if(packet.stream_index == video_stream) { // Ask this packet what time it is if(packet.pts >= 0) frame_time = packet.pts / static_cast<double>(AV_TIME_BASE); else // sometimes this is reported incorrectly, so guess { frame_time = frame_time + 1.0 / frames_per_second(); } // Decode video frame int got_picture; if(avcodec_decode_video(pCodecContext, pFrame, &got_picture, packet.data, packet.size) == -1) { throw BadDecode(frame_time); } // Did we get a video frame? if(got_picture) { // Convert the image from its native format to RGB img_convert((AVPicture *)pFrameRGB, is_rgb?PIX_FMT_RGB24:PIX_FMT_GRAY8, (AVPicture*)pFrame, pCodecContext->pix_fmt, pCodecContext->width, pCodecContext->height); } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); } // Did we not find one? if(i == max_loop) return false; return true; } // // GET FRAME // VideoFileFrame<byte>* RawVideoFileBuffer::get_frame() { if(!frame_pending()) throw EndOfFile(); // Don't use - pCC->frame_number doesn't reset after a seek! // Instead, we ask the packet its time when we decode it // double time = start_time + pCodecContext->frame_number * pCodecContext->frame_rate_base / static_cast<double>(pCodecContext->frame_rate); VideoFileFrame<byte>* vf = new VideoFileFrame<byte>(frame_time, next_frame); if(!read_next_frame()) { switch(end_of_buffer_behaviour) { case VideoBufferFlags::RepeatLastFrame: // Just do nothing--last frame will still be there // FIXME: trashing the frame will make get_frame() return a trashed frame break; case VideoBufferFlags::UnsetPending: frame_ready = false; break; case VideoBufferFlags::Loop: seek_to(start_time); break; } } return vf; } // // PUT FRAME // void RawVideoFileBuffer::put_frame(VideoFrame<byte>* f) { VideoFileFrame<byte>* vff = dynamic_cast<VideoFileFrame<byte> *>(f); if(!vff) throw Exceptions::VideoBuffer::BadPutFrame(); else delete vff; } // // SEEK TO // void RawVideoFileBuffer::seek_to(double t) { if(av_seek_frame(pFormatContext, -1, static_cast<int64_t>(t*AV_TIME_BASE+0.5)) < 0) { cerr << "av_seek_frame not supported by this codec: performing (slow) manual seek" << endl; // Seeking is not properly sorted with some codecs // Fudge it by closing the file and starting again, stepping through the frames string file = pFormatContext->filename; av_close_input_file(pFormatContext); avcodec_close(pCodecContext); // Now open the video file (and read the header, if present) if(av_open_input_file(&pFormatContext, file.c_str(), NULL, 0, NULL) != 0) throw FileOpen(file, "File could not be opened."); // Read the beginning of the file to get stream information (in case there is no header) if(av_find_stream_info(pFormatContext) < 0) throw FileOpen(file, "Stream information could not be read."); // No need to find the stream--we know which one it is (in video_stream) // Get the codec context for this video stream pCodecContext = &(pFormatContext->streams[video_stream]->codec); // Find the decoder for the video stream AVCodec* pCodec = avcodec_find_decoder(pCodecContext->codec_id); if(pCodec == NULL) { pCodecContext = 0; // Since it's not been opened yet throw FileOpen(file, "No appropriate codec could be found."); } // Open codec if(avcodec_open(pCodecContext, pCodec) < 0) { pCodecContext = 0; // Since it's not been opened yet throw FileOpen(file, string(pCodec->name) + " codec could not be initialised."); } // Hack to fix wrong frame rates if(pCodecContext->frame_rate > 1000 && pCodecContext->frame_rate_base == 1) pCodecContext->frame_rate_base = 1000; start_time = 0; frame_ready = true; // REOPENED FILE OK // Now read frames until we get to the time we want int frames = static_cast<int>((t * frames_per_second() + 0.5)); for(int i = 0; i < frames; i++) { read_next_frame(); } } if(!read_next_frame()) throw BadSeek(t); } } } // namespace CVD <commit_msg>Fixed RepeatLastFrame behaviour<commit_after>// Paul Smith 1 March 2005 // Uses ffmpeg libraries to play most types of video file #include <string> #include <sstream> #include <cvd/exceptions.h> #include <cvd/videofilebuffer.h> using namespace std; namespace CVD { using namespace Exceptions::VideoFileBuffer; // // EXCEPTIONS // Exceptions::VideoFileBuffer::FileOpen::FileOpen(const std::string& name, const string& error) { what = "RawVideoFileBuffer: Error opening file \"" + name + "\": " + error; } Exceptions::VideoFileBuffer::BadFrameAlloc::BadFrameAlloc() { what = "RawVideoFileBuffer: Unable to allocate video frame."; } Exceptions::VideoFileBuffer::BadDecode::BadDecode(double t) { ostringstream os; os << "RawVideoFileBuffer: Error decoding video frame at time " << t << "."; what = os.str(); } Exceptions::VideoFileBuffer::EndOfFile::EndOfFile() { what = "RawVideoFileBuffer: Tried to read off the end of the file."; } Exceptions::VideoFileBuffer::BadSeek::BadSeek(double t) { ostringstream ss; ss << "RawVideoFileBuffer: Seek to time " << t << "s failed."; what = ss.str(); } namespace VFB { // // CONSTRUCTOR // RawVideoFileBuffer::RawVideoFileBuffer(const std::string& file, bool rgbp) : end_of_buffer_behaviour(VideoBufferFlags::RepeatLastFrame), pFormatContext(0), pCodecContext(0), pFrame(0), pFrameRGB(0), //buffer(0), frame_time(0.0), is_rgb(rgbp) { try { // Register the formats and codecs av_register_all(); // Now open the video file (and read the header, if present) if(av_open_input_file(&pFormatContext, file.c_str(), NULL, 0, NULL) != 0) throw FileOpen(file, "File could not be opened."); // Read the beginning of the file to get stream information (in case there is no header) if(av_find_stream_info(pFormatContext) < 0) throw FileOpen(file, "Stream information could not be read."); // Dump details of the video to standard error dump_format(pFormatContext, 0, file.c_str(), false); // We shall just use the first video stream video_stream = -1; for(int i=0; i < pFormatContext->nb_streams && video_stream == -1; i++) { if(pFormatContext->streams[i]->codec.codec_type == CODEC_TYPE_VIDEO) video_stream = i; // Found one! } if(video_stream == -1) throw FileOpen(file, "No video stream found."); // Get the codec context for this video stream pCodecContext = &(pFormatContext->streams[video_stream]->codec); // Find the decoder for the video stream AVCodec* pCodec = avcodec_find_decoder(pCodecContext->codec_id); if(pCodec == NULL) { pCodecContext = 0; // Since it's not been opened yet throw FileOpen(file, "No appropriate codec could be found."); } // Open codec if(avcodec_open(pCodecContext, pCodec) < 0) { pCodecContext = 0; // Since it's not been opened yet throw FileOpen(file, string(pCodec->name) + " codec could not be initialised."); } // Hack to fix wrong frame rates if(pCodecContext->frame_rate > 1000 && pCodecContext->frame_rate_base == 1) pCodecContext->frame_rate_base = 1000; // Allocate video frame pFrame = avcodec_alloc_frame(); if(pFrame == NULL) throw BadFrameAlloc(); // And a frame to hold the RGB version pFrameRGB = avcodec_alloc_frame(); if(pFrameRGB == NULL) throw BadFrameAlloc(); // How big is the buffer? //long num_bytes = avpicture_get_size(PIX_FMT_RGB24, pCodecContext->width, pCodecContext->height); my_size = ImageRef(pCodecContext->width, pCodecContext->height); // And allocate a contiguous buffer //buffer = new CVD::Rgb<CVD::byte>[my_size.x * my_size.y]; // Assign this buffer to image planes in pFrameRGB //avpicture_fill((AVPicture *)pFrameRGB, reinterpret_cast<uint8_t*>(buffer), PIX_FMT_RGB24, pCodecContext->width, pCodecContext->height); // Now read the first frame if(!read_next_frame()) throw EndOfFile(); start_time = 0; frame_ready = true; } catch(CVD::Exceptions::All) { // Tidy things up on the heap if we failed part-way through constructing if(pFormatContext != 0) av_close_input_file(pFormatContext); if(pCodecContext != 0) avcodec_close(pCodecContext); if(pFrame != 0) av_free(pFrame); if(pFrameRGB != 0) av_free(pFrameRGB); //if(buffer != 0) // delete[] buffer; // Now re-throw throw; } } // // DESTRUCTOR // RawVideoFileBuffer::~RawVideoFileBuffer() { //delete [] buffer; av_free(pFrameRGB); av_free(pFrame); avcodec_close(pCodecContext); av_close_input_file(pFormatContext); } // // READ NEXT FRAME // bool RawVideoFileBuffer::read_next_frame() { //Make next_frame point to a new block of data, getting the sizes correct. if(is_rgb) { Image<Rgb<byte> > tmp(my_size); next_frame = (reinterpret_cast<Image<byte>&>(tmp)); } else { Image<byte> tmp(my_size); next_frame = tmp; } //Assign this new memory block avpicture_fill((AVPicture *)pFrameRGB, reinterpret_cast<uint8_t*>(next_frame.data()), is_rgb?PIX_FMT_RGB24:PIX_FMT_GRAY8, pCodecContext->width, pCodecContext->height); AVPacket packet; packet.stream_index = -1; // How many frames do we read looking for our video stream? // If we assume our streams are interlaced, and some might be interlaced // 2:1, this should probably do const int max_loop = MAX_STREAMS * 2; int i; for(i = 0; packet.stream_index != video_stream && i < max_loop; i++) { if(av_read_frame(pFormatContext, &packet) < 0) return false; if(packet.stream_index == video_stream) { // Ask this packet what time it is if(packet.pts >= 0) frame_time = packet.pts / static_cast<double>(AV_TIME_BASE); else // sometimes this is reported incorrectly, so guess { frame_time = frame_time + 1.0 / frames_per_second(); } // Decode video frame int got_picture; if(avcodec_decode_video(pCodecContext, pFrame, &got_picture, packet.data, packet.size) == -1) { throw BadDecode(frame_time); } // Did we get a video frame? if(got_picture) { // Convert the image from its native format to RGB img_convert((AVPicture *)pFrameRGB, is_rgb?PIX_FMT_RGB24:PIX_FMT_GRAY8, (AVPicture*)pFrame, pCodecContext->pix_fmt, pCodecContext->width, pCodecContext->height); } } // Free the packet that was allocated by av_read_frame av_free_packet(&packet); } // Did we not find one? if(i == max_loop) return false; return true; } // // GET FRAME // VideoFileFrame<byte>* RawVideoFileBuffer::get_frame() { if(!frame_pending()) throw EndOfFile(); // Don't use - pCC->frame_number doesn't reset after a seek! // Instead, we ask the packet its time when we decode it // double time = start_time + pCodecContext->frame_number * pCodecContext->frame_rate_base / static_cast<double>(pCodecContext->frame_rate); VideoFileFrame<byte>* vf = new VideoFileFrame<byte>(frame_time, next_frame); if(!read_next_frame()) { switch(end_of_buffer_behaviour) { case VideoBufferFlags::RepeatLastFrame: // next_frame is empty because there isn't one, so // I'll copy the one that I'm about to return so that // I can return it next time as well if(is_rgb) { Image<Rgb<byte> > tmp = reinterpret_cast<Image<Rgb<byte> >&>(next_frame); tmp.copy_from(reinterpret_cast<VideoFileFrame<Rgb<byte> >&>(*vf)); next_frame = (reinterpret_cast<Image<byte>&>(tmp)); } else { next_frame.copy_from(*vf); } break; case VideoBufferFlags::UnsetPending: frame_ready = false; break; case VideoBufferFlags::Loop: seek_to(start_time); break; } } return vf; } // // PUT FRAME // void RawVideoFileBuffer::put_frame(VideoFrame<byte>* f) { VideoFileFrame<byte>* vff = dynamic_cast<VideoFileFrame<byte> *>(f); if(!vff) throw Exceptions::VideoBuffer::BadPutFrame(); else delete vff; } // // SEEK TO // void RawVideoFileBuffer::seek_to(double t) { if(av_seek_frame(pFormatContext, -1, static_cast<int64_t>(t*AV_TIME_BASE+0.5)) < 0) { cerr << "av_seek_frame not supported by this codec: performing (slow) manual seek" << endl; // Seeking is not properly sorted with some codecs // Fudge it by closing the file and starting again, stepping through the frames string file = pFormatContext->filename; av_close_input_file(pFormatContext); avcodec_close(pCodecContext); // Now open the video file (and read the header, if present) if(av_open_input_file(&pFormatContext, file.c_str(), NULL, 0, NULL) != 0) throw FileOpen(file, "File could not be opened."); // Read the beginning of the file to get stream information (in case there is no header) if(av_find_stream_info(pFormatContext) < 0) throw FileOpen(file, "Stream information could not be read."); // No need to find the stream--we know which one it is (in video_stream) // Get the codec context for this video stream pCodecContext = &(pFormatContext->streams[video_stream]->codec); // Find the decoder for the video stream AVCodec* pCodec = avcodec_find_decoder(pCodecContext->codec_id); if(pCodec == NULL) { pCodecContext = 0; // Since it's not been opened yet throw FileOpen(file, "No appropriate codec could be found."); } // Open codec if(avcodec_open(pCodecContext, pCodec) < 0) { pCodecContext = 0; // Since it's not been opened yet throw FileOpen(file, string(pCodec->name) + " codec could not be initialised."); } // Hack to fix wrong frame rates if(pCodecContext->frame_rate > 1000 && pCodecContext->frame_rate_base == 1) pCodecContext->frame_rate_base = 1000; start_time = 0; frame_ready = true; // REOPENED FILE OK // Now read frames until we get to the time we want int frames = static_cast<int>((t * frames_per_second() + 0.5)); for(int i = 0; i < frames; i++) { read_next_frame(); } } if(!read_next_frame()) throw BadSeek(t); } } } // namespace CVD <|endoftext|>
<commit_before>// // Copyright (c) 2015-2016 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_python_algorithm_hpp__ #define __se3_python_algorithm_hpp__ #include <eigenpy/exception.hpp> #include <eigenpy/eigenpy.hpp> #include "pinocchio/python/model.hpp" #include "pinocchio/python/data.hpp" #include "pinocchio/algorithm/rnea.hpp" #include "pinocchio/algorithm/non-linear-effects.hpp" #include "pinocchio/algorithm/crba.hpp" #include "pinocchio/algorithm/kinematics.hpp" #include "pinocchio/algorithm/jacobian.hpp" #include "pinocchio/algorithm/center-of-mass.hpp" #include "pinocchio/algorithm/joint-limits.hpp" #include "pinocchio/algorithm/energy.hpp" #include "pinocchio/simulation/compute-all-terms.hpp" #ifdef WITH_HPP_FCL #include "pinocchio/multibody/geometry.hpp" #include "pinocchio/python/geometry-model.hpp" #include "pinocchio/python/geometry-data.hpp" #include "pinocchio/algorithm/collisions.hpp" #endif namespace se3 { namespace python { struct AlgorithmsPythonVisitor { typedef eigenpy::UnalignedEquivalent<Eigen::VectorXd>::type VectorXd_fx; static Eigen::VectorXd rnea_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & qd, const VectorXd_fx & qdd ) { return rnea(*model,*data,q,qd,qdd); } static Eigen::VectorXd nle_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & qd ) { return nonLinearEffects(*model,*data,q,qd); } static Eigen::MatrixXd crba_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q ) { data->M.fill(0); crba(*model,*data,q); data->M.triangularView<Eigen::StrictlyLower>() = data->M.transpose().triangularView<Eigen::StrictlyLower>(); return data->M; } static Eigen::VectorXd com_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q ) { return centerOfMass(*model,*data,q); } static void com_acceleration_proxy(const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & v, const VectorXd_fx & a) { return centerOfMassAcceleration(*model,*data,q,v,a); } static Eigen::MatrixXd Jcom_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q ) { return jacobianCenterOfMass(*model,*data,q); } static Eigen::MatrixXd jacobian_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, Model::Index jointId, bool local, bool update_geometry ) { Eigen::MatrixXd J( 6,model->nv ); J.setZero(); if (update_geometry) computeJacobians( *model,*data,q ); if(local) getJacobian<true> (*model, *data, jointId, J); else getJacobian<false> (*model, *data, jointId, J); return J; } static void compute_jacobians_proxy(const ModelHandler& model, DataHandler & data, const VectorXd_fx & q) { computeJacobians( *model,*data,q ); } static void fk_0_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q) { forwardKinematics(*model,*data,q); } static void fk_1_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & qdot ) { forwardKinematics(*model,*data,q,qdot); } static void fk_2_proxy(const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & v, const VectorXd_fx & a) { forwardKinematics(*model,*data,q,v,a); } static void computeAllTerms_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & v) { data->M.fill(0); computeAllTerms(*model,*data,q,v); data->M.triangularView<Eigen::StrictlyLower>() = data->M.transpose().triangularView<Eigen::StrictlyLower>(); } static void jointLimits_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q) { jointLimits(*model,*data,q); } static double kineticEnergy_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & v, const bool update_kinematics = true) { return kineticEnergy(*model,*data,q,v,update_kinematics); } static double potentialEnergy_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q, const bool update_kinematics = true) { return potentialEnergy(*model,*data,q,update_kinematics); } #ifdef WITH_HPP_FCL static bool computeCollisions_proxy(GeometryDataHandler & data_geom, const bool stopAtFirstCollision) { return computeCollisions(*data_geom, stopAtFirstCollision); } static bool computeGeometryAndCollisions_proxy(const ModelHandler & model, DataHandler & data, const GeometryModelHandler & model_geom, GeometryDataHandler & data_geom, const VectorXd_fx & q, const bool & stopAtFirstCollision) { return computeCollisions(*model,*data,*model_geom, *data_geom, q, stopAtFirstCollision); } static void computeDistances_proxy(GeometryDataHandler & data_geom) { computeDistances(*data_geom); } static void computeGeometryAndDistances_proxy( const ModelHandler & model, DataHandler & data, const GeometryModelHandler & model_geom, GeometryDataHandler & data_geom, const Eigen::VectorXd & q ) { computeDistances(*model, *data, *model_geom, *data_geom, q); } #endif /* --- Expose --------------------------------------------------------- */ static void expose() { bp::def("rnea",rnea_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity qdot (size Model::nv)", "Acceleration qddot (size Model::nv)"), "Compute the RNEA, put the result in Data and return it."); bp::def("nle",nle_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity qdot (size Model::nv)"), "Compute the Non Linear Effects (coriolis, centrifugal and gravitational effects), put the result in Data and return it."); bp::def("crba",crba_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute CRBA, put the result in Data and return it."); bp::def("centerOfMass",com_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute the center of mass, putting the result in Data and return it."); bp::def("centerOfMassAcceleration",com_acceleration_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)", "Acceleration a (size Model::nv)"), "Compute the center of mass position, velocity and acceleration andputting the result in Data."); bp::def("jacobianCenterOfMass",Jcom_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute the jacobian of the center of mass, put the result in Data and return it."); bp::def("kinematics",fk_1_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)"), "Compute the placements and spatial velocities of all the frames of the kinematic " "tree and put the results in data."); bp::def("geometry",fk_0_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute the placements of all the frames of the kinematic " "tree and put the results in data."); bp::def("dynamics",fk_2_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)", "Acceleration a (size Model::nv)"), "Compute the placements, spatial velocities and spatial accelerations of all the frames of the kinematic " "tree and put the results in data."); bp::def("computeAllTerms",computeAllTerms_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)"), "Compute all the terms M, non linear effects and Jacobians in" "in the same loop and put the results in data."); bp::def("jacobian",jacobian_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Joint ID (int)", "frame (true = local, false = world)", "update_geometry (true = update the value of the total jacobian)"), "Calling computeJacobians then getJacobian, return the result. Attention: the " "function computes indeed all the jacobians of the model, even if just outputing " "the demanded one if update_geometry is set to false. It is therefore outrageously costly wrt a dedicated " "call. Function to be used only for prototyping."); bp::def("computeJacobians",compute_jacobians_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Calling computeJacobians"); bp::def("jointLimits",jointLimits_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute the maximum limits of all the joints of the model " "and put the results in data."); bp::def("kineticEnergy",kineticEnergy_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)", "Update kinematics (bool)"), "Compute the kinematic energy of the model for the " "given joint configuration and velocity and store it " " in data.kinetic_energy. By default, the kinematics of model is updated."); bp::def("potentialEnergy",potentialEnergy_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Update kinematics (bool)"), "Compute the potential energy of the model for the " "given the joint configuration and store it " " in data.potential_energy. By default, the kinematics of model is updated."); #ifdef WITH_HPP_FCL bp::def("computeCollisions",computeCollisions_proxy, bp::args("GeometryData","bool"), "Determine if collisions pairs are effectively in collision." ); bp::def("computeGeometryAndCollisions",computeGeometryAndCollisions_proxy, bp::args("Model","Data","GeometryModel","GeometryData","Configuration q (size Model::nq)", "bool"), "Update the geometry for a given configuration and" "determine if collision pars are effectively in collision" ); bp::def("computeDistances",computeDistances_proxy, bp::args("GeometryData"), "Compute the distance between each collision pairs." ); bp::def("computeGeometryAndDistances",computeGeometryAndDistances_proxy, bp::args("Model","Data","GeometryModel","GeometryData","Configuration q (size Model::nq)"), "Update the geometry for a given configuration and" "compute the distance between each collision pairs" ); #endif } }; }} // namespace se3::python #endif // ifndef __se3_python_data_hpp__ <commit_msg>[Doc] Correct documentation of geometry algo<commit_after>// // Copyright (c) 2015-2016 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_python_algorithm_hpp__ #define __se3_python_algorithm_hpp__ #include <eigenpy/exception.hpp> #include <eigenpy/eigenpy.hpp> #include "pinocchio/python/model.hpp" #include "pinocchio/python/data.hpp" #include "pinocchio/algorithm/rnea.hpp" #include "pinocchio/algorithm/non-linear-effects.hpp" #include "pinocchio/algorithm/crba.hpp" #include "pinocchio/algorithm/kinematics.hpp" #include "pinocchio/algorithm/jacobian.hpp" #include "pinocchio/algorithm/center-of-mass.hpp" #include "pinocchio/algorithm/joint-limits.hpp" #include "pinocchio/algorithm/energy.hpp" #include "pinocchio/simulation/compute-all-terms.hpp" #ifdef WITH_HPP_FCL #include "pinocchio/multibody/geometry.hpp" #include "pinocchio/python/geometry-model.hpp" #include "pinocchio/python/geometry-data.hpp" #include "pinocchio/algorithm/collisions.hpp" #endif namespace se3 { namespace python { struct AlgorithmsPythonVisitor { typedef eigenpy::UnalignedEquivalent<Eigen::VectorXd>::type VectorXd_fx; static Eigen::VectorXd rnea_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & qd, const VectorXd_fx & qdd ) { return rnea(*model,*data,q,qd,qdd); } static Eigen::VectorXd nle_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & qd ) { return nonLinearEffects(*model,*data,q,qd); } static Eigen::MatrixXd crba_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q ) { data->M.fill(0); crba(*model,*data,q); data->M.triangularView<Eigen::StrictlyLower>() = data->M.transpose().triangularView<Eigen::StrictlyLower>(); return data->M; } static Eigen::VectorXd com_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q ) { return centerOfMass(*model,*data,q); } static void com_acceleration_proxy(const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & v, const VectorXd_fx & a) { return centerOfMassAcceleration(*model,*data,q,v,a); } static Eigen::MatrixXd Jcom_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q ) { return jacobianCenterOfMass(*model,*data,q); } static Eigen::MatrixXd jacobian_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, Model::Index jointId, bool local, bool update_geometry ) { Eigen::MatrixXd J( 6,model->nv ); J.setZero(); if (update_geometry) computeJacobians( *model,*data,q ); if(local) getJacobian<true> (*model, *data, jointId, J); else getJacobian<false> (*model, *data, jointId, J); return J; } static void compute_jacobians_proxy(const ModelHandler& model, DataHandler & data, const VectorXd_fx & q) { computeJacobians( *model,*data,q ); } static void fk_0_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q) { forwardKinematics(*model,*data,q); } static void fk_1_proxy( const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & qdot ) { forwardKinematics(*model,*data,q,qdot); } static void fk_2_proxy(const ModelHandler& model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & v, const VectorXd_fx & a) { forwardKinematics(*model,*data,q,v,a); } static void computeAllTerms_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & v) { data->M.fill(0); computeAllTerms(*model,*data,q,v); data->M.triangularView<Eigen::StrictlyLower>() = data->M.transpose().triangularView<Eigen::StrictlyLower>(); } static void jointLimits_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q) { jointLimits(*model,*data,q); } static double kineticEnergy_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q, const VectorXd_fx & v, const bool update_kinematics = true) { return kineticEnergy(*model,*data,q,v,update_kinematics); } static double potentialEnergy_proxy(const ModelHandler & model, DataHandler & data, const VectorXd_fx & q, const bool update_kinematics = true) { return potentialEnergy(*model,*data,q,update_kinematics); } #ifdef WITH_HPP_FCL static bool computeCollisions_proxy(GeometryDataHandler & data_geom, const bool stopAtFirstCollision) { return computeCollisions(*data_geom, stopAtFirstCollision); } static bool computeGeometryAndCollisions_proxy(const ModelHandler & model, DataHandler & data, const GeometryModelHandler & model_geom, GeometryDataHandler & data_geom, const VectorXd_fx & q, const bool & stopAtFirstCollision) { return computeCollisions(*model,*data,*model_geom, *data_geom, q, stopAtFirstCollision); } static void computeDistances_proxy(GeometryDataHandler & data_geom) { computeDistances(*data_geom); } static void computeGeometryAndDistances_proxy( const ModelHandler & model, DataHandler & data, const GeometryModelHandler & model_geom, GeometryDataHandler & data_geom, const Eigen::VectorXd & q ) { computeDistances(*model, *data, *model_geom, *data_geom, q); } #endif /* --- Expose --------------------------------------------------------- */ static void expose() { bp::def("rnea",rnea_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity qdot (size Model::nv)", "Acceleration qddot (size Model::nv)"), "Compute the RNEA, put the result in Data and return it."); bp::def("nle",nle_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity qdot (size Model::nv)"), "Compute the Non Linear Effects (coriolis, centrifugal and gravitational effects), put the result in Data and return it."); bp::def("crba",crba_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute CRBA, put the result in Data and return it."); bp::def("centerOfMass",com_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute the center of mass, putting the result in Data and return it."); bp::def("centerOfMassAcceleration",com_acceleration_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)", "Acceleration a (size Model::nv)"), "Compute the center of mass position, velocity and acceleration andputting the result in Data."); bp::def("jacobianCenterOfMass",Jcom_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute the jacobian of the center of mass, put the result in Data and return it."); bp::def("kinematics",fk_1_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)"), "Compute the placements and spatial velocities of all the frames of the kinematic " "tree and put the results in data."); bp::def("geometry",fk_0_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute the placements of all the frames of the kinematic " "tree and put the results in data."); bp::def("dynamics",fk_2_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)", "Acceleration a (size Model::nv)"), "Compute the placements, spatial velocities and spatial accelerations of all the frames of the kinematic " "tree and put the results in data."); bp::def("computeAllTerms",computeAllTerms_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)"), "Compute all the terms M, non linear effects and Jacobians in" "in the same loop and put the results in data."); bp::def("jacobian",jacobian_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Joint ID (int)", "frame (true = local, false = world)", "update_geometry (true = update the value of the total jacobian)"), "Calling computeJacobians then getJacobian, return the result. Attention: the " "function computes indeed all the jacobians of the model, even if just outputing " "the demanded one if update_geometry is set to false. It is therefore outrageously costly wrt a dedicated " "call. Function to be used only for prototyping."); bp::def("computeJacobians",compute_jacobians_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Calling computeJacobians"); bp::def("jointLimits",jointLimits_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)"), "Compute the maximum limits of all the joints of the model " "and put the results in data."); bp::def("kineticEnergy",kineticEnergy_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Velocity v (size Model::nv)", "Update kinematics (bool)"), "Compute the kinematic energy of the model for the " "given joint configuration and velocity and store it " " in data.kinetic_energy. By default, the kinematics of model is updated."); bp::def("potentialEnergy",potentialEnergy_proxy, bp::args("Model","Data", "Configuration q (size Model::nq)", "Update kinematics (bool)"), "Compute the potential energy of the model for the " "given the joint configuration and store it " " in data.potential_energy. By default, the kinematics of model is updated."); #ifdef WITH_HPP_FCL bp::def("computeCollisions",computeCollisions_proxy, bp::args("GeometryData","bool"), "Determine if collisions pairs are effectively in collision." ); bp::def("computeGeometryAndCollisions",computeGeometryAndCollisions_proxy, bp::args("Model","Data","GeometryModel","GeometryData","Configuration q (size Model::nq)", "bool"), "Update the geometry for a given configuration and" "determine if all collision pairs are effectively in collision or not." ); bp::def("computeDistances",computeDistances_proxy, bp::args("GeometryData"), "Compute the distance between each collision pair." ); bp::def("computeGeometryAndDistances",computeGeometryAndDistances_proxy, bp::args("Model","Data","GeometryModel","GeometryData","Configuration q (size Model::nq)"), "Update the geometry for a given configuration and" "compute the distance between each collision pair" ); #endif } }; }} // namespace se3::python #endif // ifndef __se3_python_data_hpp__ <|endoftext|>
<commit_before>// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/MSF/MSFBuilder.h" #include "llvm/DebugInfo/MSF/MSFError.h" using namespace llvm; using namespace llvm::msf; using namespace llvm::support; namespace { const uint32_t kSuperBlockBlock = 0; const uint32_t kFreePageMap0Block = 1; const uint32_t kFreePageMap1Block = 2; const uint32_t kNumReservedPages = 3; const uint32_t kDefaultBlockMapAddr = kNumReservedPages; } MSFBuilder::MSFBuilder(uint32_t BlockSize, uint32_t MinBlockCount, bool CanGrow, BumpPtrAllocator &Allocator) : Allocator(Allocator), IsGrowable(CanGrow), BlockSize(BlockSize), MininumBlocks(MinBlockCount), BlockMapAddr(kDefaultBlockMapAddr), FreeBlocks(MinBlockCount, true) { FreeBlocks[kSuperBlockBlock] = false; FreeBlocks[kFreePageMap0Block] = false; FreeBlocks[kFreePageMap1Block] = false; FreeBlocks[BlockMapAddr] = false; } Expected<MSFBuilder> MSFBuilder::create(BumpPtrAllocator &Allocator, uint32_t BlockSize, uint32_t MinBlockCount, bool CanGrow) { if (!isValidBlockSize(BlockSize)) return make_error<MSFError>(msf_error_code::invalid_format, "The requested block size is unsupported"); return MSFBuilder(BlockSize, std::max(MinBlockCount, msf::getMinimumBlockCount()), CanGrow, Allocator); } Error MSFBuilder::setBlockMapAddr(uint32_t Addr) { if (Addr == BlockMapAddr) return Error::success(); if (Addr >= FreeBlocks.size()) { if (!IsGrowable) return make_error<MSFError>(msf_error_code::insufficient_buffer, "Cannot grow the number of blocks"); FreeBlocks.resize(Addr + 1); } if (!isBlockFree(Addr)) return make_error<MSFError>( msf_error_code::block_in_use, "Requested block map address is already in use"); FreeBlocks[BlockMapAddr] = true; FreeBlocks[Addr] = false; BlockMapAddr = Addr; return Error::success(); } void MSFBuilder::setFreePageMap(uint32_t Fpm) { FreePageMap = Fpm; } void MSFBuilder::setUnknown1(uint32_t Unk1) { Unknown1 = Unk1; } Error MSFBuilder::setDirectoryBlocksHint(ArrayRef<uint32_t> DirBlocks) { for (auto B : DirectoryBlocks) FreeBlocks[B] = true; for (auto B : DirBlocks) { if (!isBlockFree(B)) { return make_error<MSFError>(msf_error_code::unspecified, "Attempt to reuse an allocated block"); } FreeBlocks[B] = false; } DirectoryBlocks = DirBlocks; return Error::success(); } Error MSFBuilder::allocateBlocks(uint32_t NumBlocks, MutableArrayRef<uint32_t> Blocks) { if (NumBlocks == 0) return Error::success(); uint32_t NumFreeBlocks = FreeBlocks.count(); if (NumFreeBlocks < NumBlocks) { if (!IsGrowable) return make_error<MSFError>(msf_error_code::insufficient_buffer, "There are no free Blocks in the file"); uint32_t AllocBlocks = NumBlocks - NumFreeBlocks; FreeBlocks.resize(AllocBlocks + FreeBlocks.size(), true); } int I = 0; int Block = FreeBlocks.find_first(); do { assert(Block != -1 && "We ran out of Blocks!"); uint32_t NextBlock = static_cast<uint32_t>(Block); Blocks[I++] = NextBlock; FreeBlocks.reset(NextBlock); Block = FreeBlocks.find_next(Block); } while (--NumBlocks > 0); return Error::success(); } uint32_t MSFBuilder::getNumUsedBlocks() const { return getTotalBlockCount() - getNumFreeBlocks(); } uint32_t MSFBuilder::getNumFreeBlocks() const { return FreeBlocks.count(); } uint32_t MSFBuilder::getTotalBlockCount() const { return FreeBlocks.size(); } bool MSFBuilder::isBlockFree(uint32_t Idx) const { return FreeBlocks[Idx]; } Error MSFBuilder::addStream(uint32_t Size, ArrayRef<uint32_t> Blocks) { // Add a new stream mapped to the specified blocks. Verify that the specified // blocks are both necessary and sufficient for holding the requested number // of bytes, and verify that all requested blocks are free. uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize); if (ReqBlocks != Blocks.size()) return make_error<MSFError>( msf_error_code::invalid_format, "Incorrect number of blocks for requested stream size"); for (auto Block : Blocks) { if (Block >= FreeBlocks.size()) FreeBlocks.resize(Block + 1, true); if (!FreeBlocks.test(Block)) return make_error<MSFError>( msf_error_code::unspecified, "Attempt to re-use an already allocated block"); } // Mark all the blocks occupied by the new stream as not free. for (auto Block : Blocks) { FreeBlocks.reset(Block); } StreamData.push_back(std::make_pair(Size, Blocks)); return Error::success(); } Error MSFBuilder::addStream(uint32_t Size) { uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize); std::vector<uint32_t> NewBlocks; NewBlocks.resize(ReqBlocks); if (auto EC = allocateBlocks(ReqBlocks, NewBlocks)) return EC; StreamData.push_back(std::make_pair(Size, NewBlocks)); return Error::success(); } Error MSFBuilder::setStreamSize(uint32_t Idx, uint32_t Size) { uint32_t OldSize = getStreamSize(Idx); if (OldSize == Size) return Error::success(); uint32_t NewBlocks = bytesToBlocks(Size, BlockSize); uint32_t OldBlocks = bytesToBlocks(OldSize, BlockSize); if (NewBlocks > OldBlocks) { uint32_t AddedBlocks = NewBlocks - OldBlocks; // If we're growing, we have to allocate new Blocks. std::vector<uint32_t> AddedBlockList; AddedBlockList.resize(AddedBlocks); if (auto EC = allocateBlocks(AddedBlocks, AddedBlockList)) return EC; auto &CurrentBlocks = StreamData[Idx].second; CurrentBlocks.insert(CurrentBlocks.end(), AddedBlockList.begin(), AddedBlockList.end()); } else if (OldBlocks > NewBlocks) { // For shrinking, free all the Blocks in the Block map, update the stream // data, then shrink the directory. uint32_t RemovedBlocks = OldBlocks - NewBlocks; auto CurrentBlocks = ArrayRef<uint32_t>(StreamData[Idx].second); auto RemovedBlockList = CurrentBlocks.drop_front(NewBlocks); for (auto P : RemovedBlockList) FreeBlocks[P] = true; StreamData[Idx].second = CurrentBlocks.drop_back(RemovedBlocks); } StreamData[Idx].first = Size; return Error::success(); } uint32_t MSFBuilder::getNumStreams() const { return StreamData.size(); } uint32_t MSFBuilder::getStreamSize(uint32_t StreamIdx) const { return StreamData[StreamIdx].first; } ArrayRef<uint32_t> MSFBuilder::getStreamBlocks(uint32_t StreamIdx) const { return StreamData[StreamIdx].second; } uint32_t MSFBuilder::computeDirectoryByteSize() const { // The directory has the following layout, where each item is a ulittle32_t: // NumStreams // StreamSizes[NumStreams] // StreamBlocks[NumStreams][] uint32_t Size = sizeof(ulittle32_t); // NumStreams Size += StreamData.size() * sizeof(ulittle32_t); // StreamSizes for (const auto &D : StreamData) { uint32_t ExpectedNumBlocks = bytesToBlocks(D.first, BlockSize); assert(ExpectedNumBlocks == D.second.size() && "Unexpected number of blocks"); Size += ExpectedNumBlocks * sizeof(ulittle32_t); } return Size; } Expected<MSFLayout> MSFBuilder::build() { SuperBlock *SB = Allocator.Allocate<SuperBlock>(); MSFLayout L; L.SB = SB; std::memcpy(SB->MagicBytes, Magic, sizeof(Magic)); SB->BlockMapAddr = BlockMapAddr; SB->BlockSize = BlockSize; SB->NumDirectoryBytes = computeDirectoryByteSize(); SB->FreeBlockMapBlock = FreePageMap; SB->Unknown1 = Unknown1; uint32_t NumDirectoryBlocks = bytesToBlocks(SB->NumDirectoryBytes, BlockSize); if (NumDirectoryBlocks > DirectoryBlocks.size()) { // Our hint wasn't enough to satisfy the entire directory. Allocate // remaining pages. std::vector<uint32_t> ExtraBlocks; uint32_t NumExtraBlocks = NumDirectoryBlocks - DirectoryBlocks.size(); ExtraBlocks.resize(NumExtraBlocks); if (auto EC = allocateBlocks(NumExtraBlocks, ExtraBlocks)) return std::move(EC); DirectoryBlocks.insert(DirectoryBlocks.end(), ExtraBlocks.begin(), ExtraBlocks.end()); } else if (NumDirectoryBlocks < DirectoryBlocks.size()) { uint32_t NumUnnecessaryBlocks = DirectoryBlocks.size() - NumDirectoryBlocks; for (auto B : ArrayRef<uint32_t>(DirectoryBlocks).drop_back(NumUnnecessaryBlocks)) FreeBlocks[B] = true; DirectoryBlocks.resize(NumDirectoryBlocks); } // Don't set the number of blocks in the file until after allocating Blocks // for the directory, since the allocation might cause the file to need to // grow. SB->NumBlocks = FreeBlocks.size(); ulittle32_t *DirBlocks = Allocator.Allocate<ulittle32_t>(NumDirectoryBlocks); std::uninitialized_copy_n(DirectoryBlocks.begin(), NumDirectoryBlocks, DirBlocks); L.DirectoryBlocks = ArrayRef<ulittle32_t>(DirBlocks, NumDirectoryBlocks); // The stream sizes should be re-allocated as a stable pointer and the stream // map should have each of its entries allocated as a separate stable pointer. if (StreamData.size() > 0) { ulittle32_t *Sizes = Allocator.Allocate<ulittle32_t>(StreamData.size()); L.StreamSizes = ArrayRef<ulittle32_t>(Sizes, StreamData.size()); L.StreamMap.resize(StreamData.size()); for (uint32_t I = 0; I < StreamData.size(); ++I) { Sizes[I] = StreamData[I].first; ulittle32_t *BlockList = Allocator.Allocate<ulittle32_t>(StreamData[I].second.size()); std::uninitialized_copy_n(StreamData[I].second.begin(), StreamData[I].second.size(), BlockList); L.StreamMap[I] = ArrayRef<ulittle32_t>(BlockList, StreamData[I].second.size()); } } return L; } <commit_msg>PDB: Mark extended file pages as free by default.<commit_after>// // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/DebugInfo/MSF/MSFBuilder.h" #include "llvm/DebugInfo/MSF/MSFError.h" using namespace llvm; using namespace llvm::msf; using namespace llvm::support; namespace { const uint32_t kSuperBlockBlock = 0; const uint32_t kFreePageMap0Block = 1; const uint32_t kFreePageMap1Block = 2; const uint32_t kNumReservedPages = 3; const uint32_t kDefaultBlockMapAddr = kNumReservedPages; } MSFBuilder::MSFBuilder(uint32_t BlockSize, uint32_t MinBlockCount, bool CanGrow, BumpPtrAllocator &Allocator) : Allocator(Allocator), IsGrowable(CanGrow), BlockSize(BlockSize), MininumBlocks(MinBlockCount), BlockMapAddr(kDefaultBlockMapAddr), FreeBlocks(MinBlockCount, true) { FreeBlocks[kSuperBlockBlock] = false; FreeBlocks[kFreePageMap0Block] = false; FreeBlocks[kFreePageMap1Block] = false; FreeBlocks[BlockMapAddr] = false; } Expected<MSFBuilder> MSFBuilder::create(BumpPtrAllocator &Allocator, uint32_t BlockSize, uint32_t MinBlockCount, bool CanGrow) { if (!isValidBlockSize(BlockSize)) return make_error<MSFError>(msf_error_code::invalid_format, "The requested block size is unsupported"); return MSFBuilder(BlockSize, std::max(MinBlockCount, msf::getMinimumBlockCount()), CanGrow, Allocator); } Error MSFBuilder::setBlockMapAddr(uint32_t Addr) { if (Addr == BlockMapAddr) return Error::success(); if (Addr >= FreeBlocks.size()) { if (!IsGrowable) return make_error<MSFError>(msf_error_code::insufficient_buffer, "Cannot grow the number of blocks"); FreeBlocks.resize(Addr + 1, true); } if (!isBlockFree(Addr)) return make_error<MSFError>( msf_error_code::block_in_use, "Requested block map address is already in use"); FreeBlocks[BlockMapAddr] = true; FreeBlocks[Addr] = false; BlockMapAddr = Addr; return Error::success(); } void MSFBuilder::setFreePageMap(uint32_t Fpm) { FreePageMap = Fpm; } void MSFBuilder::setUnknown1(uint32_t Unk1) { Unknown1 = Unk1; } Error MSFBuilder::setDirectoryBlocksHint(ArrayRef<uint32_t> DirBlocks) { for (auto B : DirectoryBlocks) FreeBlocks[B] = true; for (auto B : DirBlocks) { if (!isBlockFree(B)) { return make_error<MSFError>(msf_error_code::unspecified, "Attempt to reuse an allocated block"); } FreeBlocks[B] = false; } DirectoryBlocks = DirBlocks; return Error::success(); } Error MSFBuilder::allocateBlocks(uint32_t NumBlocks, MutableArrayRef<uint32_t> Blocks) { if (NumBlocks == 0) return Error::success(); uint32_t NumFreeBlocks = FreeBlocks.count(); if (NumFreeBlocks < NumBlocks) { if (!IsGrowable) return make_error<MSFError>(msf_error_code::insufficient_buffer, "There are no free Blocks in the file"); uint32_t AllocBlocks = NumBlocks - NumFreeBlocks; FreeBlocks.resize(AllocBlocks + FreeBlocks.size(), true); } int I = 0; int Block = FreeBlocks.find_first(); do { assert(Block != -1 && "We ran out of Blocks!"); uint32_t NextBlock = static_cast<uint32_t>(Block); Blocks[I++] = NextBlock; FreeBlocks.reset(NextBlock); Block = FreeBlocks.find_next(Block); } while (--NumBlocks > 0); return Error::success(); } uint32_t MSFBuilder::getNumUsedBlocks() const { return getTotalBlockCount() - getNumFreeBlocks(); } uint32_t MSFBuilder::getNumFreeBlocks() const { return FreeBlocks.count(); } uint32_t MSFBuilder::getTotalBlockCount() const { return FreeBlocks.size(); } bool MSFBuilder::isBlockFree(uint32_t Idx) const { return FreeBlocks[Idx]; } Error MSFBuilder::addStream(uint32_t Size, ArrayRef<uint32_t> Blocks) { // Add a new stream mapped to the specified blocks. Verify that the specified // blocks are both necessary and sufficient for holding the requested number // of bytes, and verify that all requested blocks are free. uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize); if (ReqBlocks != Blocks.size()) return make_error<MSFError>( msf_error_code::invalid_format, "Incorrect number of blocks for requested stream size"); for (auto Block : Blocks) { if (Block >= FreeBlocks.size()) FreeBlocks.resize(Block + 1, true); if (!FreeBlocks.test(Block)) return make_error<MSFError>( msf_error_code::unspecified, "Attempt to re-use an already allocated block"); } // Mark all the blocks occupied by the new stream as not free. for (auto Block : Blocks) { FreeBlocks.reset(Block); } StreamData.push_back(std::make_pair(Size, Blocks)); return Error::success(); } Error MSFBuilder::addStream(uint32_t Size) { uint32_t ReqBlocks = bytesToBlocks(Size, BlockSize); std::vector<uint32_t> NewBlocks; NewBlocks.resize(ReqBlocks); if (auto EC = allocateBlocks(ReqBlocks, NewBlocks)) return EC; StreamData.push_back(std::make_pair(Size, NewBlocks)); return Error::success(); } Error MSFBuilder::setStreamSize(uint32_t Idx, uint32_t Size) { uint32_t OldSize = getStreamSize(Idx); if (OldSize == Size) return Error::success(); uint32_t NewBlocks = bytesToBlocks(Size, BlockSize); uint32_t OldBlocks = bytesToBlocks(OldSize, BlockSize); if (NewBlocks > OldBlocks) { uint32_t AddedBlocks = NewBlocks - OldBlocks; // If we're growing, we have to allocate new Blocks. std::vector<uint32_t> AddedBlockList; AddedBlockList.resize(AddedBlocks); if (auto EC = allocateBlocks(AddedBlocks, AddedBlockList)) return EC; auto &CurrentBlocks = StreamData[Idx].second; CurrentBlocks.insert(CurrentBlocks.end(), AddedBlockList.begin(), AddedBlockList.end()); } else if (OldBlocks > NewBlocks) { // For shrinking, free all the Blocks in the Block map, update the stream // data, then shrink the directory. uint32_t RemovedBlocks = OldBlocks - NewBlocks; auto CurrentBlocks = ArrayRef<uint32_t>(StreamData[Idx].second); auto RemovedBlockList = CurrentBlocks.drop_front(NewBlocks); for (auto P : RemovedBlockList) FreeBlocks[P] = true; StreamData[Idx].second = CurrentBlocks.drop_back(RemovedBlocks); } StreamData[Idx].first = Size; return Error::success(); } uint32_t MSFBuilder::getNumStreams() const { return StreamData.size(); } uint32_t MSFBuilder::getStreamSize(uint32_t StreamIdx) const { return StreamData[StreamIdx].first; } ArrayRef<uint32_t> MSFBuilder::getStreamBlocks(uint32_t StreamIdx) const { return StreamData[StreamIdx].second; } uint32_t MSFBuilder::computeDirectoryByteSize() const { // The directory has the following layout, where each item is a ulittle32_t: // NumStreams // StreamSizes[NumStreams] // StreamBlocks[NumStreams][] uint32_t Size = sizeof(ulittle32_t); // NumStreams Size += StreamData.size() * sizeof(ulittle32_t); // StreamSizes for (const auto &D : StreamData) { uint32_t ExpectedNumBlocks = bytesToBlocks(D.first, BlockSize); assert(ExpectedNumBlocks == D.second.size() && "Unexpected number of blocks"); Size += ExpectedNumBlocks * sizeof(ulittle32_t); } return Size; } Expected<MSFLayout> MSFBuilder::build() { SuperBlock *SB = Allocator.Allocate<SuperBlock>(); MSFLayout L; L.SB = SB; std::memcpy(SB->MagicBytes, Magic, sizeof(Magic)); SB->BlockMapAddr = BlockMapAddr; SB->BlockSize = BlockSize; SB->NumDirectoryBytes = computeDirectoryByteSize(); SB->FreeBlockMapBlock = FreePageMap; SB->Unknown1 = Unknown1; uint32_t NumDirectoryBlocks = bytesToBlocks(SB->NumDirectoryBytes, BlockSize); if (NumDirectoryBlocks > DirectoryBlocks.size()) { // Our hint wasn't enough to satisfy the entire directory. Allocate // remaining pages. std::vector<uint32_t> ExtraBlocks; uint32_t NumExtraBlocks = NumDirectoryBlocks - DirectoryBlocks.size(); ExtraBlocks.resize(NumExtraBlocks); if (auto EC = allocateBlocks(NumExtraBlocks, ExtraBlocks)) return std::move(EC); DirectoryBlocks.insert(DirectoryBlocks.end(), ExtraBlocks.begin(), ExtraBlocks.end()); } else if (NumDirectoryBlocks < DirectoryBlocks.size()) { uint32_t NumUnnecessaryBlocks = DirectoryBlocks.size() - NumDirectoryBlocks; for (auto B : ArrayRef<uint32_t>(DirectoryBlocks).drop_back(NumUnnecessaryBlocks)) FreeBlocks[B] = true; DirectoryBlocks.resize(NumDirectoryBlocks); } // Don't set the number of blocks in the file until after allocating Blocks // for the directory, since the allocation might cause the file to need to // grow. SB->NumBlocks = FreeBlocks.size(); ulittle32_t *DirBlocks = Allocator.Allocate<ulittle32_t>(NumDirectoryBlocks); std::uninitialized_copy_n(DirectoryBlocks.begin(), NumDirectoryBlocks, DirBlocks); L.DirectoryBlocks = ArrayRef<ulittle32_t>(DirBlocks, NumDirectoryBlocks); // The stream sizes should be re-allocated as a stable pointer and the stream // map should have each of its entries allocated as a separate stable pointer. if (StreamData.size() > 0) { ulittle32_t *Sizes = Allocator.Allocate<ulittle32_t>(StreamData.size()); L.StreamSizes = ArrayRef<ulittle32_t>(Sizes, StreamData.size()); L.StreamMap.resize(StreamData.size()); for (uint32_t I = 0; I < StreamData.size(); ++I) { Sizes[I] = StreamData[I].first; ulittle32_t *BlockList = Allocator.Allocate<ulittle32_t>(StreamData[I].second.size()); std::uninitialized_copy_n(StreamData[I].second.begin(), StreamData[I].second.size(), BlockList); L.StreamMap[I] = ArrayRef<ulittle32_t>(BlockList, StreamData[I].second.size()); } } return L; } <|endoftext|>
<commit_before>/* * AliFemtoPPbpbLamZVtxMultContainer.cxx * * Created on: Aug 30, 2017 * Author: gu74req */ //#include "AliLog.h" #include <iostream> #include "AliFemtoDreamZVtxMultContainer.h" #include "TLorentzVector.h" #include "TDatabasePDG.h" #include "TVector2.h" ClassImp(AliFemtoDreamPartContainer) AliFemtoDreamZVtxMultContainer::AliFemtoDreamZVtxMultContainer() : fPartContainer(0), fPDGParticleSpecies(0), fWhichPairs(){ } AliFemtoDreamZVtxMultContainer::AliFemtoDreamZVtxMultContainer( AliFemtoDreamCollConfig *conf) : fPartContainer(conf->GetNParticles(), AliFemtoDreamPartContainer(conf->GetMixingDepth())), fPDGParticleSpecies(conf->GetPDGCodes()), fWhichPairs(conf->GetWhichPairs()){ TDatabasePDG::Instance()->AddParticle("deuteron", "deuteron", 1.8756134, kTRUE, 0.0, 1, "Nucleus", 1000010020); TDatabasePDG::Instance()->AddAntiParticle("anti-deuteron", -1000010020); } AliFemtoDreamZVtxMultContainer::~AliFemtoDreamZVtxMultContainer() { // TODO Auto-generated destructor stub } void AliFemtoDreamZVtxMultContainer::SetEvent( std::vector<std::vector<AliFemtoDreamBasePart>> &Particles) { //This method sets the particles of an event only in the case, that //more than one particle was identified, to avoid empty events. // if (Particles->size()!=fParticleSpecies){ // TString errMessage = Form("Number of Input Particlese (%d) doese not" // "correspond to the Number of particles Set (%d)",Particles->size(), // fParticleSpecies); // AliFatal(errMessage.Data()); // } else { std::vector<std::vector<AliFemtoDreamBasePart>>::iterator itInput = Particles .begin(); std::vector<AliFemtoDreamPartContainer>::iterator itContainer = fPartContainer .begin(); while (itContainer != fPartContainer.end()) { if (itInput->size() > 0) { itContainer->SetEvent(*itInput); } ++itInput; ++itContainer; } // } } void AliFemtoDreamZVtxMultContainer::PairParticlesSE( std::vector<std::vector<AliFemtoDreamBasePart>> &Particles, AliFemtoDreamHigherPairMath *HigherMath, int iMult, float cent) { float RelativeK = 0; int HistCounter = 0; //First loop over all the different Species auto itPDGPar1 = fPDGParticleSpecies.begin(); for (auto itSpec1 = Particles.begin(); itSpec1 != Particles.end(); ++itSpec1) { auto itPDGPar2 = fPDGParticleSpecies.begin(); itPDGPar2 += itSpec1 - Particles.begin(); for (auto itSpec2 = itSpec1; itSpec2 != Particles.end(); ++itSpec2) { HigherMath->FillPairCounterSE(HistCounter, itSpec1->size(), itSpec2->size()); //Now loop over the actual Particles and correlate them for (auto itPart1 = itSpec1->begin(); itPart1 != itSpec1->end(); ++itPart1) { AliFemtoDreamBasePart part1 = *itPart1; std::vector<AliFemtoDreamBasePart>::iterator itPart2; if (itSpec1 == itSpec2) { itPart2 = itPart1 + 1; } else { itPart2 = itSpec2->begin(); } while (itPart2 != itSpec2->end()) { AliFemtoDreamBasePart part2 = *itPart2; TLorentzVector PartOne, PartTwo; PartOne.SetXYZM( itPart1->GetMomentum().X(), itPart1->GetMomentum().Y(), itPart1->GetMomentum().Z(), TDatabasePDG::Instance()->GetParticle(*itPDGPar1)->Mass()); PartTwo.SetXYZM( itPart2->GetMomentum().X(), itPart2->GetMomentum().Y(), itPart2->GetMomentum().Z(), TDatabasePDG::Instance()->GetParticle(*itPDGPar2)->Mass()); float RelativeK = HigherMath->RelativePairMomentum(PartOne, PartTwo); if (!HigherMath->PassesPairSelection(HistCounter, *itPart1, *itPart2, RelativeK, true, false)) { ++itPart2; continue; } RelativeK = HigherMath->FillSameEvent(HistCounter, iMult, cent, part1, *itPDGPar1, part2, *itPDGPar2); HigherMath->MassQA(HistCounter, RelativeK, *itPart1, *itPart2); HigherMath->SEDetaDPhiPlots(HistCounter, *itPart1, *itPDGPar1, *itPart2, *itPDGPar2, RelativeK, false); HigherMath->SEMomentumResolution(HistCounter, &(*itPart1), *itPDGPar1, &(*itPart2), *itPDGPar2, RelativeK); ++itPart2; } } ++HistCounter; itPDGPar2++; } itPDGPar1++; } } void AliFemtoDreamZVtxMultContainer::PairParticlesME( std::vector<std::vector<AliFemtoDreamBasePart>> &Particles, AliFemtoDreamHigherPairMath *HigherMath, int iMult, float cent) { float RelativeK = 0; int HistCounter = 0; auto itPDGPar1 = fPDGParticleSpecies.begin(); //First loop over all the different Species for (auto itSpec1 = Particles.begin(); itSpec1 != Particles.end(); ++itSpec1) { //We dont want to correlate the particles twice. Mixed Event Dist. of //Particle1 + Particle2 == Particle2 + Particle 1 int SkipPart = itSpec1 - Particles.begin(); auto itPDGPar2 = fPDGParticleSpecies.begin() + SkipPart; for (auto itSpec2 = fPartContainer.begin() + SkipPart; itSpec2 != fPartContainer.end(); ++itSpec2) { if (itSpec1->size() > 0) { HigherMath->FillEffectiveMixingDepth(HistCounter, (int) itSpec2->GetMixingDepth()); } for (int iDepth = 0; iDepth < (int) itSpec2->GetMixingDepth(); ++iDepth) { std::vector<AliFemtoDreamBasePart> ParticlesOfEvent = itSpec2->GetEvent( iDepth); HigherMath->FillPairCounterME(HistCounter, itSpec1->size(), ParticlesOfEvent.size()); for (auto itPart1 = itSpec1->begin(); itPart1 != itSpec1->end(); ++itPart1) { for (auto itPart2 = ParticlesOfEvent.begin(); itPart2 != ParticlesOfEvent.end(); ++itPart2) { TLorentzVector PartOne, PartTwo; PartOne.SetXYZM( itPart1->GetMomentum().X(), itPart1->GetMomentum().Y(), itPart1->GetMomentum().Z(), TDatabasePDG::Instance()->GetParticle(*itPDGPar1)->Mass()); PartTwo.SetXYZM( itPart2->GetMomentum().X(), itPart2->GetMomentum().Y(), itPart2->GetMomentum().Z(), TDatabasePDG::Instance()->GetParticle(*itPDGPar2)->Mass()); float RelativeK = HigherMath->RelativePairMomentum(PartOne, PartTwo); if (!HigherMath->PassesPairSelection(HistCounter, *itPart1, *itPart2, RelativeK, false, false)) { continue; } RelativeK = HigherMath->FillMixedEvent( HistCounter, iMult, cent, *itPart1, *itPDGPar1, *itPart2, *itPDGPar2, AliFemtoDreamCollConfig::kNone); HigherMath->MEDetaDPhiPlots(HistCounter, *itPart1, *itPDGPar1, *itPart2, *itPDGPar2, RelativeK, false); HigherMath->MEMomentumResolution(HistCounter, &(*itPart1), *itPDGPar1, &(*itPart2), *itPDGPar2, RelativeK); } } } ++HistCounter; ++itPDGPar2; } ++itPDGPar1; } } <commit_msg>Takes care of a compiler warning<commit_after>/* * AliFemtoPPbpbLamZVtxMultContainer.cxx * * Created on: Aug 30, 2017 * Author: gu74req */ //#include "AliLog.h" #include <iostream> #include "AliFemtoDreamZVtxMultContainer.h" #include "TLorentzVector.h" #include "TDatabasePDG.h" #include "TVector2.h" ClassImp(AliFemtoDreamPartContainer) AliFemtoDreamZVtxMultContainer::AliFemtoDreamZVtxMultContainer() : fPartContainer(0), fPDGParticleSpecies(0), fWhichPairs(){ } AliFemtoDreamZVtxMultContainer::AliFemtoDreamZVtxMultContainer( AliFemtoDreamCollConfig *conf) : fPartContainer(conf->GetNParticles(), AliFemtoDreamPartContainer(conf->GetMixingDepth())), fPDGParticleSpecies(conf->GetPDGCodes()), fWhichPairs(conf->GetWhichPairs()){ TDatabasePDG::Instance()->AddParticle("deuteron", "deuteron", 1.8756134, kTRUE, 0.0, 1, "Nucleus", 1000010020); TDatabasePDG::Instance()->AddAntiParticle("anti-deuteron", -1000010020); } AliFemtoDreamZVtxMultContainer::~AliFemtoDreamZVtxMultContainer() { // TODO Auto-generated destructor stub } void AliFemtoDreamZVtxMultContainer::SetEvent( std::vector<std::vector<AliFemtoDreamBasePart>> &Particles) { //This method sets the particles of an event only in the case, that //more than one particle was identified, to avoid empty events. // if (Particles->size()!=fParticleSpecies){ // TString errMessage = Form("Number of Input Particlese (%d) doese not" // "correspond to the Number of particles Set (%d)",Particles->size(), // fParticleSpecies); // AliFatal(errMessage.Data()); // } else { std::vector<std::vector<AliFemtoDreamBasePart>>::iterator itInput = Particles .begin(); std::vector<AliFemtoDreamPartContainer>::iterator itContainer = fPartContainer .begin(); while (itContainer != fPartContainer.end()) { if (itInput->size() > 0) { itContainer->SetEvent(*itInput); } ++itInput; ++itContainer; } // } } void AliFemtoDreamZVtxMultContainer::PairParticlesSE( std::vector<std::vector<AliFemtoDreamBasePart>> &Particles, AliFemtoDreamHigherPairMath *HigherMath, int iMult, float cent) { int HistCounter = 0; //First loop over all the different Species auto itPDGPar1 = fPDGParticleSpecies.begin(); for (auto itSpec1 = Particles.begin(); itSpec1 != Particles.end(); ++itSpec1) { auto itPDGPar2 = fPDGParticleSpecies.begin(); itPDGPar2 += itSpec1 - Particles.begin(); for (auto itSpec2 = itSpec1; itSpec2 != Particles.end(); ++itSpec2) { HigherMath->FillPairCounterSE(HistCounter, itSpec1->size(), itSpec2->size()); //Now loop over the actual Particles and correlate them for (auto itPart1 = itSpec1->begin(); itPart1 != itSpec1->end(); ++itPart1) { AliFemtoDreamBasePart part1 = *itPart1; std::vector<AliFemtoDreamBasePart>::iterator itPart2; if (itSpec1 == itSpec2) { itPart2 = itPart1 + 1; } else { itPart2 = itSpec2->begin(); } while (itPart2 != itSpec2->end()) { AliFemtoDreamBasePart part2 = *itPart2; TLorentzVector PartOne, PartTwo; PartOne.SetXYZM( itPart1->GetMomentum().X(), itPart1->GetMomentum().Y(), itPart1->GetMomentum().Z(), TDatabasePDG::Instance()->GetParticle(*itPDGPar1)->Mass()); PartTwo.SetXYZM( itPart2->GetMomentum().X(), itPart2->GetMomentum().Y(), itPart2->GetMomentum().Z(), TDatabasePDG::Instance()->GetParticle(*itPDGPar2)->Mass()); float RelativeK = HigherMath->RelativePairMomentum(PartOne, PartTwo); if (!HigherMath->PassesPairSelection(HistCounter, *itPart1, *itPart2, RelativeK, true, false)) { ++itPart2; continue; } RelativeK = HigherMath->FillSameEvent(HistCounter, iMult, cent, part1, *itPDGPar1, part2, *itPDGPar2); HigherMath->MassQA(HistCounter, RelativeK, *itPart1, *itPart2); HigherMath->SEDetaDPhiPlots(HistCounter, *itPart1, *itPDGPar1, *itPart2, *itPDGPar2, RelativeK, false); HigherMath->SEMomentumResolution(HistCounter, &(*itPart1), *itPDGPar1, &(*itPart2), *itPDGPar2, RelativeK); ++itPart2; } } ++HistCounter; itPDGPar2++; } itPDGPar1++; } } void AliFemtoDreamZVtxMultContainer::PairParticlesME( std::vector<std::vector<AliFemtoDreamBasePart>> &Particles, AliFemtoDreamHigherPairMath *HigherMath, int iMult, float cent) { int HistCounter = 0; auto itPDGPar1 = fPDGParticleSpecies.begin(); //First loop over all the different Species for (auto itSpec1 = Particles.begin(); itSpec1 != Particles.end(); ++itSpec1) { //We dont want to correlate the particles twice. Mixed Event Dist. of //Particle1 + Particle2 == Particle2 + Particle 1 int SkipPart = itSpec1 - Particles.begin(); auto itPDGPar2 = fPDGParticleSpecies.begin() + SkipPart; for (auto itSpec2 = fPartContainer.begin() + SkipPart; itSpec2 != fPartContainer.end(); ++itSpec2) { if (itSpec1->size() > 0) { HigherMath->FillEffectiveMixingDepth(HistCounter, (int) itSpec2->GetMixingDepth()); } for (int iDepth = 0; iDepth < (int) itSpec2->GetMixingDepth(); ++iDepth) { std::vector<AliFemtoDreamBasePart> ParticlesOfEvent = itSpec2->GetEvent( iDepth); HigherMath->FillPairCounterME(HistCounter, itSpec1->size(), ParticlesOfEvent.size()); for (auto itPart1 = itSpec1->begin(); itPart1 != itSpec1->end(); ++itPart1) { for (auto itPart2 = ParticlesOfEvent.begin(); itPart2 != ParticlesOfEvent.end(); ++itPart2) { TLorentzVector PartOne, PartTwo; PartOne.SetXYZM( itPart1->GetMomentum().X(), itPart1->GetMomentum().Y(), itPart1->GetMomentum().Z(), TDatabasePDG::Instance()->GetParticle(*itPDGPar1)->Mass()); PartTwo.SetXYZM( itPart2->GetMomentum().X(), itPart2->GetMomentum().Y(), itPart2->GetMomentum().Z(), TDatabasePDG::Instance()->GetParticle(*itPDGPar2)->Mass()); float RelativeK = HigherMath->RelativePairMomentum(PartOne, PartTwo); if (!HigherMath->PassesPairSelection(HistCounter, *itPart1, *itPart2, RelativeK, false, false)) { continue; } RelativeK = HigherMath->FillMixedEvent( HistCounter, iMult, cent, *itPart1, *itPDGPar1, *itPart2, *itPDGPar2, AliFemtoDreamCollConfig::kNone); HigherMath->MEDetaDPhiPlots(HistCounter, *itPart1, *itPDGPar1, *itPart2, *itPDGPar2, RelativeK, false); HigherMath->MEMomentumResolution(HistCounter, &(*itPart1), *itPDGPar1, &(*itPart2), *itPDGPar2, RelativeK); } } } ++HistCounter; ++itPDGPar2; } ++itPDGPar1; } } <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // 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) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #include "hadesmem/module_iterator.hpp" #define BOOST_TEST_MODULE module_iterator #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/test/unit_test.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/error.hpp" #include "hadesmem/module.hpp" #include "hadesmem/process.hpp" // Boost.Test causes the following warning under GCC: // error: base class 'struct boost::unit_test::ut_detail::nil_t' has a // non-virtual destructor [-Werror=effc++] #if defined(HADESMEM_GCC) #pragma GCC diagnostic ignored "-Weffc++" #endif // #if defined(HADESMEM_GCC) BOOST_AUTO_TEST_CASE(module_iterator) { hadesmem::Process const process(::GetCurrentProcessId()); auto iter = hadesmem::ModuleIterator(process); hadesmem::Module const this_mod(process, nullptr); BOOST_CHECK(iter != hadesmem::ModuleIterator()); BOOST_CHECK(*iter == this_mod); hadesmem::Module const ntdll_mod(process, L"NtDll.DlL"); BOOST_CHECK(++iter != hadesmem::ModuleIterator()); BOOST_CHECK(*iter == ntdll_mod); hadesmem::Module const kernel32_mod(process, L"kernel32.dll"); BOOST_CHECK(++iter != hadesmem::ModuleIterator()); BOOST_CHECK(*iter == kernel32_mod); std::for_each(hadesmem::ModuleIterator(process), hadesmem::ModuleIterator(), [] (hadesmem::Module const& module) { BOOST_CHECK(module.GetHandle() != nullptr); }); BOOST_CHECK(std::find_if(hadesmem::ModuleIterator(process), hadesmem::ModuleIterator(), [] (hadesmem::Module const& module) { return module.GetHandle() == GetModuleHandle(L"user32.dll"); }) != hadesmem::ModuleIterator()); } <commit_msg>* [module_iterator] Perform concept checking.<commit_after>// Copyright Joshua Boyce 2010-2012. // 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) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #include "hadesmem/module_iterator.hpp" #define BOOST_TEST_MODULE module_iterator #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/concept_check.hpp> #include <boost/test/unit_test.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include "hadesmem/error.hpp" #include "hadesmem/module.hpp" #include "hadesmem/process.hpp" // Boost.Test causes the following warning under GCC: // error: base class 'struct boost::unit_test::ut_detail::nil_t' has a // non-virtual destructor [-Werror=effc++] #if defined(HADESMEM_GCC) #pragma GCC diagnostic ignored "-Weffc++" #endif // #if defined(HADESMEM_GCC) BOOST_AUTO_TEST_CASE(module_iterator) { BOOST_CONCEPT_ASSERT((boost::InputIterator<hadesmem::ModuleIterator>)); hadesmem::Process const process(::GetCurrentProcessId()); auto iter = hadesmem::ModuleIterator(process); hadesmem::Module const this_mod(process, nullptr); BOOST_CHECK(iter != hadesmem::ModuleIterator()); BOOST_CHECK(*iter == this_mod); hadesmem::Module const ntdll_mod(process, L"NtDll.DlL"); BOOST_CHECK(++iter != hadesmem::ModuleIterator()); BOOST_CHECK(*iter == ntdll_mod); hadesmem::Module const kernel32_mod(process, L"kernel32.dll"); BOOST_CHECK(++iter != hadesmem::ModuleIterator()); BOOST_CHECK(*iter == kernel32_mod); std::for_each(hadesmem::ModuleIterator(process), hadesmem::ModuleIterator(), [] (hadesmem::Module const& module) { BOOST_CHECK(module.GetHandle() != nullptr); }); BOOST_CHECK(std::find_if(hadesmem::ModuleIterator(process), hadesmem::ModuleIterator(), [] (hadesmem::Module const& module) { return module.GetHandle() == GetModuleHandle(L"user32.dll"); }) != hadesmem::ModuleIterator()); } <|endoftext|>
<commit_before>/* * Copyright © 2013 Intel Corporation * * 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 (including the next * paragraph) 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 "brw_fs.h" #include "brw_cfg.h" /** @file brw_fs_sel_peephole.cpp * * This file contains the opt_peephole_sel() optimization pass that replaces * MOV instructions to the same destination in the "then" and "else" bodies of * an if statement with SEL instructions. */ /* Four MOVs seems to be pretty typical, so I picked the next power of two in * the hopes that it would handle almost anything possible in a single * pass. */ #define MAX_MOVS 8 /**< The maximum number of MOVs to attempt to match. */ /** * Scans forwards from an IF counting consecutive MOV instructions in the * "then" and "else" blocks of the if statement. * * A pointer to the fs_inst* for IF is passed as the <if_inst> argument. The * function stores pointers to the MOV instructions in the <then_mov> and * <else_mov> arrays. * * \return the minimum number of MOVs found in the two branches or zero if * an error occurred. * * E.g.: * IF ... * then_mov[0] = MOV g4, ... * then_mov[1] = MOV g5, ... * then_mov[2] = MOV g6, ... * ELSE ... * else_mov[0] = MOV g4, ... * else_mov[1] = MOV g5, ... * else_mov[2] = MOV g7, ... * ENDIF * returns 3. */ static int count_movs_from_if(fs_inst *then_mov[MAX_MOVS], fs_inst *else_mov[MAX_MOVS], fs_inst *if_inst, fs_inst *else_inst) { fs_inst *m = if_inst; assert(m->opcode == BRW_OPCODE_IF); m = (fs_inst *) m->next; int then_movs = 0; while (then_movs < MAX_MOVS && m->opcode == BRW_OPCODE_MOV) { then_mov[then_movs] = m; m = (fs_inst *) m->next; then_movs++; } m = (fs_inst *) else_inst->next; int else_movs = 0; while (else_movs < MAX_MOVS && m->opcode == BRW_OPCODE_MOV) { else_mov[else_movs] = m; m = (fs_inst *) m->next; else_movs++; } return MIN2(then_movs, else_movs); } /** * Try to replace IF/MOV+/ELSE/MOV+/ENDIF with SEL. * * Many GLSL shaders contain the following pattern: * * x = condition ? foo : bar * * or * * if (...) a.xyzw = foo.xyzw; * else a.xyzw = bar.xyzw; * * The compiler emits an ir_if tree for this, since each subexpression might be * a complex tree that could have side-effects or short-circuit logic. * * However, the common case is to simply select one of two constants or * variable values---which is exactly what SEL is for. In this case, the * assembly looks like: * * (+f0) IF * MOV dst src0 * ... * ELSE * MOV dst src1 * ... * ENDIF * * where each pair of MOVs to a common destination and can be easily translated * into * * (+f0) SEL dst src0 src1 * * If src0 is an immediate value, we promote it to a temporary GRF. */ bool fs_visitor::opt_peephole_sel() { bool progress = false; cfg_t cfg(&instructions); for (int b = 0; b < cfg.num_blocks; b++) { bblock_t *block = cfg.blocks[b]; /* IF instructions, by definition, can only be found at the ends of * basic blocks. */ fs_inst *if_inst = (fs_inst *) block->end; if (if_inst->opcode != BRW_OPCODE_IF) continue; if (!block->else_inst) continue; fs_inst *else_inst = (fs_inst *) block->else_inst; assert(else_inst->opcode == BRW_OPCODE_ELSE); fs_inst *else_mov[MAX_MOVS] = { NULL }; fs_inst *then_mov[MAX_MOVS] = { NULL }; int movs = count_movs_from_if(then_mov, else_mov, if_inst, else_inst); if (movs == 0) continue; fs_inst *sel_inst[MAX_MOVS] = { NULL }; fs_inst *mov_imm_inst[MAX_MOVS] = { NULL }; /* Generate SEL instructions for pairs of MOVs to a common destination. */ for (int i = 0; i < movs; i++) { if (!then_mov[i] || !else_mov[i]) break; /* Check that the MOVs are the right form. */ if (!then_mov[i]->dst.equals(else_mov[i]->dst) || then_mov[i]->is_partial_write() || else_mov[i]->is_partial_write()) { movs = i; break; } /* Only the last source register can be a constant, so if the MOV in * the "then" clause uses a constant, we need to put it in a * temporary. */ fs_reg src0(then_mov[i]->src[0]); if (src0.file == IMM) { src0 = fs_reg(this, glsl_type::float_type); src0.type = then_mov[i]->src[0].type; mov_imm_inst[i] = MOV(src0, then_mov[i]->src[0]); } sel_inst[i] = SEL(then_mov[i]->dst, src0, else_mov[i]->src[0]); if (brw->gen == 6 && if_inst->conditional_mod) { /* For Sandybridge with IF with embedded comparison */ sel_inst[i]->predicate = BRW_PREDICATE_NORMAL; } else { /* Separate CMP and IF instructions */ sel_inst[i]->predicate = if_inst->predicate; sel_inst[i]->predicate_inverse = if_inst->predicate_inverse; } } if (movs == 0) continue; /* Emit a CMP if our IF used the embedded comparison */ if (brw->gen == 6 && if_inst->conditional_mod) { fs_inst *cmp_inst = CMP(reg_null_d, if_inst->src[0], if_inst->src[1], if_inst->conditional_mod); if_inst->insert_before(cmp_inst); } for (int i = 0; i < movs; i++) { if (mov_imm_inst[i]) if_inst->insert_before(mov_imm_inst[i]); if_inst->insert_before(sel_inst[i]); then_mov[i]->remove(); else_mov[i]->remove(); } progress = true; } if (progress) invalidate_live_intervals(); return progress; } <commit_msg>i965/fs: Emit a MOV instead of a SEL if the sources are the same.<commit_after>/* * Copyright © 2013 Intel Corporation * * 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 (including the next * paragraph) 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 "brw_fs.h" #include "brw_cfg.h" /** @file brw_fs_sel_peephole.cpp * * This file contains the opt_peephole_sel() optimization pass that replaces * MOV instructions to the same destination in the "then" and "else" bodies of * an if statement with SEL instructions. */ /* Four MOVs seems to be pretty typical, so I picked the next power of two in * the hopes that it would handle almost anything possible in a single * pass. */ #define MAX_MOVS 8 /**< The maximum number of MOVs to attempt to match. */ /** * Scans forwards from an IF counting consecutive MOV instructions in the * "then" and "else" blocks of the if statement. * * A pointer to the fs_inst* for IF is passed as the <if_inst> argument. The * function stores pointers to the MOV instructions in the <then_mov> and * <else_mov> arrays. * * \return the minimum number of MOVs found in the two branches or zero if * an error occurred. * * E.g.: * IF ... * then_mov[0] = MOV g4, ... * then_mov[1] = MOV g5, ... * then_mov[2] = MOV g6, ... * ELSE ... * else_mov[0] = MOV g4, ... * else_mov[1] = MOV g5, ... * else_mov[2] = MOV g7, ... * ENDIF * returns 3. */ static int count_movs_from_if(fs_inst *then_mov[MAX_MOVS], fs_inst *else_mov[MAX_MOVS], fs_inst *if_inst, fs_inst *else_inst) { fs_inst *m = if_inst; assert(m->opcode == BRW_OPCODE_IF); m = (fs_inst *) m->next; int then_movs = 0; while (then_movs < MAX_MOVS && m->opcode == BRW_OPCODE_MOV) { then_mov[then_movs] = m; m = (fs_inst *) m->next; then_movs++; } m = (fs_inst *) else_inst->next; int else_movs = 0; while (else_movs < MAX_MOVS && m->opcode == BRW_OPCODE_MOV) { else_mov[else_movs] = m; m = (fs_inst *) m->next; else_movs++; } return MIN2(then_movs, else_movs); } /** * Try to replace IF/MOV+/ELSE/MOV+/ENDIF with SEL. * * Many GLSL shaders contain the following pattern: * * x = condition ? foo : bar * * or * * if (...) a.xyzw = foo.xyzw; * else a.xyzw = bar.xyzw; * * The compiler emits an ir_if tree for this, since each subexpression might be * a complex tree that could have side-effects or short-circuit logic. * * However, the common case is to simply select one of two constants or * variable values---which is exactly what SEL is for. In this case, the * assembly looks like: * * (+f0) IF * MOV dst src0 * ... * ELSE * MOV dst src1 * ... * ENDIF * * where each pair of MOVs to a common destination and can be easily translated * into * * (+f0) SEL dst src0 src1 * * If src0 is an immediate value, we promote it to a temporary GRF. */ bool fs_visitor::opt_peephole_sel() { bool progress = false; cfg_t cfg(&instructions); for (int b = 0; b < cfg.num_blocks; b++) { bblock_t *block = cfg.blocks[b]; /* IF instructions, by definition, can only be found at the ends of * basic blocks. */ fs_inst *if_inst = (fs_inst *) block->end; if (if_inst->opcode != BRW_OPCODE_IF) continue; if (!block->else_inst) continue; fs_inst *else_inst = (fs_inst *) block->else_inst; assert(else_inst->opcode == BRW_OPCODE_ELSE); fs_inst *else_mov[MAX_MOVS] = { NULL }; fs_inst *then_mov[MAX_MOVS] = { NULL }; int movs = count_movs_from_if(then_mov, else_mov, if_inst, else_inst); if (movs == 0) continue; fs_inst *sel_inst[MAX_MOVS] = { NULL }; fs_inst *mov_imm_inst[MAX_MOVS] = { NULL }; /* Generate SEL instructions for pairs of MOVs to a common destination. */ for (int i = 0; i < movs; i++) { if (!then_mov[i] || !else_mov[i]) break; /* Check that the MOVs are the right form. */ if (!then_mov[i]->dst.equals(else_mov[i]->dst) || then_mov[i]->is_partial_write() || else_mov[i]->is_partial_write()) { movs = i; break; } if (!then_mov[i]->src[0].equals(else_mov[i]->src[0])) { /* Only the last source register can be a constant, so if the MOV * in the "then" clause uses a constant, we need to put it in a * temporary. */ fs_reg src0(then_mov[i]->src[0]); if (src0.file == IMM) { src0 = fs_reg(this, glsl_type::float_type); src0.type = then_mov[i]->src[0].type; mov_imm_inst[i] = MOV(src0, then_mov[i]->src[0]); } sel_inst[i] = SEL(then_mov[i]->dst, src0, else_mov[i]->src[0]); if (brw->gen == 6 && if_inst->conditional_mod) { /* For Sandybridge with IF with embedded comparison */ sel_inst[i]->predicate = BRW_PREDICATE_NORMAL; } else { /* Separate CMP and IF instructions */ sel_inst[i]->predicate = if_inst->predicate; sel_inst[i]->predicate_inverse = if_inst->predicate_inverse; } } else { sel_inst[i] = MOV(then_mov[i]->dst, then_mov[i]->src[0]); } } if (movs == 0) continue; /* Emit a CMP if our IF used the embedded comparison */ if (brw->gen == 6 && if_inst->conditional_mod) { fs_inst *cmp_inst = CMP(reg_null_d, if_inst->src[0], if_inst->src[1], if_inst->conditional_mod); if_inst->insert_before(cmp_inst); } for (int i = 0; i < movs; i++) { if (mov_imm_inst[i]) if_inst->insert_before(mov_imm_inst[i]); if_inst->insert_before(sel_inst[i]); then_mov[i]->remove(); else_mov[i]->remove(); } progress = true; } if (progress) invalidate_live_intervals(); return progress; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "quicktest.h" #include "quicktestresult_p.h" #include <QtTest/qtestsystem.h> #include "qtestoptions_p.h" #include <QApplication> #include <QtDeclarative/qdeclarative.h> #include <QtQuick1/qdeclarativeview.h> #include <QtDeclarative/qdeclarativeengine.h> #include <QtDeclarative/qdeclarativecontext.h> #if defined(QML_VERSION) && QML_VERSION >= 0x020000 #include <QtQuick/qquickview.h> #define QUICK_TEST_SCENEGRAPH 1 #endif #include <QtDeclarative/qjsvalue.h> #include <QtDeclarative/qjsengine.h> #include <QtGui/qopengl.h> #include <QtCore/qurl.h> #include <QtCore/qfileinfo.h> #include <QtCore/qdir.h> #include <QtCore/qdiriterator.h> #include <QtCore/qfile.h> #include <QtCore/qdebug.h> #include <QtCore/qeventloop.h> #include <QtCore/qtextstream.h> #include <QtGui/qtextdocument.h> #include <stdio.h> #include <QtGui/QGuiApplication> #include <QtCore/QTranslator> QT_BEGIN_NAMESPACE static void installCoverageTool(const char * appname, const char * testname) { #ifdef __COVERAGESCANNER__ // Install Coverage Tool __coveragescanner_install(appname); __coveragescanner_testname(testname); __coveragescanner_clear(); #else Q_UNUSED(appname); Q_UNUSED(testname); #endif } static void saveCoverageTool(const char * appname, bool testfailed) { #ifdef __COVERAGESCANNER__ // install again to make sure the filename is correct. // without this, a plugin or similar may have changed the filename. __coveragescanner_install(appname); __coveragescanner_teststate(testfailed ? "FAILED" : "PASSED"); __coveragescanner_save(); __coveragescanner_testname(""); __coveragescanner_clear(); #else Q_UNUSED(appname); Q_UNUSED(testfailed); #endif } class QTestRootObject : public QObject { Q_OBJECT Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged) Q_PROPERTY(bool hasTestCase READ hasTestCase WRITE setHasTestCase NOTIFY hasTestCaseChanged) public: QTestRootObject(QObject *parent = 0) : QObject(parent), hasQuit(false), m_windowShown(false), m_hasTestCase(false) {} bool hasQuit:1; bool hasTestCase() const { return m_hasTestCase; } void setHasTestCase(bool value) { m_hasTestCase = value; emit hasTestCaseChanged(); } bool windowShown() const { return m_windowShown; } void setWindowShown(bool value) { m_windowShown = value; emit windowShownChanged(); } Q_SIGNALS: void windowShownChanged(); void hasTestCaseChanged(); private Q_SLOTS: void quit() { hasQuit = true; } private: bool m_windowShown : 1; bool m_hasTestCase :1; }; static inline QString stripQuotes(const QString &s) { if (s.length() >= 2 && s.startsWith(QLatin1Char('"')) && s.endsWith(QLatin1Char('"'))) return s.mid(1, s.length() - 2); else return s; } template <class View> void handleCompileErrors(const QFileInfo &fi, const View &view) { // Error compiling the test - flag failure in the log and continue. const QList<QDeclarativeError> errors = view.errors(); QuickTestResult results; results.setTestCaseName(fi.baseName()); results.startLogging(); results.setFunctionName(QLatin1String("compile")); results.setFunctionType(QuickTestResult::Func); // Verbose warning output of all messages and relevant parameters QString message; QTextStream str(&message); str << "\n " << QDir::toNativeSeparators(fi.absoluteFilePath()) << " produced " << errors.size() << " error(s):\n"; foreach (const QDeclarativeError &e, errors) { str << " "; if (e.url().isLocalFile()) { str << e.url().toLocalFile(); } else { str << e.url().toString(); } if (e.line() > 0) str << ':' << e.line() << ',' << e.column(); str << ": " << e.description() << '\n'; } str << " Working directory: " << QDir::toNativeSeparators(QDir::current().absolutePath()) << '\n'; if (QDeclarativeEngine *engine = view.engine()) { str << " View: " << view.metaObject()->className() << ", import paths:\n"; foreach (const QString &i, engine->importPathList()) str << " '" << QDir::toNativeSeparators(i) << "'\n"; const QStringList pluginPaths = engine->pluginPathList(); str << " Plugin paths:\n"; foreach (const QString &p, pluginPaths) str << " '" << QDir::toNativeSeparators(p) << "'\n"; } qWarning("%s", qPrintable(message)); // Fail with error 0. results.fail(errors.at(0).description(), errors.at(0).url(), errors.at(0).line()); results.finishTestFunction(); results.setFunctionName(QString()); results.setFunctionType(QuickTestResult::NoWhere); results.stopLogging(); } int quick_test_main(int argc, char **argv, const char *name, quick_test_viewport_create createViewport, const char *sourceDir) { QGuiApplication* app = 0; if (!QCoreApplication::instance()) { app = new QGuiApplication(argc, argv); } // Look for QML-specific command-line options. // -import dir Specify an import directory. // -input dir Specify the input directory for test cases. // -qtquick1 Run with QtQuick 1 rather than QtQuick 2. // -translation file Specify the translation file. QStringList imports; QString testPath; QString translationFile; bool qtQuick2 = true; int outargc = 1; int index = 1; while (index < argc) { if (strcmp(argv[index], "-import") == 0 && (index + 1) < argc) { imports += stripQuotes(QString::fromLocal8Bit(argv[index + 1])); index += 2; } else if (strcmp(argv[index], "-input") == 0 && (index + 1) < argc) { testPath = stripQuotes(QString::fromLocal8Bit(argv[index + 1])); index += 2; } else if (strcmp(argv[index], "-opengl") == 0) { ++index; } else if (strcmp(argv[index], "-qtquick1") == 0) { qtQuick2 = false; ++index; } else if (strcmp(argv[index], "-translation") == 0 && (index + 1) < argc) { translationFile = stripQuotes(QString::fromLocal8Bit(argv[index + 1])); index += 2; } else if (outargc != index) { argv[outargc++] = argv[index++]; } else { ++outargc; ++index; } } argv[outargc] = 0; argc = outargc; // Parse the command-line arguments. QuickTestResult::parseArgs(argc, argv); QuickTestResult::setProgramName(name); installCoverageTool(argv[0], name); QTranslator translator; if (!translationFile.isEmpty()) { if (translator.load(translationFile)) { app->installTranslator(&translator); } else { qWarning("Could not load the translation file '%s'.", qPrintable(translationFile)); } } // Determine where to look for the test data. if (testPath.isEmpty() && sourceDir) testPath = QString::fromLocal8Bit(sourceDir); if (testPath.isEmpty()) { QDir current = QDir::current(); #ifdef Q_OS_WIN // Skip release/debug subfolders if (!current.dirName().compare(QLatin1String("Release"), Qt::CaseInsensitive) || !current.dirName().compare(QLatin1String("Debug"), Qt::CaseInsensitive)) current.cdUp(); #endif // Q_OS_WIN testPath = current.absolutePath(); } QStringList files; const QFileInfo testPathInfo(testPath); if (testPathInfo.isFile()) { if (!testPath.endsWith(QStringLiteral(".qml"))) { qWarning("'%s' does not have the suffix '.qml'.", qPrintable(testPath)); return 1; } files << testPath; } else if (testPathInfo.isDir()) { // Scan the test data directory recursively, looking for "tst_*.qml" files. const QStringList filters(QStringLiteral("tst_*.qml")); QDirIterator iter(testPathInfo.absoluteFilePath(), filters, QDir::Files, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks); while (iter.hasNext()) files += iter.next(); files.sort(); if (files.isEmpty()) { qWarning("The directory '%s' does not contain any test files matching '%s'", qPrintable(testPath), qPrintable(filters.front())); return 1; } } else { qWarning("'%s' does not exist under '%s'.", qPrintable(testPath), qPrintable(QDir::currentPath())); return 1; } // Scan through all of the "tst_*.qml" files and run each of them // in turn with a QDeclarativeView. #ifdef QUICK_TEST_SCENEGRAPH if (qtQuick2) { QQuickView view; QTestRootObject rootobj; QEventLoop eventLoop; QObject::connect(view.engine(), SIGNAL(quit()), &rootobj, SLOT(quit())); QObject::connect(view.engine(), SIGNAL(quit()), &eventLoop, SLOT(quit())); view.rootContext()->setContextProperty (QLatin1String("qtest"), &rootobj); foreach (const QString &path, imports) view.engine()->addImportPath(path); foreach (QString file, files) { QFileInfo fi(file); if (!fi.exists()) continue; rootobj.setHasTestCase(false); rootobj.setWindowShown(false); rootobj.hasQuit = false; QString path = fi.absoluteFilePath(); if (path.startsWith(QLatin1String(":/"))) view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2))); else view.setSource(QUrl::fromLocalFile(path)); if (QTest::printAvailableFunctions) continue; if (view.status() == QQuickView::Error) { handleCompileErrors(fi, view); continue; } if (!rootobj.hasQuit) { // If the test already quit, then it was performed // synchronously during setSource(). Otherwise it is // an asynchronous test and we need to show the window // and wait for the quit indication. view.show(); QTest::qWaitForWindowShown(&view); rootobj.setWindowShown(true); if (!rootobj.hasQuit && rootobj.hasTestCase()) eventLoop.exec(); } } } else #endif { foreach (QString file, files) { QFileInfo fi(file); if (!fi.exists()) continue; QDeclarativeView view; QTestRootObject rootobj; QEventLoop eventLoop; QObject::connect(view.engine(), SIGNAL(quit()), &rootobj, SLOT(quit())); QObject::connect(view.engine(), SIGNAL(quit()), &eventLoop, SLOT(quit())); if (createViewport) view.setViewport((*createViewport)()); view.rootContext()->setContextProperty (QLatin1String("qtest"), &rootobj); foreach (QString path, imports) view.engine()->addImportPath(path); QString path = fi.absoluteFilePath(); if (path.startsWith(QLatin1String(":/"))) view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2))); else view.setSource(QUrl::fromLocalFile(path)); if (QTest::printAvailableFunctions) continue; if (view.status() == QDeclarativeView::Error) { // Error compiling the test - flag failure in the log and continue. handleCompileErrors(fi, view); continue; } if (!rootobj.hasQuit) { // If the test already quit, then it was performed // synchronously during setSource(). Otherwise it is // an asynchronous test and we need to show the window // and wait for the quit indication. view.show(); QTest::qWaitForWindowShown(&view); rootobj.setWindowShown(true); if (!rootobj.hasQuit) eventLoop.exec(); } } } // Flush the current logging stream. QuickTestResult::setProgramName(0); saveCoverageTool(argv[0], QuickTestResult::exitCode()); delete app; // Return the number of failures as the exit code. return QuickTestResult::exitCode(); } QT_END_NAMESPACE #include "quicktest.moc" <commit_msg>Don't delete global app<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "quicktest.h" #include "quicktestresult_p.h" #include <QtTest/qtestsystem.h> #include "qtestoptions_p.h" #include <QApplication> #include <QtDeclarative/qdeclarative.h> #include <QtQuick1/qdeclarativeview.h> #include <QtDeclarative/qdeclarativeengine.h> #include <QtDeclarative/qdeclarativecontext.h> #if defined(QML_VERSION) && QML_VERSION >= 0x020000 #include <QtQuick/qquickview.h> #define QUICK_TEST_SCENEGRAPH 1 #endif #include <QtDeclarative/qjsvalue.h> #include <QtDeclarative/qjsengine.h> #include <QtGui/qopengl.h> #include <QtCore/qurl.h> #include <QtCore/qfileinfo.h> #include <QtCore/qdir.h> #include <QtCore/qdiriterator.h> #include <QtCore/qfile.h> #include <QtCore/qdebug.h> #include <QtCore/qeventloop.h> #include <QtCore/qtextstream.h> #include <QtGui/qtextdocument.h> #include <stdio.h> #include <QtGui/QGuiApplication> #include <QtCore/QTranslator> QT_BEGIN_NAMESPACE static void installCoverageTool(const char * appname, const char * testname) { #ifdef __COVERAGESCANNER__ // Install Coverage Tool __coveragescanner_install(appname); __coveragescanner_testname(testname); __coveragescanner_clear(); #else Q_UNUSED(appname); Q_UNUSED(testname); #endif } static void saveCoverageTool(const char * appname, bool testfailed) { #ifdef __COVERAGESCANNER__ // install again to make sure the filename is correct. // without this, a plugin or similar may have changed the filename. __coveragescanner_install(appname); __coveragescanner_teststate(testfailed ? "FAILED" : "PASSED"); __coveragescanner_save(); __coveragescanner_testname(""); __coveragescanner_clear(); #else Q_UNUSED(appname); Q_UNUSED(testfailed); #endif } class QTestRootObject : public QObject { Q_OBJECT Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged) Q_PROPERTY(bool hasTestCase READ hasTestCase WRITE setHasTestCase NOTIFY hasTestCaseChanged) public: QTestRootObject(QObject *parent = 0) : QObject(parent), hasQuit(false), m_windowShown(false), m_hasTestCase(false) {} bool hasQuit:1; bool hasTestCase() const { return m_hasTestCase; } void setHasTestCase(bool value) { m_hasTestCase = value; emit hasTestCaseChanged(); } bool windowShown() const { return m_windowShown; } void setWindowShown(bool value) { m_windowShown = value; emit windowShownChanged(); } Q_SIGNALS: void windowShownChanged(); void hasTestCaseChanged(); private Q_SLOTS: void quit() { hasQuit = true; } private: bool m_windowShown : 1; bool m_hasTestCase :1; }; static inline QString stripQuotes(const QString &s) { if (s.length() >= 2 && s.startsWith(QLatin1Char('"')) && s.endsWith(QLatin1Char('"'))) return s.mid(1, s.length() - 2); else return s; } template <class View> void handleCompileErrors(const QFileInfo &fi, const View &view) { // Error compiling the test - flag failure in the log and continue. const QList<QDeclarativeError> errors = view.errors(); QuickTestResult results; results.setTestCaseName(fi.baseName()); results.startLogging(); results.setFunctionName(QLatin1String("compile")); results.setFunctionType(QuickTestResult::Func); // Verbose warning output of all messages and relevant parameters QString message; QTextStream str(&message); str << "\n " << QDir::toNativeSeparators(fi.absoluteFilePath()) << " produced " << errors.size() << " error(s):\n"; foreach (const QDeclarativeError &e, errors) { str << " "; if (e.url().isLocalFile()) { str << e.url().toLocalFile(); } else { str << e.url().toString(); } if (e.line() > 0) str << ':' << e.line() << ',' << e.column(); str << ": " << e.description() << '\n'; } str << " Working directory: " << QDir::toNativeSeparators(QDir::current().absolutePath()) << '\n'; if (QDeclarativeEngine *engine = view.engine()) { str << " View: " << view.metaObject()->className() << ", import paths:\n"; foreach (const QString &i, engine->importPathList()) str << " '" << QDir::toNativeSeparators(i) << "'\n"; const QStringList pluginPaths = engine->pluginPathList(); str << " Plugin paths:\n"; foreach (const QString &p, pluginPaths) str << " '" << QDir::toNativeSeparators(p) << "'\n"; } qWarning("%s", qPrintable(message)); // Fail with error 0. results.fail(errors.at(0).description(), errors.at(0).url(), errors.at(0).line()); results.finishTestFunction(); results.setFunctionName(QString()); results.setFunctionType(QuickTestResult::NoWhere); results.stopLogging(); } int quick_test_main(int argc, char **argv, const char *name, quick_test_viewport_create createViewport, const char *sourceDir) { QGuiApplication* app = 0; if (!QCoreApplication::instance()) { app = new QGuiApplication(argc, argv); } // Look for QML-specific command-line options. // -import dir Specify an import directory. // -input dir Specify the input directory for test cases. // -qtquick1 Run with QtQuick 1 rather than QtQuick 2. // -translation file Specify the translation file. QStringList imports; QString testPath; QString translationFile; bool qtQuick2 = true; int outargc = 1; int index = 1; while (index < argc) { if (strcmp(argv[index], "-import") == 0 && (index + 1) < argc) { imports += stripQuotes(QString::fromLocal8Bit(argv[index + 1])); index += 2; } else if (strcmp(argv[index], "-input") == 0 && (index + 1) < argc) { testPath = stripQuotes(QString::fromLocal8Bit(argv[index + 1])); index += 2; } else if (strcmp(argv[index], "-opengl") == 0) { ++index; } else if (strcmp(argv[index], "-qtquick1") == 0) { qtQuick2 = false; ++index; } else if (strcmp(argv[index], "-translation") == 0 && (index + 1) < argc) { translationFile = stripQuotes(QString::fromLocal8Bit(argv[index + 1])); index += 2; } else if (outargc != index) { argv[outargc++] = argv[index++]; } else { ++outargc; ++index; } } argv[outargc] = 0; argc = outargc; // Parse the command-line arguments. QuickTestResult::parseArgs(argc, argv); QuickTestResult::setProgramName(name); installCoverageTool(argv[0], name); QTranslator translator; if (!translationFile.isEmpty()) { if (translator.load(translationFile)) { app->installTranslator(&translator); } else { qWarning("Could not load the translation file '%s'.", qPrintable(translationFile)); } } // Determine where to look for the test data. if (testPath.isEmpty() && sourceDir) testPath = QString::fromLocal8Bit(sourceDir); if (testPath.isEmpty()) { QDir current = QDir::current(); #ifdef Q_OS_WIN // Skip release/debug subfolders if (!current.dirName().compare(QLatin1String("Release"), Qt::CaseInsensitive) || !current.dirName().compare(QLatin1String("Debug"), Qt::CaseInsensitive)) current.cdUp(); #endif // Q_OS_WIN testPath = current.absolutePath(); } QStringList files; const QFileInfo testPathInfo(testPath); if (testPathInfo.isFile()) { if (!testPath.endsWith(QStringLiteral(".qml"))) { qWarning("'%s' does not have the suffix '.qml'.", qPrintable(testPath)); return 1; } files << testPath; } else if (testPathInfo.isDir()) { // Scan the test data directory recursively, looking for "tst_*.qml" files. const QStringList filters(QStringLiteral("tst_*.qml")); QDirIterator iter(testPathInfo.absoluteFilePath(), filters, QDir::Files, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks); while (iter.hasNext()) files += iter.next(); files.sort(); if (files.isEmpty()) { qWarning("The directory '%s' does not contain any test files matching '%s'", qPrintable(testPath), qPrintable(filters.front())); return 1; } } else { qWarning("'%s' does not exist under '%s'.", qPrintable(testPath), qPrintable(QDir::currentPath())); return 1; } // Scan through all of the "tst_*.qml" files and run each of them // in turn with a QDeclarativeView. #ifdef QUICK_TEST_SCENEGRAPH if (qtQuick2) { QQuickView view; QTestRootObject rootobj; QEventLoop eventLoop; QObject::connect(view.engine(), SIGNAL(quit()), &rootobj, SLOT(quit())); QObject::connect(view.engine(), SIGNAL(quit()), &eventLoop, SLOT(quit())); view.rootContext()->setContextProperty (QLatin1String("qtest"), &rootobj); foreach (const QString &path, imports) view.engine()->addImportPath(path); foreach (QString file, files) { QFileInfo fi(file); if (!fi.exists()) continue; rootobj.setHasTestCase(false); rootobj.setWindowShown(false); rootobj.hasQuit = false; QString path = fi.absoluteFilePath(); if (path.startsWith(QLatin1String(":/"))) view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2))); else view.setSource(QUrl::fromLocalFile(path)); if (QTest::printAvailableFunctions) continue; if (view.status() == QQuickView::Error) { handleCompileErrors(fi, view); continue; } if (!rootobj.hasQuit) { // If the test already quit, then it was performed // synchronously during setSource(). Otherwise it is // an asynchronous test and we need to show the window // and wait for the quit indication. view.show(); QTest::qWaitForWindowShown(&view); rootobj.setWindowShown(true); if (!rootobj.hasQuit && rootobj.hasTestCase()) eventLoop.exec(); } } } else #endif { foreach (QString file, files) { QFileInfo fi(file); if (!fi.exists()) continue; QDeclarativeView view; QTestRootObject rootobj; QEventLoop eventLoop; QObject::connect(view.engine(), SIGNAL(quit()), &rootobj, SLOT(quit())); QObject::connect(view.engine(), SIGNAL(quit()), &eventLoop, SLOT(quit())); if (createViewport) view.setViewport((*createViewport)()); view.rootContext()->setContextProperty (QLatin1String("qtest"), &rootobj); foreach (QString path, imports) view.engine()->addImportPath(path); QString path = fi.absoluteFilePath(); if (path.startsWith(QLatin1String(":/"))) view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2))); else view.setSource(QUrl::fromLocalFile(path)); if (QTest::printAvailableFunctions) continue; if (view.status() == QDeclarativeView::Error) { // Error compiling the test - flag failure in the log and continue. handleCompileErrors(fi, view); continue; } if (!rootobj.hasQuit) { // If the test already quit, then it was performed // synchronously during setSource(). Otherwise it is // an asynchronous test and we need to show the window // and wait for the quit indication. view.show(); QTest::qWaitForWindowShown(&view); rootobj.setWindowShown(true); if (!rootobj.hasQuit) eventLoop.exec(); } } } // Flush the current logging stream. QuickTestResult::setProgramName(0); saveCoverageTool(argv[0], QuickTestResult::exitCode()); //Sometimes delete app cause crash here with some qpa plugins, //so we comment the follow line out to make them happy. //delete app; // Return the number of failures as the exit code. return QuickTestResult::exitCode(); } QT_END_NAMESPACE #include "quicktest.moc" <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Dan Leinir Turthra Jensen <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ #include "qmlplugin.h" #include "ArchiveBookModel.h" #include "BookListModel.h" #include "BookModel.h" #include "ComicCoverImageProvider.h" #include "FolderBookModel.h" #include "PeruseConfig.h" #include "PreviewImageProvider.h" #ifdef USE_PERUSE_PDFTHUMBNAILER #include "PDFCoverImageProvider.h" #endif #include "FilterProxy.h" #include "PropertyContainer.h" #include "TextDocumentEditor.h" #include "AcbfBinary.h" #include "AcbfReference.h" #include "AcbfStyle.h" #include "AcbfIdentifiedObjectModel.h" #include <QQmlEngine> #include <QtQml/qqml.h> void QmlPlugins::initializeEngine(QQmlEngine *engine, const char *) { engine->addImageProvider("preview", new PreviewImageProvider()); engine->addImageProvider("comiccover", new ComicCoverImageProvider()); #ifdef USE_PERUSE_PDFTHUMBNAILER engine->addImageProvider("pdfcover", new PDFCoverImageProvider()); #endif } void QmlPlugins::registerTypes(const char *uri) { qmlRegisterType<BookListModel>(uri, 0, 1, "BookListModel"); qmlRegisterType<BookModel>(uri, 0, 1, "BookModel"); qmlRegisterType<ArchiveBookModel>(uri, 0, 1, "ArchiveBookModel"); qmlRegisterType<FolderBookModel>(uri, 0, 1, "FolderBookModel"); qmlRegisterType<PeruseConfig>(uri, 0, 1, "Config"); qmlRegisterType<PropertyContainer>(uri, 0, 1, "PropertyContainer"); qmlRegisterType<FilterProxy>(uri, 0, 1, "FilterProxy"); qmlRegisterType<TextDocumentEditor>(uri, 0, 1, "TextDocumentEditor"); qmlRegisterUncreatableType<AdvancedComicBookFormat::Reference>(uri, 0, 1, "Reference", "Don't attempt to create ACBF types directly, use the convenience functions on their container types for creating them"); qmlRegisterUncreatableType<AdvancedComicBookFormat::Binary>(uri, 0, 1, "Binary", "Don't attempt to create ACBF types directly, use the convenience functions on their container types for creating them"); qmlRegisterUncreatableType<AdvancedComicBookFormat::Style>(uri, 0, 1, "Style", "Don't attempt to create ACBF types directly, use the convenience functions on their container types for creating them"); qmlRegisterType<AdvancedComicBookFormat::IdentifiedObjectModel>(uri, 0, 1, "IdentifiedObjectModel"); } <commit_msg>Register CategoryEntriesModel so we can use it from QML<commit_after>/* * Copyright (C) 2015 Dan Leinir Turthra Jensen <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * */ #include "qmlplugin.h" #include "ArchiveBookModel.h" #include "BookListModel.h" #include "BookModel.h" #include "ComicCoverImageProvider.h" #include "FolderBookModel.h" #include "PeruseConfig.h" #include "PreviewImageProvider.h" #ifdef USE_PERUSE_PDFTHUMBNAILER #include "PDFCoverImageProvider.h" #endif #include "FilterProxy.h" #include "PropertyContainer.h" #include "TextDocumentEditor.h" #include "AcbfBinary.h" #include "AcbfReference.h" #include "AcbfStyle.h" #include "AcbfIdentifiedObjectModel.h" #include <QQmlEngine> #include <QtQml/qqml.h> void QmlPlugins::initializeEngine(QQmlEngine *engine, const char *) { engine->addImageProvider("preview", new PreviewImageProvider()); engine->addImageProvider("comiccover", new ComicCoverImageProvider()); #ifdef USE_PERUSE_PDFTHUMBNAILER engine->addImageProvider("pdfcover", new PDFCoverImageProvider()); #endif } void QmlPlugins::registerTypes(const char *uri) { qmlRegisterType<CategoryEntriesModel>(uri, 0, 1, "CategoryEntriesModel"); qmlRegisterType<BookListModel>(uri, 0, 1, "BookListModel"); qmlRegisterType<BookModel>(uri, 0, 1, "BookModel"); qmlRegisterType<ArchiveBookModel>(uri, 0, 1, "ArchiveBookModel"); qmlRegisterType<FolderBookModel>(uri, 0, 1, "FolderBookModel"); qmlRegisterType<PeruseConfig>(uri, 0, 1, "Config"); qmlRegisterType<PropertyContainer>(uri, 0, 1, "PropertyContainer"); qmlRegisterType<FilterProxy>(uri, 0, 1, "FilterProxy"); qmlRegisterType<TextDocumentEditor>(uri, 0, 1, "TextDocumentEditor"); qmlRegisterUncreatableType<AdvancedComicBookFormat::Reference>(uri, 0, 1, "Reference", "Don't attempt to create ACBF types directly, use the convenience functions on their container types for creating them"); qmlRegisterUncreatableType<AdvancedComicBookFormat::Binary>(uri, 0, 1, "Binary", "Don't attempt to create ACBF types directly, use the convenience functions on their container types for creating them"); qmlRegisterUncreatableType<AdvancedComicBookFormat::Style>(uri, 0, 1, "Style", "Don't attempt to create ACBF types directly, use the convenience functions on their container types for creating them"); qmlRegisterType<AdvancedComicBookFormat::IdentifiedObjectModel>(uri, 0, 1, "IdentifiedObjectModel"); } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "formeditoritem.h" #include "formeditorscene.h" #include "formeditornodeinstanceview.h" #include "selectiontool.h" #include <modelnode.h> #include <nodemetainfo.h> #include <widgetqueryview.h> #include <QGraphicsSceneMouseEvent> #include <QDebug> #include <QPainter> #include <QStyleOptionGraphicsItem> #include <QGraphicsView> #include <QTimeLine> #include <cmath> #include <invalidmodelnodeexception.h> #include <invalidnodestateexception.h> namespace QmlDesigner { FormEditorScene *FormEditorItem::scene() const { return qobject_cast<FormEditorScene*>(QGraphicsItem::scene()); } FormEditorItem::FormEditorItem(const QmlItemNode &qmlItemNode, FormEditorScene* scene) : QGraphicsObject(scene->formLayerItem()), m_snappingLineCreator(this), m_qmlItemNode(qmlItemNode), m_borderWidth(1.0), m_opacity(0.6), m_highlightBoundingRect(false) { setCacheMode(QGraphicsItem::DeviceCoordinateCache); setup(); } void FormEditorItem::setup() { if (qmlItemNode().hasInstanceParent()) setParentItem(scene()->itemForQmlItemNode(qmlItemNode().instanceParent().toQmlItemNode())); if (QGraphicsItem::parentItem() == scene()->formLayerItem()) m_borderWidth = 0.0; setFlag(QGraphicsItem::ItemIsMovable, true); updateGeometry(); updateVisibilty(); } QRectF FormEditorItem::boundingRect() const { return m_boundingRect; } void FormEditorItem::updateGeometry() { prepareGeometryChange(); m_boundingRect = qmlItemNode().instanceBoundingRect().adjusted(0, 0, 1., 1.); setTransform(qmlItemNode().instanceTransform()); setTransform(m_attentionTransform, true); //the property for zValue is called z in QGraphicsObject Q_ASSERT(qmlItemNode().instanceValue("z").isValid()); setZValue(qmlItemNode().instanceValue("z").toDouble()); } void FormEditorItem::updateVisibilty() { // setVisible(nodeInstance().isVisible()); // setOpacity(nodeInstance().opacity()); } void FormEditorItem::showAttention() { if (m_attentionTimeLine.isNull()) { m_attentionTimeLine = new QTimeLine(500, this); m_attentionTimeLine->setCurveShape(QTimeLine::SineCurve); connect(m_attentionTimeLine.data(), SIGNAL(valueChanged(qreal)), SLOT(changeAttention(qreal))); connect(m_attentionTimeLine.data(), SIGNAL(finished()), m_attentionTimeLine.data(), SLOT(deleteLater())); m_attentionTimeLine->start(); } } void FormEditorItem::changeAttention(qreal value) { if (QGraphicsItem::parentItem() == scene()->formLayerItem()) { setAttentionHighlight(value); } else { setAttentionHighlight(value); setAttentionScale(value); } } FormEditorView *FormEditorItem::formEditorView() const { return scene()->editorView(); } void FormEditorItem::setAttentionScale(double sinusScale) { if (!qFuzzyIsNull(sinusScale)) { double scale = std::sqrt(sinusScale); m_attentionTransform.reset(); QPointF centerPoint(qmlItemNode().instanceBoundingRect().center()); m_attentionTransform.translate(centerPoint.x(), centerPoint.y()); m_attentionTransform.scale(scale * 0.15 + 1.0, scale * 0.15 + 1.0); m_attentionTransform.translate(-centerPoint.x(), -centerPoint.y()); m_inverseAttentionTransform = m_attentionTransform.inverted(); prepareGeometryChange(); setTransform(qmlItemNode().instanceTransform()); setTransform(m_attentionTransform, true); } else { m_attentionTransform.reset(); prepareGeometryChange(); setTransform(qmlItemNode().instanceTransform()); } } void FormEditorItem::setAttentionHighlight(double value) { m_opacity = 0.6 + value; if (QGraphicsItem::parentItem() == scene()->formLayerItem()) m_borderWidth = value * 4; else m_borderWidth = 1. + value * 3; update(); } void FormEditorItem::setHighlightBoundingRect(bool highlight) { if (m_highlightBoundingRect != highlight) { m_highlightBoundingRect = highlight; update(); } } FormEditorItem::~FormEditorItem() { scene()->removeItemFromHash(this); } /* \brief returns the parent item skipping all proxyItem*/ FormEditorItem *FormEditorItem::parentItem() const { return qgraphicsitem_cast<FormEditorItem*> (QGraphicsItem::parentItem()); } FormEditorItem* FormEditorItem::fromQGraphicsItem(QGraphicsItem *graphicsItem) { return qgraphicsitem_cast<FormEditorItem*>(graphicsItem); } //static QRectF alignedRect(const QRectF &rect) //{ // QRectF alignedRect(rect); // alignedRect.setTop(std::floor(rect.top()) + 0.5); // alignedRect.setBottom(std::floor(rect.bottom()) + 0.5); // alignedRect.setLeft(std::floor(rect.left()) + 0.5); // alignedRect.setRight(std::floor(rect.right()) + 0.5); // // return alignedRect; //} void FormEditorItem::paintBoundingRect(QPainter *painter) const { if (QGraphicsItem::parentItem() == scene()->formLayerItem() && qFuzzyIsNull(m_borderWidth)) return; QPen pen; pen.setJoinStyle(Qt::MiterJoin); switch(scene()->paintMode()) { case FormEditorScene::AnchorMode: { pen.setColor(Qt::black); pen.setWidth(m_borderWidth); } break; case FormEditorScene::NormalMode: { if (scene()->showBoundingRects()) { if (m_highlightBoundingRect) pen.setColor("#AAAAAA"); else pen.setColor("#888888"); } else { if (m_highlightBoundingRect) pen.setColor("#AAAAAA"); else pen.setColor(Qt::transparent); } } break; } painter->setPen(pen); // int offset = m_borderWidth / 2; const QRectF br = boundingRect(); if (br.isValid()) painter->drawRect(br.adjusted(0., 0., -1., -1.)); } void FormEditorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if (!qmlItemNode().isValid()) return; painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); switch(scene()->paintMode()) { case FormEditorScene::AnchorMode: painter->setOpacity(m_opacity); break; case FormEditorScene::NormalMode: painter->setOpacity(qmlItemNode().instanceValue("opacity").toDouble()); break; } qmlItemNode().paintInstance(painter); painter->setRenderHint(QPainter::Antialiasing, false); if (!qmlItemNode().isRootModelNode()) paintBoundingRect(painter); painter->restore(); } AbstractFormEditorTool* FormEditorItem::tool() const { return static_cast<FormEditorScene*>(scene())->currentTool(); } SnapLineMap FormEditorItem::topSnappingLines() const { return m_snappingLineCreator.topLines(); } SnapLineMap FormEditorItem::bottomSnappingLines() const { return m_snappingLineCreator.bottomLines(); } SnapLineMap FormEditorItem::leftSnappingLines() const { return m_snappingLineCreator.leftLines(); } SnapLineMap FormEditorItem::rightSnappingLines() const { return m_snappingLineCreator.rightLines(); } SnapLineMap FormEditorItem::horizontalCenterSnappingLines() const { return m_snappingLineCreator.horizontalCenterLines(); } SnapLineMap FormEditorItem::verticalCenterSnappingLines() const { return m_snappingLineCreator.verticalCenterLines(); } SnapLineMap FormEditorItem::topSnappingOffsets() const { return m_snappingLineCreator.topOffsets(); } SnapLineMap FormEditorItem::bottomSnappingOffsets() const { return m_snappingLineCreator.bottomOffsets(); } SnapLineMap FormEditorItem::leftSnappingOffsets() const { return m_snappingLineCreator.leftOffsets(); } SnapLineMap FormEditorItem::rightSnappingOffsets() const { return m_snappingLineCreator.rightOffsets(); } void FormEditorItem::updateSnappingLines(const QList<FormEditorItem*> &exceptionList, FormEditorItem *transformationSpaceItem) { m_snappingLineCreator.update(exceptionList, transformationSpaceItem); } QList<FormEditorItem*> FormEditorItem::childFormEditorItems() const { QList<FormEditorItem*> formEditorItemList; foreach (QGraphicsItem *item, childItems()) { FormEditorItem *formEditorItem = fromQGraphicsItem(item); if (formEditorItem) formEditorItemList.append(formEditorItem); } return formEditorItemList; } bool FormEditorItem::isContainer() const { return qmlItemNode().modelNode().metaInfo().isContainer(); } QmlItemNode FormEditorItem::qmlItemNode() const { return m_qmlItemNode; } } <commit_msg>Paint a yellow frame if the item anchored<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "formeditoritem.h" #include "formeditorscene.h" #include "formeditornodeinstanceview.h" #include "selectiontool.h" #include <modelnode.h> #include <nodemetainfo.h> #include <widgetqueryview.h> #include <QGraphicsSceneMouseEvent> #include <QDebug> #include <QPainter> #include <QStyleOptionGraphicsItem> #include <QGraphicsView> #include <QTimeLine> #include <cmath> #include <invalidmodelnodeexception.h> #include <invalidnodestateexception.h> namespace QmlDesigner { FormEditorScene *FormEditorItem::scene() const { return qobject_cast<FormEditorScene*>(QGraphicsItem::scene()); } FormEditorItem::FormEditorItem(const QmlItemNode &qmlItemNode, FormEditorScene* scene) : QGraphicsObject(scene->formLayerItem()), m_snappingLineCreator(this), m_qmlItemNode(qmlItemNode), m_borderWidth(1.0), m_opacity(0.6), m_highlightBoundingRect(false) { setCacheMode(QGraphicsItem::DeviceCoordinateCache); setup(); } void FormEditorItem::setup() { if (qmlItemNode().hasInstanceParent()) setParentItem(scene()->itemForQmlItemNode(qmlItemNode().instanceParent().toQmlItemNode())); if (QGraphicsItem::parentItem() == scene()->formLayerItem()) m_borderWidth = 0.0; setFlag(QGraphicsItem::ItemIsMovable, true); updateGeometry(); updateVisibilty(); } QRectF FormEditorItem::boundingRect() const { return m_boundingRect; } void FormEditorItem::updateGeometry() { prepareGeometryChange(); m_boundingRect = qmlItemNode().instanceBoundingRect().adjusted(0, 0, 1., 1.); setTransform(qmlItemNode().instanceTransform()); setTransform(m_attentionTransform, true); //the property for zValue is called z in QGraphicsObject Q_ASSERT(qmlItemNode().instanceValue("z").isValid()); setZValue(qmlItemNode().instanceValue("z").toDouble()); } void FormEditorItem::updateVisibilty() { // setVisible(nodeInstance().isVisible()); // setOpacity(nodeInstance().opacity()); } void FormEditorItem::showAttention() { if (m_attentionTimeLine.isNull()) { m_attentionTimeLine = new QTimeLine(500, this); m_attentionTimeLine->setCurveShape(QTimeLine::SineCurve); connect(m_attentionTimeLine.data(), SIGNAL(valueChanged(qreal)), SLOT(changeAttention(qreal))); connect(m_attentionTimeLine.data(), SIGNAL(finished()), m_attentionTimeLine.data(), SLOT(deleteLater())); m_attentionTimeLine->start(); } } void FormEditorItem::changeAttention(qreal value) { if (QGraphicsItem::parentItem() == scene()->formLayerItem()) { setAttentionHighlight(value); } else { setAttentionHighlight(value); setAttentionScale(value); } } FormEditorView *FormEditorItem::formEditorView() const { return scene()->editorView(); } void FormEditorItem::setAttentionScale(double sinusScale) { if (!qFuzzyIsNull(sinusScale)) { double scale = std::sqrt(sinusScale); m_attentionTransform.reset(); QPointF centerPoint(qmlItemNode().instanceBoundingRect().center()); m_attentionTransform.translate(centerPoint.x(), centerPoint.y()); m_attentionTransform.scale(scale * 0.15 + 1.0, scale * 0.15 + 1.0); m_attentionTransform.translate(-centerPoint.x(), -centerPoint.y()); m_inverseAttentionTransform = m_attentionTransform.inverted(); prepareGeometryChange(); setTransform(qmlItemNode().instanceTransform()); setTransform(m_attentionTransform, true); } else { m_attentionTransform.reset(); prepareGeometryChange(); setTransform(qmlItemNode().instanceTransform()); } } void FormEditorItem::setAttentionHighlight(double value) { m_opacity = 0.6 + value; if (QGraphicsItem::parentItem() == scene()->formLayerItem()) m_borderWidth = value * 4; else m_borderWidth = 1. + value * 3; update(); } void FormEditorItem::setHighlightBoundingRect(bool highlight) { if (m_highlightBoundingRect != highlight) { m_highlightBoundingRect = highlight; update(); } } FormEditorItem::~FormEditorItem() { scene()->removeItemFromHash(this); } /* \brief returns the parent item skipping all proxyItem*/ FormEditorItem *FormEditorItem::parentItem() const { return qgraphicsitem_cast<FormEditorItem*> (QGraphicsItem::parentItem()); } FormEditorItem* FormEditorItem::fromQGraphicsItem(QGraphicsItem *graphicsItem) { return qgraphicsitem_cast<FormEditorItem*>(graphicsItem); } //static QRectF alignedRect(const QRectF &rect) //{ // QRectF alignedRect(rect); // alignedRect.setTop(std::floor(rect.top()) + 0.5); // alignedRect.setBottom(std::floor(rect.bottom()) + 0.5); // alignedRect.setLeft(std::floor(rect.left()) + 0.5); // alignedRect.setRight(std::floor(rect.right()) + 0.5); // // return alignedRect; //} void FormEditorItem::paintBoundingRect(QPainter *painter) const { if (QGraphicsItem::parentItem() == scene()->formLayerItem() && qFuzzyIsNull(m_borderWidth)) return; QPen pen; pen.setJoinStyle(Qt::MiterJoin); switch(scene()->paintMode()) { case FormEditorScene::AnchorMode: { pen.setColor(Qt::black); pen.setWidth(m_borderWidth); } break; case FormEditorScene::NormalMode: { QColor frameColor("#AAAAAA"); if (qmlItemNode().anchors().instanceHasAnchors()) frameColor = QColor("#ffff00"); if (scene()->showBoundingRects()) { if (m_highlightBoundingRect) pen.setColor(frameColor); else pen.setColor(frameColor.darker(150)); } else { if (m_highlightBoundingRect) pen.setColor(frameColor); else pen.setColor(Qt::transparent); } } break; } painter->setPen(pen); // int offset = m_borderWidth / 2; const QRectF br = boundingRect(); if (br.isValid()) painter->drawRect(br.adjusted(0., 0., -1., -1.)); } void FormEditorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if (!qmlItemNode().isValid()) return; painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); switch(scene()->paintMode()) { case FormEditorScene::AnchorMode: painter->setOpacity(m_opacity); break; case FormEditorScene::NormalMode: painter->setOpacity(qmlItemNode().instanceValue("opacity").toDouble()); break; } qmlItemNode().paintInstance(painter); painter->setRenderHint(QPainter::Antialiasing, false); if (!qmlItemNode().isRootModelNode()) paintBoundingRect(painter); painter->restore(); } AbstractFormEditorTool* FormEditorItem::tool() const { return static_cast<FormEditorScene*>(scene())->currentTool(); } SnapLineMap FormEditorItem::topSnappingLines() const { return m_snappingLineCreator.topLines(); } SnapLineMap FormEditorItem::bottomSnappingLines() const { return m_snappingLineCreator.bottomLines(); } SnapLineMap FormEditorItem::leftSnappingLines() const { return m_snappingLineCreator.leftLines(); } SnapLineMap FormEditorItem::rightSnappingLines() const { return m_snappingLineCreator.rightLines(); } SnapLineMap FormEditorItem::horizontalCenterSnappingLines() const { return m_snappingLineCreator.horizontalCenterLines(); } SnapLineMap FormEditorItem::verticalCenterSnappingLines() const { return m_snappingLineCreator.verticalCenterLines(); } SnapLineMap FormEditorItem::topSnappingOffsets() const { return m_snappingLineCreator.topOffsets(); } SnapLineMap FormEditorItem::bottomSnappingOffsets() const { return m_snappingLineCreator.bottomOffsets(); } SnapLineMap FormEditorItem::leftSnappingOffsets() const { return m_snappingLineCreator.leftOffsets(); } SnapLineMap FormEditorItem::rightSnappingOffsets() const { return m_snappingLineCreator.rightOffsets(); } void FormEditorItem::updateSnappingLines(const QList<FormEditorItem*> &exceptionList, FormEditorItem *transformationSpaceItem) { m_snappingLineCreator.update(exceptionList, transformationSpaceItem); } QList<FormEditorItem*> FormEditorItem::childFormEditorItems() const { QList<FormEditorItem*> formEditorItemList; foreach (QGraphicsItem *item, childItems()) { FormEditorItem *formEditorItem = fromQGraphicsItem(item); if (formEditorItem) formEditorItemList.append(formEditorItem); } return formEditorItemList; } bool FormEditorItem::isContainer() const { return qmlItemNode().modelNode().metaInfo().isContainer(); } QmlItemNode FormEditorItem::qmlItemNode() const { return m_qmlItemNode; } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "maemorunconfiguration.h" #include "maemodeployables.h" #include "maemodeploystep.h" #include "maemodeviceconfiglistmodel.h" #include "maemoglobal.h" #include "maemoqemumanager.h" #include "maemoremotemountsmodel.h" #include "maemorunconfigurationwidget.h" #include "maemotoolchain.h" #include "qtoutputformatter.h" #include <coreplugin/icore.h> #include <coreplugin/messagemanager.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/session.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4project.h> #include <utils/qtcassert.h> #include <QtCore/QStringBuilder> namespace Qt4ProjectManager { namespace Internal { namespace { const bool DefaultUseRemoteGdbValue = false; // TODO: Make true once it works reliably on Windows } // anonymous namespace using namespace ProjectExplorer; MaemoRunConfiguration::MaemoRunConfiguration(Qt4Target *parent, const QString &proFilePath) : RunConfiguration(parent, QLatin1String(MAEMO_RC_ID)) , m_proFilePath(proFilePath) , m_useRemoteGdb(DefaultUseRemoteGdbValue) , m_baseEnvironmentBase(SystemEnvironmentBase) , m_validParse(parent->qt4Project()->validParse(m_proFilePath)) { init(); } MaemoRunConfiguration::MaemoRunConfiguration(Qt4Target *parent, MaemoRunConfiguration *source) : RunConfiguration(parent, source) , m_proFilePath(source->m_proFilePath) , m_gdbPath(source->m_gdbPath) , m_arguments(source->m_arguments) , m_useRemoteGdb(source->useRemoteGdb()) , m_baseEnvironmentBase(source->m_baseEnvironmentBase) , m_systemEnvironment(source->m_systemEnvironment) , m_userEnvironmentChanges(source->m_userEnvironmentChanges) , m_validParse(source->m_validParse) { init(); } void MaemoRunConfiguration::init() { setDefaultDisplayName(defaultDisplayName()); setUseCppDebugger(true); setUseQmlDebugger(false); m_remoteMounts = new MaemoRemoteMountsModel(this); connect(target(), SIGNAL(activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration*)), this, SLOT(handleDeployConfigChanged())); handleDeployConfigChanged(); Qt4Project *pro = qt4Target()->qt4Project(); connect(pro, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)), this, SLOT(proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool))); connect(pro, SIGNAL(profFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode *)), this, SLOT(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode*))); } MaemoRunConfiguration::~MaemoRunConfiguration() { } Qt4Target *MaemoRunConfiguration::qt4Target() const { return static_cast<Qt4Target *>(target()); } Qt4BuildConfiguration *MaemoRunConfiguration::activeQt4BuildConfiguration() const { return static_cast<Qt4BuildConfiguration *>(activeBuildConfiguration()); } bool MaemoRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *config) const { if (!m_validParse) return false; Qt4BuildConfiguration *qt4bc = qobject_cast<Qt4BuildConfiguration*>(config); QTC_ASSERT(qt4bc, return false); ToolChain::ToolChainType type = qt4bc->toolChainType(); return type == ToolChain::GCC_MAEMO; } QWidget *MaemoRunConfiguration::createConfigurationWidget() { return new MaemoRunConfigurationWidget(this); } ProjectExplorer::OutputFormatter *MaemoRunConfiguration::createOutputFormatter() const { return new QtOutputFormatter(qt4Target()->qt4Project()); } void MaemoRunConfiguration::handleParseState(bool success) { bool enabled = isEnabled(); m_validParse = success; if (enabled != isEnabled()) { qDebug()<<"Emitting isEnabledChanged()"<<!enabled; emit isEnabledChanged(!enabled); } } void MaemoRunConfiguration::proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode *pro) { if (m_proFilePath != pro->path()) return; qDebug()<<"proFileInvalidated"; handleParseState(false); } void MaemoRunConfiguration::proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode *pro, bool success) { if (m_proFilePath == pro->path()) { handleParseState(success); emit targetInformationChanged(); } } QVariantMap MaemoRunConfiguration::toMap() const { QVariantMap map(RunConfiguration::toMap()); map.insert(ArgumentsKey, m_arguments); const QDir dir = QDir(target()->project()->projectDirectory()); map.insert(ProFileKey, dir.relativeFilePath(m_proFilePath)); map.insert(UseRemoteGdbKey, useRemoteGdb()); map.insert(BaseEnvironmentBaseKey, m_baseEnvironmentBase); map.insert(UserEnvironmentChangesKey, Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges)); map.unite(m_remoteMounts->toMap()); return map; } bool MaemoRunConfiguration::fromMap(const QVariantMap &map) { if (!RunConfiguration::fromMap(map)) return false; m_arguments = map.value(ArgumentsKey).toStringList(); const QDir dir = QDir(target()->project()->projectDirectory()); m_proFilePath = dir.filePath(map.value(ProFileKey).toString()); m_useRemoteGdb = map.value(UseRemoteGdbKey, DefaultUseRemoteGdbValue).toBool(); m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(map.value(UserEnvironmentChangesKey) .toStringList()); m_baseEnvironmentBase = static_cast<BaseEnvironmentBase> (map.value(BaseEnvironmentBaseKey, SystemEnvironmentBase).toInt()); m_remoteMounts->fromMap(map); m_validParse = qt4Target()->qt4Project()->validParse(m_proFilePath); setDefaultDisplayName(defaultDisplayName()); return true; } QString MaemoRunConfiguration::defaultDisplayName() { if (!m_proFilePath.isEmpty()) return (QFileInfo(m_proFilePath).completeBaseName()); //: Maemo run configuration default display name return tr("Run on Maemo device"); } MaemoDeviceConfig MaemoRunConfiguration::deviceConfig() const { return deployStep()->deviceConfigModel()->current(); } const MaemoToolChain *MaemoRunConfiguration::toolchain() const { Qt4BuildConfiguration *qt4bc(activeQt4BuildConfiguration()); QTC_ASSERT(qt4bc, return 0); MaemoToolChain *tc = dynamic_cast<MaemoToolChain *>(qt4bc->toolChain()); QTC_ASSERT(tc != 0, return 0); return tc; } const QString MaemoRunConfiguration::gdbCmd() const { if (const MaemoToolChain *tc = toolchain()) return QDir::toNativeSeparators(tc->targetRoot() + QLatin1String("/bin/gdb")); return QString(); } MaemoDeployStep *MaemoRunConfiguration::deployStep() const { MaemoDeployStep * const step = MaemoGlobal::buildStep<MaemoDeployStep>(target()->activeDeployConfiguration()); Q_ASSERT_X(step, Q_FUNC_INFO, "Impossible: Maemo build configuration without deploy step."); return step; } QString MaemoRunConfiguration::maddeRoot() const { if (const MaemoToolChain *tc = toolchain()) return tc->maddeRoot(); return QString(); } const QString MaemoRunConfiguration::sysRoot() const { if (const MaemoToolChain *tc = toolchain()) return tc->sysrootRoot(); return QString(); } const QString MaemoRunConfiguration::targetRoot() const { if (const MaemoToolChain *tc = toolchain()) return tc->targetRoot(); return QString(); } const QStringList MaemoRunConfiguration::arguments() const { return m_arguments; } const QString MaemoRunConfiguration::dumperLib() const { Qt4BuildConfiguration *qt4bc(activeQt4BuildConfiguration()); return qt4bc->qtVersion()->debuggingHelperLibrary(); } QString MaemoRunConfiguration::localDirToMountForRemoteGdb() const { const QString projectDir = QDir::fromNativeSeparators(QDir::cleanPath(activeBuildConfiguration() ->target()->project()->projectDirectory())); const QString execDir = QDir::fromNativeSeparators(QFileInfo(localExecutableFilePath()).path()); const int length = qMin(projectDir.length(), execDir.length()); int lastSeparatorPos = 0; for (int i = 0; i < length; ++i) { if (projectDir.at(i) != execDir.at(i)) return projectDir.left(lastSeparatorPos); if (projectDir.at(i) == QLatin1Char('/')) lastSeparatorPos = i; } return projectDir.length() == execDir.length() ? projectDir : projectDir.left(lastSeparatorPos); } QString MaemoRunConfiguration::localExecutableFilePath() const { TargetInformation ti = qt4Target()->qt4Project()->rootProjectNode() ->targetInformation(m_proFilePath); if (!ti.valid) return QString(); return QDir::cleanPath(ti.workingDir + QLatin1Char('/') + ti.target); } QString MaemoRunConfiguration::remoteExecutableFilePath() const { return deployStep()->deployables() ->remoteExecutableFilePath(localExecutableFilePath()); } MaemoPortList MaemoRunConfiguration::freePorts() const { const MaemoDeviceConfig &devConfig = deviceConfig(); const Qt4BuildConfiguration * const qt4bc = activeQt4BuildConfiguration(); if (devConfig.type == MaemoDeviceConfig::Simulator && qt4bc) { Runtime rt; const int id = qt4bc->qtVersion()->uniqueId(); if (MaemoQemuManager::instance().runtimeForQtVersion(id, &rt)) return rt.m_freePorts; } return devConfig.freePorts(); } bool MaemoRunConfiguration::useRemoteGdb() const { return m_useRemoteGdb && toolchain()->allowsRemoteMounts(); } void MaemoRunConfiguration::setArguments(const QStringList &args) { m_arguments = args; } MaemoRunConfiguration::DebuggingType MaemoRunConfiguration::debuggingType() const { if (!toolchain() || !toolchain()->allowsQmlDebugging()) return DebugCppOnly; if (useCppDebugger()) { if (useQmlDebugger()) return DebugCppAndQml; return DebugCppOnly; } return DebugQmlOnly; } int MaemoRunConfiguration::portsUsedByDebuggers() const { switch (debuggingType()) { case DebugCppOnly: case DebugQmlOnly: return 1; case DebugCppAndQml: default: return 2; } } void MaemoRunConfiguration::updateDeviceConfigurations() { emit deviceConfigurationChanged(target()); } void MaemoRunConfiguration::handleDeployConfigChanged() { const QList<DeployConfiguration *> &deployConfigs = target()->deployConfigurations(); DeployConfiguration * const activeDeployConf = target()->activeDeployConfiguration(); for (int i = 0; i < deployConfigs.count(); ++i) { MaemoDeployStep * const step = MaemoGlobal::buildStep<MaemoDeployStep>(deployConfigs.at(i)); MaemoDeviceConfigListModel * const devConfigModel = step->deviceConfigModel(); if (deployConfigs.at(i) == activeDeployConf) { connect(devConfigModel, SIGNAL(currentChanged()), this, SLOT(updateDeviceConfigurations())); connect(devConfigModel, SIGNAL(modelReset()), this, SLOT(updateDeviceConfigurations())); } else { disconnect(devConfigModel, 0, this, SLOT(updateDeviceConfigurations())); } } updateDeviceConfigurations(); } QString MaemoRunConfiguration::baseEnvironmentText() const { if (m_baseEnvironmentBase == CleanEnvironmentBase) return tr("Clean Environment"); else if (m_baseEnvironmentBase == SystemEnvironmentBase) return tr("System Environment"); return QString(); } MaemoRunConfiguration::BaseEnvironmentBase MaemoRunConfiguration::baseEnvironmentBase() const { return m_baseEnvironmentBase; } void MaemoRunConfiguration::setBaseEnvironmentBase(BaseEnvironmentBase env) { if (m_baseEnvironmentBase != env) { m_baseEnvironmentBase = env; emit baseEnvironmentChanged(); } } Utils::Environment MaemoRunConfiguration::environment() const { Utils::Environment env = baseEnvironment(); env.modify(userEnvironmentChanges()); return env; } Utils::Environment MaemoRunConfiguration::baseEnvironment() const { return (m_baseEnvironmentBase == SystemEnvironmentBase ? systemEnvironment() : Utils::Environment()); } QList<Utils::EnvironmentItem> MaemoRunConfiguration::userEnvironmentChanges() const { return m_userEnvironmentChanges; } void MaemoRunConfiguration::setUserEnvironmentChanges( const QList<Utils::EnvironmentItem> &diff) { if (m_userEnvironmentChanges != diff) { m_userEnvironmentChanges = diff; emit userEnvironmentChangesChanged(diff); } } Utils::Environment MaemoRunConfiguration::systemEnvironment() const { return m_systemEnvironment; } void MaemoRunConfiguration::setSystemEnvironment(const Utils::Environment &environment) { if (m_systemEnvironment.size() == 0 || m_systemEnvironment != environment) { m_systemEnvironment = environment; emit systemEnvironmentChanged(); } } } // namespace Internal } // namespace Qt4ProjectManager <commit_msg>Maemo: Fix typo in connect() call.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "maemorunconfiguration.h" #include "maemodeployables.h" #include "maemodeploystep.h" #include "maemodeviceconfiglistmodel.h" #include "maemoglobal.h" #include "maemoqemumanager.h" #include "maemoremotemountsmodel.h" #include "maemorunconfigurationwidget.h" #include "maemotoolchain.h" #include "qtoutputformatter.h" #include <coreplugin/icore.h> #include <coreplugin/messagemanager.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/session.h> #include <qt4projectmanager/qt4buildconfiguration.h> #include <qt4projectmanager/qt4project.h> #include <utils/qtcassert.h> #include <QtCore/QStringBuilder> namespace Qt4ProjectManager { namespace Internal { namespace { const bool DefaultUseRemoteGdbValue = false; // TODO: Make true once it works reliably on Windows } // anonymous namespace using namespace ProjectExplorer; MaemoRunConfiguration::MaemoRunConfiguration(Qt4Target *parent, const QString &proFilePath) : RunConfiguration(parent, QLatin1String(MAEMO_RC_ID)) , m_proFilePath(proFilePath) , m_useRemoteGdb(DefaultUseRemoteGdbValue) , m_baseEnvironmentBase(SystemEnvironmentBase) , m_validParse(parent->qt4Project()->validParse(m_proFilePath)) { init(); } MaemoRunConfiguration::MaemoRunConfiguration(Qt4Target *parent, MaemoRunConfiguration *source) : RunConfiguration(parent, source) , m_proFilePath(source->m_proFilePath) , m_gdbPath(source->m_gdbPath) , m_arguments(source->m_arguments) , m_useRemoteGdb(source->useRemoteGdb()) , m_baseEnvironmentBase(source->m_baseEnvironmentBase) , m_systemEnvironment(source->m_systemEnvironment) , m_userEnvironmentChanges(source->m_userEnvironmentChanges) , m_validParse(source->m_validParse) { init(); } void MaemoRunConfiguration::init() { setDefaultDisplayName(defaultDisplayName()); setUseCppDebugger(true); setUseQmlDebugger(false); m_remoteMounts = new MaemoRemoteMountsModel(this); connect(target(), SIGNAL(activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration*)), this, SLOT(handleDeployConfigChanged())); handleDeployConfigChanged(); Qt4Project *pro = qt4Target()->qt4Project(); connect(pro, SIGNAL(proFileUpdated(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool)), this, SLOT(proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode*,bool))); connect(pro, SIGNAL(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode *)), this, SLOT(proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode*))); } MaemoRunConfiguration::~MaemoRunConfiguration() { } Qt4Target *MaemoRunConfiguration::qt4Target() const { return static_cast<Qt4Target *>(target()); } Qt4BuildConfiguration *MaemoRunConfiguration::activeQt4BuildConfiguration() const { return static_cast<Qt4BuildConfiguration *>(activeBuildConfiguration()); } bool MaemoRunConfiguration::isEnabled(ProjectExplorer::BuildConfiguration *config) const { if (!m_validParse) return false; Qt4BuildConfiguration *qt4bc = qobject_cast<Qt4BuildConfiguration*>(config); QTC_ASSERT(qt4bc, return false); ToolChain::ToolChainType type = qt4bc->toolChainType(); return type == ToolChain::GCC_MAEMO; } QWidget *MaemoRunConfiguration::createConfigurationWidget() { return new MaemoRunConfigurationWidget(this); } ProjectExplorer::OutputFormatter *MaemoRunConfiguration::createOutputFormatter() const { return new QtOutputFormatter(qt4Target()->qt4Project()); } void MaemoRunConfiguration::handleParseState(bool success) { bool enabled = isEnabled(); m_validParse = success; if (enabled != isEnabled()) { qDebug()<<"Emitting isEnabledChanged()"<<!enabled; emit isEnabledChanged(!enabled); } } void MaemoRunConfiguration::proFileInvalidated(Qt4ProjectManager::Internal::Qt4ProFileNode *pro) { if (m_proFilePath != pro->path()) return; qDebug()<<"proFileInvalidated"; handleParseState(false); } void MaemoRunConfiguration::proFileUpdate(Qt4ProjectManager::Internal::Qt4ProFileNode *pro, bool success) { if (m_proFilePath == pro->path()) { handleParseState(success); emit targetInformationChanged(); } } QVariantMap MaemoRunConfiguration::toMap() const { QVariantMap map(RunConfiguration::toMap()); map.insert(ArgumentsKey, m_arguments); const QDir dir = QDir(target()->project()->projectDirectory()); map.insert(ProFileKey, dir.relativeFilePath(m_proFilePath)); map.insert(UseRemoteGdbKey, useRemoteGdb()); map.insert(BaseEnvironmentBaseKey, m_baseEnvironmentBase); map.insert(UserEnvironmentChangesKey, Utils::EnvironmentItem::toStringList(m_userEnvironmentChanges)); map.unite(m_remoteMounts->toMap()); return map; } bool MaemoRunConfiguration::fromMap(const QVariantMap &map) { if (!RunConfiguration::fromMap(map)) return false; m_arguments = map.value(ArgumentsKey).toStringList(); const QDir dir = QDir(target()->project()->projectDirectory()); m_proFilePath = dir.filePath(map.value(ProFileKey).toString()); m_useRemoteGdb = map.value(UseRemoteGdbKey, DefaultUseRemoteGdbValue).toBool(); m_userEnvironmentChanges = Utils::EnvironmentItem::fromStringList(map.value(UserEnvironmentChangesKey) .toStringList()); m_baseEnvironmentBase = static_cast<BaseEnvironmentBase> (map.value(BaseEnvironmentBaseKey, SystemEnvironmentBase).toInt()); m_remoteMounts->fromMap(map); m_validParse = qt4Target()->qt4Project()->validParse(m_proFilePath); setDefaultDisplayName(defaultDisplayName()); return true; } QString MaemoRunConfiguration::defaultDisplayName() { if (!m_proFilePath.isEmpty()) return (QFileInfo(m_proFilePath).completeBaseName()); //: Maemo run configuration default display name return tr("Run on Maemo device"); } MaemoDeviceConfig MaemoRunConfiguration::deviceConfig() const { return deployStep()->deviceConfigModel()->current(); } const MaemoToolChain *MaemoRunConfiguration::toolchain() const { Qt4BuildConfiguration *qt4bc(activeQt4BuildConfiguration()); QTC_ASSERT(qt4bc, return 0); MaemoToolChain *tc = dynamic_cast<MaemoToolChain *>(qt4bc->toolChain()); QTC_ASSERT(tc != 0, return 0); return tc; } const QString MaemoRunConfiguration::gdbCmd() const { if (const MaemoToolChain *tc = toolchain()) return QDir::toNativeSeparators(tc->targetRoot() + QLatin1String("/bin/gdb")); return QString(); } MaemoDeployStep *MaemoRunConfiguration::deployStep() const { MaemoDeployStep * const step = MaemoGlobal::buildStep<MaemoDeployStep>(target()->activeDeployConfiguration()); Q_ASSERT_X(step, Q_FUNC_INFO, "Impossible: Maemo build configuration without deploy step."); return step; } QString MaemoRunConfiguration::maddeRoot() const { if (const MaemoToolChain *tc = toolchain()) return tc->maddeRoot(); return QString(); } const QString MaemoRunConfiguration::sysRoot() const { if (const MaemoToolChain *tc = toolchain()) return tc->sysrootRoot(); return QString(); } const QString MaemoRunConfiguration::targetRoot() const { if (const MaemoToolChain *tc = toolchain()) return tc->targetRoot(); return QString(); } const QStringList MaemoRunConfiguration::arguments() const { return m_arguments; } const QString MaemoRunConfiguration::dumperLib() const { Qt4BuildConfiguration *qt4bc(activeQt4BuildConfiguration()); return qt4bc->qtVersion()->debuggingHelperLibrary(); } QString MaemoRunConfiguration::localDirToMountForRemoteGdb() const { const QString projectDir = QDir::fromNativeSeparators(QDir::cleanPath(activeBuildConfiguration() ->target()->project()->projectDirectory())); const QString execDir = QDir::fromNativeSeparators(QFileInfo(localExecutableFilePath()).path()); const int length = qMin(projectDir.length(), execDir.length()); int lastSeparatorPos = 0; for (int i = 0; i < length; ++i) { if (projectDir.at(i) != execDir.at(i)) return projectDir.left(lastSeparatorPos); if (projectDir.at(i) == QLatin1Char('/')) lastSeparatorPos = i; } return projectDir.length() == execDir.length() ? projectDir : projectDir.left(lastSeparatorPos); } QString MaemoRunConfiguration::localExecutableFilePath() const { TargetInformation ti = qt4Target()->qt4Project()->rootProjectNode() ->targetInformation(m_proFilePath); if (!ti.valid) return QString(); return QDir::cleanPath(ti.workingDir + QLatin1Char('/') + ti.target); } QString MaemoRunConfiguration::remoteExecutableFilePath() const { return deployStep()->deployables() ->remoteExecutableFilePath(localExecutableFilePath()); } MaemoPortList MaemoRunConfiguration::freePorts() const { const MaemoDeviceConfig &devConfig = deviceConfig(); const Qt4BuildConfiguration * const qt4bc = activeQt4BuildConfiguration(); if (devConfig.type == MaemoDeviceConfig::Simulator && qt4bc) { Runtime rt; const int id = qt4bc->qtVersion()->uniqueId(); if (MaemoQemuManager::instance().runtimeForQtVersion(id, &rt)) return rt.m_freePorts; } return devConfig.freePorts(); } bool MaemoRunConfiguration::useRemoteGdb() const { return m_useRemoteGdb && toolchain()->allowsRemoteMounts(); } void MaemoRunConfiguration::setArguments(const QStringList &args) { m_arguments = args; } MaemoRunConfiguration::DebuggingType MaemoRunConfiguration::debuggingType() const { if (!toolchain() || !toolchain()->allowsQmlDebugging()) return DebugCppOnly; if (useCppDebugger()) { if (useQmlDebugger()) return DebugCppAndQml; return DebugCppOnly; } return DebugQmlOnly; } int MaemoRunConfiguration::portsUsedByDebuggers() const { switch (debuggingType()) { case DebugCppOnly: case DebugQmlOnly: return 1; case DebugCppAndQml: default: return 2; } } void MaemoRunConfiguration::updateDeviceConfigurations() { emit deviceConfigurationChanged(target()); } void MaemoRunConfiguration::handleDeployConfigChanged() { const QList<DeployConfiguration *> &deployConfigs = target()->deployConfigurations(); DeployConfiguration * const activeDeployConf = target()->activeDeployConfiguration(); for (int i = 0; i < deployConfigs.count(); ++i) { MaemoDeployStep * const step = MaemoGlobal::buildStep<MaemoDeployStep>(deployConfigs.at(i)); MaemoDeviceConfigListModel * const devConfigModel = step->deviceConfigModel(); if (deployConfigs.at(i) == activeDeployConf) { connect(devConfigModel, SIGNAL(currentChanged()), this, SLOT(updateDeviceConfigurations())); connect(devConfigModel, SIGNAL(modelReset()), this, SLOT(updateDeviceConfigurations())); } else { disconnect(devConfigModel, 0, this, SLOT(updateDeviceConfigurations())); } } updateDeviceConfigurations(); } QString MaemoRunConfiguration::baseEnvironmentText() const { if (m_baseEnvironmentBase == CleanEnvironmentBase) return tr("Clean Environment"); else if (m_baseEnvironmentBase == SystemEnvironmentBase) return tr("System Environment"); return QString(); } MaemoRunConfiguration::BaseEnvironmentBase MaemoRunConfiguration::baseEnvironmentBase() const { return m_baseEnvironmentBase; } void MaemoRunConfiguration::setBaseEnvironmentBase(BaseEnvironmentBase env) { if (m_baseEnvironmentBase != env) { m_baseEnvironmentBase = env; emit baseEnvironmentChanged(); } } Utils::Environment MaemoRunConfiguration::environment() const { Utils::Environment env = baseEnvironment(); env.modify(userEnvironmentChanges()); return env; } Utils::Environment MaemoRunConfiguration::baseEnvironment() const { return (m_baseEnvironmentBase == SystemEnvironmentBase ? systemEnvironment() : Utils::Environment()); } QList<Utils::EnvironmentItem> MaemoRunConfiguration::userEnvironmentChanges() const { return m_userEnvironmentChanges; } void MaemoRunConfiguration::setUserEnvironmentChanges( const QList<Utils::EnvironmentItem> &diff) { if (m_userEnvironmentChanges != diff) { m_userEnvironmentChanges = diff; emit userEnvironmentChangesChanged(diff); } } Utils::Environment MaemoRunConfiguration::systemEnvironment() const { return m_systemEnvironment; } void MaemoRunConfiguration::setSystemEnvironment(const Utils::Environment &environment) { if (m_systemEnvironment.size() == 0 || m_systemEnvironment != environment) { m_systemEnvironment = environment; emit systemEnvironmentChanged(); } } } // namespace Internal } // namespace Qt4ProjectManager <|endoftext|>
<commit_before>#include <ncurses.h> #include <iostream> #include <gtest/gtest.h> #include <Utils/Utils.h> TEST(UtilsTest, LowercaseAllLowerCase) { std::string s{"hello world"}; auto actual = vis::Utils::lowercase(s); std::string expected{"hello world"}; EXPECT_EQ(expected, actual) << "lowercase must not change an all lowercased string"; } TEST(UtilsTest, LowercaseAllUpperCase) { std::string s{"HELLO WORLD"}; auto actual = vis::Utils::lowercase(s); std::string expected{"hello world"}; EXPECT_EQ(expected, actual) << "lowercase must lowercase an all uppercase string"; } TEST(UtilsTest, LowercaseAllMixedCase) { std::string s{"HeLlo wORLD"}; auto actual = vis::Utils::lowercase(s); std::string expected{"hello world"}; EXPECT_EQ(expected, actual) << "lowercase must lowercase a mixed case string"; } TEST(UtilsTest, LowercaseEmptyString) { std::string s{""}; auto actual = vis::Utils::lowercase(s); std::string expected{""}; EXPECT_EQ(expected, actual) << "lowercase must work with an empty string"; } TEST(UtilsTest, GetHomeDirectory) { auto actual = vis::Utils::get_home_directory(); EXPECT_FALSE(actual.empty()) << "get home directory should not return an empty string"; } TEST(UtilsTest, ToBoolEmptyString) { auto actual = vis::Utils::to_bool(""); EXPECT_FALSE(actual) << "to_bool should return false for empty string"; } TEST(UtilsTest, ToBoolOneString) { auto actual = vis::Utils::to_bool("1"); EXPECT_TRUE(actual) << "to_bool should return false for \"1\""; } TEST(UtilsTest, ToBoolZeroString) { auto actual = vis::Utils::to_bool("0"); EXPECT_FALSE(actual) << "to_bool should return false for \"0\""; } TEST(UtilsTest, ToBoolTrueString) { auto actual = vis::Utils::to_bool("true"); EXPECT_TRUE(actual) << "to_bool should return true for \"true\""; } TEST(UtilsTest, ToBoolTrUeString) { auto actual = vis::Utils::to_bool("trUe"); EXPECT_TRUE(actual) << "to_bool should return true for \"trUe\""; } TEST(UtilsTest, ToBoolFalseString) { auto actual = vis::Utils::to_bool("false"); EXPECT_FALSE(actual) << "to_bool should return true for \"false\""; } TEST(UtilsTest, ToBoolFaLseString) { auto actual = vis::Utils::to_bool("faLse"); EXPECT_FALSE(actual) << "to_bool should return true for \"faLse\""; } TEST(UtilsTest, GetStrFromStrStrUnorderedMap) { std::unordered_map<std::string, std::string> m{ {"a", "a"}, {"b", "b"}, {"c", "c"}}; EXPECT_EQ(std::string{"a"}, vis::Utils::get(m, std::string{"a"}, std::string{""})); EXPECT_EQ(std::string{"b"}, vis::Utils::get(m, std::string{"b"}, std::string{""})); EXPECT_EQ(std::string{""}, vis::Utils::get(m, std::string{"z"}, std::string{""})); EXPECT_EQ(std::string{"d"}, vis::Utils::get(m, std::string{"z"}, std::string{"d"})); } TEST(UtilsTest, GetBoolFromStrStrUnorderedMap) { std::unordered_map<std::string, std::string> m{ {"a", "true"}, {"b", "false"}, {"c", "c"}}; EXPECT_EQ(true, vis::Utils::get(m, std::string{"a"}, true)); EXPECT_EQ(false, vis::Utils::get(m, std::string{"b"}, true)); EXPECT_EQ(true, vis::Utils::get(m, std::string{"z"}, true)); EXPECT_EQ(false, vis::Utils::get(m, std::string{"z"}, false)); } TEST(UtilsTest, GetUintFromStrStrUnorderedMap) { std::unordered_map<std::string, std::string> m{ {"a", "1337"}, {"b", "42"}, {"c", "c"}}; EXPECT_EQ(1337, vis::Utils::get(m, std::string{"a"}, static_cast<uint32_t>(1))); EXPECT_EQ(42, vis::Utils::get(m, std::string{"b"}, static_cast<uint32_t>(1))); EXPECT_EQ(314, vis::Utils::get(m, std::string{"z"}, static_cast<uint32_t>(314))); EXPECT_EQ(0, vis::Utils::get(m, std::string{"z"}, static_cast<uint32_t>(0))); } TEST(UtilsTest, SplitFirstEmptyString) { std::pair<std::string, std::string> p{"hello", "world"}; std::string s{""}; vis::Utils::split_first(s, '=', p); EXPECT_EQ("", p.first); EXPECT_EQ("", p.second); } TEST(UtilsTest, SplitFirstSingleDelimString) { std::pair<std::string, std::string> p{"hello", "world"}; std::string s{"this=isatest"}; vis::Utils::split_first(s, '=', p); EXPECT_EQ("this", p.first); EXPECT_EQ("isatest", p.second); } TEST(UtilsTest, SplitFirstMultiDelimString) { std::pair<std::string, std::string> p{"hello", "world"}; std::string s{"this=isatest=with=more=than=one=delimiter"}; vis::Utils::split_first(s, '=', p); EXPECT_EQ("this", p.first); EXPECT_EQ("isatest=with=more=than=one=delimiter", p.second); } TEST(UtilsTest, SplitEmptyString) { std::vector<std::string> v{"hello", "world"}; std::string s{""}; vis::Utils::split(s, '=', v); EXPECT_TRUE(v.empty()); } TEST(UtilsTest, SplitSingleDelimString) { std::vector<std::string> v{"hello", "world"}; std::string s{"this=isatest"}; vis::Utils::split(s, '=', v); EXPECT_EQ(2, v.size()); EXPECT_EQ("this", v[0]); EXPECT_EQ("isatest", v[1]); } TEST(UtilsTest, SplitMultiDelimString) { std::vector<std::string> v{"hello", "world"}; std::string s{"this=isatest=with=more=than=one=delimiter"}; vis::Utils::split(s, '=', v); EXPECT_EQ(7, v.size()); EXPECT_EQ("this", v[0]); EXPECT_EQ("isatest", v[1]); EXPECT_EQ("with", v[2]); EXPECT_EQ("more", v[3]); EXPECT_EQ("than", v[4]); EXPECT_EQ("one", v[5]); EXPECT_EQ("delimiter", v[6]); } TEST(UtilsTest, ToIntEmptyString) { EXPECT_EQ(0, vis::Utils::to_int("")); } TEST(UtilsTest, ToIntMinInt) { EXPECT_EQ(-2147483648, vis::Utils::to_int("-2147483648")); } TEST(UtilsTest, ToIntMaxInt) { EXPECT_EQ(2147483647, vis::Utils::to_int("2147483647")); } TEST(UtilsTest, ToIntZero) { EXPECT_EQ(0, vis::Utils::to_int("0")); } TEST(UtilsTest, ToUIntEmptyString) { EXPECT_EQ(0, vis::Utils::to_uint("")); } TEST(UtilsTest, ToUIntMaxInt) { EXPECT_EQ(4294967295, vis::Utils::to_uint("4294967295")); } TEST(UtilsTest, ToUInt) { EXPECT_EQ(1337, vis::Utils::to_uint("1337")); } TEST(UtilsTest, ToUIntZero) { EXPECT_EQ(0, vis::Utils::to_uint("0")); } <commit_msg>Remove homeDir test<commit_after>#include <ncurses.h> #include <iostream> #include <gtest/gtest.h> #include <Utils/Utils.h> TEST(UtilsTest, LowercaseAllLowerCase) { std::string s{"hello world"}; auto actual = vis::Utils::lowercase(s); std::string expected{"hello world"}; EXPECT_EQ(expected, actual) << "lowercase must not change an all lowercased string"; } TEST(UtilsTest, LowercaseAllUpperCase) { std::string s{"HELLO WORLD"}; auto actual = vis::Utils::lowercase(s); std::string expected{"hello world"}; EXPECT_EQ(expected, actual) << "lowercase must lowercase an all uppercase string"; } TEST(UtilsTest, LowercaseAllMixedCase) { std::string s{"HeLlo wORLD"}; auto actual = vis::Utils::lowercase(s); std::string expected{"hello world"}; EXPECT_EQ(expected, actual) << "lowercase must lowercase a mixed case string"; } TEST(UtilsTest, LowercaseEmptyString) { std::string s{""}; auto actual = vis::Utils::lowercase(s); std::string expected{""}; EXPECT_EQ(expected, actual) << "lowercase must work with an empty string"; } TEST(UtilsTest, ToBoolEmptyString) { auto actual = vis::Utils::to_bool(""); EXPECT_FALSE(actual) << "to_bool should return false for empty string"; } TEST(UtilsTest, ToBoolOneString) { auto actual = vis::Utils::to_bool("1"); EXPECT_TRUE(actual) << "to_bool should return false for \"1\""; } TEST(UtilsTest, ToBoolZeroString) { auto actual = vis::Utils::to_bool("0"); EXPECT_FALSE(actual) << "to_bool should return false for \"0\""; } TEST(UtilsTest, ToBoolTrueString) { auto actual = vis::Utils::to_bool("true"); EXPECT_TRUE(actual) << "to_bool should return true for \"true\""; } TEST(UtilsTest, ToBoolTrUeString) { auto actual = vis::Utils::to_bool("trUe"); EXPECT_TRUE(actual) << "to_bool should return true for \"trUe\""; } TEST(UtilsTest, ToBoolFalseString) { auto actual = vis::Utils::to_bool("false"); EXPECT_FALSE(actual) << "to_bool should return true for \"false\""; } TEST(UtilsTest, ToBoolFaLseString) { auto actual = vis::Utils::to_bool("faLse"); EXPECT_FALSE(actual) << "to_bool should return true for \"faLse\""; } TEST(UtilsTest, GetStrFromStrStrUnorderedMap) { std::unordered_map<std::string, std::string> m{ {"a", "a"}, {"b", "b"}, {"c", "c"}}; EXPECT_EQ(std::string{"a"}, vis::Utils::get(m, std::string{"a"}, std::string{""})); EXPECT_EQ(std::string{"b"}, vis::Utils::get(m, std::string{"b"}, std::string{""})); EXPECT_EQ(std::string{""}, vis::Utils::get(m, std::string{"z"}, std::string{""})); EXPECT_EQ(std::string{"d"}, vis::Utils::get(m, std::string{"z"}, std::string{"d"})); } TEST(UtilsTest, GetBoolFromStrStrUnorderedMap) { std::unordered_map<std::string, std::string> m{ {"a", "true"}, {"b", "false"}, {"c", "c"}}; EXPECT_EQ(true, vis::Utils::get(m, std::string{"a"}, true)); EXPECT_EQ(false, vis::Utils::get(m, std::string{"b"}, true)); EXPECT_EQ(true, vis::Utils::get(m, std::string{"z"}, true)); EXPECT_EQ(false, vis::Utils::get(m, std::string{"z"}, false)); } TEST(UtilsTest, GetUintFromStrStrUnorderedMap) { std::unordered_map<std::string, std::string> m{ {"a", "1337"}, {"b", "42"}, {"c", "c"}}; EXPECT_EQ(1337, vis::Utils::get(m, std::string{"a"}, static_cast<uint32_t>(1))); EXPECT_EQ(42, vis::Utils::get(m, std::string{"b"}, static_cast<uint32_t>(1))); EXPECT_EQ(314, vis::Utils::get(m, std::string{"z"}, static_cast<uint32_t>(314))); EXPECT_EQ(0, vis::Utils::get(m, std::string{"z"}, static_cast<uint32_t>(0))); } TEST(UtilsTest, SplitFirstEmptyString) { std::pair<std::string, std::string> p{"hello", "world"}; std::string s{""}; vis::Utils::split_first(s, '=', p); EXPECT_EQ("", p.first); EXPECT_EQ("", p.second); } TEST(UtilsTest, SplitFirstSingleDelimString) { std::pair<std::string, std::string> p{"hello", "world"}; std::string s{"this=isatest"}; vis::Utils::split_first(s, '=', p); EXPECT_EQ("this", p.first); EXPECT_EQ("isatest", p.second); } TEST(UtilsTest, SplitFirstMultiDelimString) { std::pair<std::string, std::string> p{"hello", "world"}; std::string s{"this=isatest=with=more=than=one=delimiter"}; vis::Utils::split_first(s, '=', p); EXPECT_EQ("this", p.first); EXPECT_EQ("isatest=with=more=than=one=delimiter", p.second); } TEST(UtilsTest, SplitEmptyString) { std::vector<std::string> v{"hello", "world"}; std::string s{""}; vis::Utils::split(s, '=', v); EXPECT_TRUE(v.empty()); } TEST(UtilsTest, SplitSingleDelimString) { std::vector<std::string> v{"hello", "world"}; std::string s{"this=isatest"}; vis::Utils::split(s, '=', v); EXPECT_EQ(2, v.size()); EXPECT_EQ("this", v[0]); EXPECT_EQ("isatest", v[1]); } TEST(UtilsTest, SplitMultiDelimString) { std::vector<std::string> v{"hello", "world"}; std::string s{"this=isatest=with=more=than=one=delimiter"}; vis::Utils::split(s, '=', v); EXPECT_EQ(7, v.size()); EXPECT_EQ("this", v[0]); EXPECT_EQ("isatest", v[1]); EXPECT_EQ("with", v[2]); EXPECT_EQ("more", v[3]); EXPECT_EQ("than", v[4]); EXPECT_EQ("one", v[5]); EXPECT_EQ("delimiter", v[6]); } TEST(UtilsTest, ToIntEmptyString) { EXPECT_EQ(0, vis::Utils::to_int("")); } TEST(UtilsTest, ToIntMinInt) { EXPECT_EQ(-2147483648, vis::Utils::to_int("-2147483648")); } TEST(UtilsTest, ToIntMaxInt) { EXPECT_EQ(2147483647, vis::Utils::to_int("2147483647")); } TEST(UtilsTest, ToIntZero) { EXPECT_EQ(0, vis::Utils::to_int("0")); } TEST(UtilsTest, ToUIntEmptyString) { EXPECT_EQ(0, vis::Utils::to_uint("")); } TEST(UtilsTest, ToUIntMaxInt) { EXPECT_EQ(4294967295, vis::Utils::to_uint("4294967295")); } TEST(UtilsTest, ToUInt) { EXPECT_EQ(1337, vis::Utils::to_uint("1337")); } TEST(UtilsTest, ToUIntZero) { EXPECT_EQ(0, vis::Utils::to_uint("0")); } <|endoftext|>
<commit_before>/* * Originally written by Xinef - Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3 */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "nexus.h" enum Spells { // Main SPELL_ICE_NOVA = 47772, SPELL_FIREBOMB = 47773, SPELL_GRAVITY_WELL = 47756, SPELL_TELESTRA_BACK = 47714, SPELL_BURNING_WINDS = 46308, SPELL_START_SUMMON_CLONES = 47710, SPELL_FIRE_MAGUS_SUMMON = 47707, SPELL_FROST_MAGUS_SUMMON = 47709, SPELL_ARCANE_MAGUS_SUMMON = 47708, SPELL_FIRE_MAGUS_DEATH = 47711, SPELL_ARCANE_MAGUS_DEATH = 47713, SPELL_WEAR_CHRISTMAS_HAT = 61400 }; enum Yells { SAY_AGGRO = 0, SAY_KILL = 1, SAY_DEATH = 2, SAY_MERGE = 3, SAY_SPLIT = 4 }; enum Misc { NPC_FIRE_MAGUS = 26928, NPC_FROST_MAGUS = 26930, NPC_ARCANE_MAGUS = 26929, ACHIEVEMENT_SPLIT_PERSONALITY = 2150, GAME_EVENT_WINTER_VEIL = 2, }; enum Events { EVENT_MAGUS_ICE_NOVA = 1, EVENT_MAGUS_FIREBOMB = 2, EVENT_MAGUS_GRAVITY_WELL = 3, EVENT_MAGUS_HEALTH1 = 4, EVENT_MAGUS_HEALTH2 = 5, EVENT_MAGUS_FAIL_ACHIEVEMENT = 6, EVENT_MAGUS_MERGED = 7, EVENT_MAGUS_RELOCATE = 8, EVENT_KILL_TALK = 9 }; class boss_magus_telestra : public CreatureScript { public: boss_magus_telestra() : CreatureScript("boss_magus_telestra") { } CreatureAI* GetAI(Creature* creature) const { return GetInstanceAI<boss_magus_telestraAI>(creature); } struct boss_magus_telestraAI : public BossAI { boss_magus_telestraAI(Creature* creature) : BossAI(creature, DATA_MAGUS_TELESTRA_EVENT) { } uint8 copiesDied; bool achievement; void Reset() { BossAI::Reset(); copiesDied = 0; achievement = true; if (IsHeroic() && sGameEventMgr->IsActiveEvent(GAME_EVENT_WINTER_VEIL) && !me->HasAura(SPELL_WEAR_CHRISTMAS_HAT)) me->AddAura(SPELL_WEAR_CHRISTMAS_HAT, me); } uint32 GetData(uint32 data) const { if (data == me->GetEntry()) return achievement; return 0; } void EnterCombat(Unit* who) { BossAI::EnterCombat(who); Talk(SAY_AGGRO); events.ScheduleEvent(EVENT_MAGUS_ICE_NOVA, 10000); events.ScheduleEvent(EVENT_MAGUS_FIREBOMB, 0); events.ScheduleEvent(EVENT_MAGUS_GRAVITY_WELL, 20000); events.ScheduleEvent(EVENT_MAGUS_HEALTH1, 1000); if (IsHeroic()) events.ScheduleEvent(EVENT_MAGUS_HEALTH2, 1000); } void AttackStart(Unit* who) { if (who && me->Attack(who, true)) me->GetMotionMaster()->MoveChase(who, 20.0f); } void JustDied(Unit* killer) { BossAI::JustDied(killer); Talk(SAY_DEATH); } void KilledUnit(Unit*) { if (events.GetNextEventTime(EVENT_KILL_TALK) == 0) { Talk(SAY_KILL); events.ScheduleEvent(EVENT_KILL_TALK, 6000); } } void JustSummoned(Creature* summon) { summons.Summon(summon); summon->SetInCombatWithZone(); } void SpellHit(Unit* caster, const SpellInfo* spellInfo) { if (spellInfo->Id >= SPELL_FIRE_MAGUS_DEATH && spellInfo->Id <= SPELL_ARCANE_MAGUS_DEATH && caster->ToCreature()) { events.ScheduleEvent(EVENT_MAGUS_FAIL_ACHIEVEMENT, 5000); caster->ToCreature()->DespawnOrUnsummon(1000); if (++copiesDied >= 3) { copiesDied = 0; Talk(SAY_MERGE); events.CancelEvent(EVENT_MAGUS_FAIL_ACHIEVEMENT); events.ScheduleEvent(EVENT_MAGUS_MERGED, 5000); me->CastSpell(me, SPELL_BURNING_WINDS, true); } } } void UpdateAI(uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (events.ExecuteEvent()) { case EVENT_MAGUS_HEALTH1: if (me->HealthBelowPct(51)) { me->CastSpell(me, SPELL_START_SUMMON_CLONES, false); events.ScheduleEvent(EVENT_MAGUS_RELOCATE, 3500); break; } events.ScheduleEvent(EVENT_MAGUS_HEALTH1, 1000); break; case EVENT_MAGUS_HEALTH2: if (me->HealthBelowPct(11)) { me->CastSpell(me, SPELL_START_SUMMON_CLONES, false); events.ScheduleEvent(EVENT_MAGUS_RELOCATE, 3500); break; } events.ScheduleEvent(EVENT_MAGUS_HEALTH2, 1000); break; case EVENT_MAGUS_FIREBOMB: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) me->CastSpell(target, SPELL_FIREBOMB, false); events.ScheduleEvent(EVENT_MAGUS_FIREBOMB, 3000); break; case EVENT_MAGUS_ICE_NOVA: me->CastSpell(me, SPELL_ICE_NOVA, false); events.ScheduleEvent(EVENT_MAGUS_ICE_NOVA, 15000); break; case EVENT_MAGUS_GRAVITY_WELL: me->CastSpell(me, SPELL_GRAVITY_WELL, false); events.ScheduleEvent(EVENT_MAGUS_GRAVITY_WELL, 15000); break; case EVENT_MAGUS_FAIL_ACHIEVEMENT: achievement = false; break; case EVENT_MAGUS_RELOCATE: me->NearTeleportTo(505.04f, 88.915f, -16.13f, 2.98f); break; case EVENT_MAGUS_MERGED: me->CastSpell(me, SPELL_TELESTRA_BACK, true); me->RemoveAllAuras(); break; } DoMeleeAttackIfReady(); } }; }; class spell_boss_magus_telestra_summon_telestra_clones : public SpellScriptLoader { public: spell_boss_magus_telestra_summon_telestra_clones() : SpellScriptLoader("spell_boss_magus_telestra_summon_telestra_clones") { } class spell_boss_magus_telestra_summon_telestra_clones_AuraScript : public AuraScript { PrepareAuraScript(spell_boss_magus_telestra_summon_telestra_clones_AuraScript); bool Load() { return GetUnitOwner()->GetTypeId() == TYPEID_UNIT; } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { GetUnitOwner()->ToCreature()->AI()->Talk(SAY_SPLIT); GetUnitOwner()->CastSpell(GetUnitOwner(), SPELL_FIRE_MAGUS_SUMMON, true); GetUnitOwner()->CastSpell(GetUnitOwner(), SPELL_FROST_MAGUS_SUMMON, true); GetUnitOwner()->CastSpell(GetUnitOwner(), SPELL_ARCANE_MAGUS_SUMMON, true); GetUnitOwner()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); GetUnitOwner()->SetControlled(true, UNIT_STATE_STUNNED); GetUnitOwner()->ToCreature()->LoadEquipment(0, true); } void HandleRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { GetUnitOwner()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); GetUnitOwner()->SetControlled(false, UNIT_STATE_STUNNED); GetUnitOwner()->ToCreature()->LoadEquipment(1, true); } void Register() { AfterEffectApply += AuraEffectApplyFn(spell_boss_magus_telestra_summon_telestra_clones_AuraScript::HandleApply, EFFECT_1, SPELL_AURA_TRANSFORM, AURA_EFFECT_HANDLE_REAL); AfterEffectRemove += AuraEffectRemoveFn(spell_boss_magus_telestra_summon_telestra_clones_AuraScript::HandleRemove, EFFECT_1, SPELL_AURA_TRANSFORM, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_boss_magus_telestra_summon_telestra_clones_AuraScript(); } }; class spell_boss_magus_telestra_gravity_well : public SpellScriptLoader { public: spell_boss_magus_telestra_gravity_well() : SpellScriptLoader("spell_boss_magus_telestra_gravity_well") { } class spell_boss_magus_telestra_gravity_well_SpellScript : public SpellScript { PrepareSpellScript(spell_boss_magus_telestra_gravity_well_SpellScript); void SelectTarget(std::list<WorldObject*>& targets) { targets.remove_if(acore::RandomCheck(50)); } void HandlePull(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); Unit* target = GetHitUnit(); if (!target) return; Position pos; if (target->GetDistance(GetCaster()) < 5.0f) { pos.Relocate(GetCaster()->GetPositionX(), GetCaster()->GetPositionY(), GetCaster()->GetPositionZ()+1.0f); float o = frand(0, 2*M_PI); target->MovePositionToFirstCollision(pos, 20.0f, o); pos.m_positionZ += frand(5.0f, 15.0f); } else pos.Relocate(GetCaster()->GetPositionX(), GetCaster()->GetPositionY(), GetCaster()->GetPositionZ()+1.0f); float speedXY = float(GetSpellInfo()->Effects[effIndex].MiscValue) * 0.1f; float speedZ = target->GetDistance(pos) / speedXY * 0.5f * Movement::gravity; target->GetMotionMaster()->MoveJump(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), speedXY, speedZ); } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_boss_magus_telestra_gravity_well_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(spell_boss_magus_telestra_gravity_well_SpellScript::HandlePull, EFFECT_0, SPELL_EFFECT_PULL_TOWARDS_DEST); } }; SpellScript* GetSpellScript() const { return new spell_boss_magus_telestra_gravity_well_SpellScript(); } }; class achievement_split_personality : public AchievementCriteriaScript { public: achievement_split_personality() : AchievementCriteriaScript("achievement_split_personality") { } bool OnCheck(Player* /*player*/, Unit* target) { if (!target) return false; return target->GetAI()->GetData(target->GetEntry()); } }; void AddSC_boss_magus_telestra() { new boss_magus_telestra(); new spell_boss_magus_telestra_summon_telestra_clones(); new spell_boss_magus_telestra_gravity_well(); new achievement_split_personality(); }<commit_msg>fix(Core/Script): Grand Magus Telestra talk (#2871)<commit_after>/* * Originally written by Xinef - Copyright (C) 2016+ AzerothCore <www.azerothcore.org>, released under GNU AGPL v3 license: https://github.com/azerothcore/azerothcore-wotlk/blob/master/LICENSE-AGPL3 */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "nexus.h" enum Spells { // Main SPELL_ICE_NOVA = 47772, SPELL_FIREBOMB = 47773, SPELL_GRAVITY_WELL = 47756, SPELL_TELESTRA_BACK = 47714, SPELL_BURNING_WINDS = 46308, SPELL_START_SUMMON_CLONES = 47710, SPELL_FIRE_MAGUS_SUMMON = 47707, SPELL_FROST_MAGUS_SUMMON = 47709, SPELL_ARCANE_MAGUS_SUMMON = 47708, SPELL_FIRE_MAGUS_DEATH = 47711, SPELL_ARCANE_MAGUS_DEATH = 47713, SPELL_WEAR_CHRISTMAS_HAT = 61400 }; enum Yells { SAY_AGGRO = 0, SAY_KILL = 1, SAY_DEATH = 2, SAY_MERGE = 3, SAY_SPLIT = 4 }; enum Misc { NPC_FIRE_MAGUS = 26928, NPC_FROST_MAGUS = 26930, NPC_ARCANE_MAGUS = 26929, ACHIEVEMENT_SPLIT_PERSONALITY = 2150, GAME_EVENT_WINTER_VEIL = 2, }; enum Events { EVENT_MAGUS_ICE_NOVA = 1, EVENT_MAGUS_FIREBOMB = 2, EVENT_MAGUS_GRAVITY_WELL = 3, EVENT_MAGUS_HEALTH1 = 4, EVENT_MAGUS_HEALTH2 = 5, EVENT_MAGUS_FAIL_ACHIEVEMENT = 6, EVENT_MAGUS_MERGED = 7, EVENT_MAGUS_RELOCATE = 8, EVENT_KILL_TALK = 9 }; class boss_magus_telestra : public CreatureScript { public: boss_magus_telestra() : CreatureScript("boss_magus_telestra") { } CreatureAI* GetAI(Creature* creature) const { return GetInstanceAI<boss_magus_telestraAI>(creature); } struct boss_magus_telestraAI : public BossAI { boss_magus_telestraAI(Creature* creature) : BossAI(creature, DATA_MAGUS_TELESTRA_EVENT) { } uint8 copiesDied; bool achievement; void Reset() { BossAI::Reset(); copiesDied = 0; achievement = true; if (IsHeroic() && sGameEventMgr->IsActiveEvent(GAME_EVENT_WINTER_VEIL) && !me->HasAura(SPELL_WEAR_CHRISTMAS_HAT)) me->AddAura(SPELL_WEAR_CHRISTMAS_HAT, me); } uint32 GetData(uint32 data) const { if (data == me->GetEntry()) return achievement; return 0; } void EnterCombat(Unit* who) { BossAI::EnterCombat(who); Talk(SAY_AGGRO); events.ScheduleEvent(EVENT_MAGUS_ICE_NOVA, 10000); events.ScheduleEvent(EVENT_MAGUS_FIREBOMB, 0); events.ScheduleEvent(EVENT_MAGUS_GRAVITY_WELL, 20000); events.ScheduleEvent(EVENT_MAGUS_HEALTH1, 1000); if (IsHeroic()) events.ScheduleEvent(EVENT_MAGUS_HEALTH2, 1000); } void AttackStart(Unit* who) { if (who && me->Attack(who, true)) me->GetMotionMaster()->MoveChase(who, 20.0f); } void JustDied(Unit* killer) { BossAI::JustDied(killer); Talk(SAY_DEATH); } void KilledUnit(Unit*) { if (events.GetNextEventTime(EVENT_KILL_TALK) == 0) { Talk(SAY_KILL); events.ScheduleEvent(EVENT_KILL_TALK, 6000); } } void JustSummoned(Creature* summon) { summons.Summon(summon); summon->SetInCombatWithZone(); } void SpellHit(Unit* caster, const SpellInfo* spellInfo) { if (spellInfo->Id >= SPELL_FIRE_MAGUS_DEATH && spellInfo->Id <= SPELL_ARCANE_MAGUS_DEATH && caster->ToCreature()) { events.ScheduleEvent(EVENT_MAGUS_FAIL_ACHIEVEMENT, 5000); caster->ToCreature()->DespawnOrUnsummon(1000); if (++copiesDied >= 3) { copiesDied = 0; events.CancelEvent(EVENT_MAGUS_FAIL_ACHIEVEMENT); events.ScheduleEvent(EVENT_MAGUS_MERGED, 5000); me->CastSpell(me, SPELL_BURNING_WINDS, true); } } } void UpdateAI(uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; switch (events.ExecuteEvent()) { case EVENT_MAGUS_HEALTH1: if (me->HealthBelowPct(51)) { me->CastSpell(me, SPELL_START_SUMMON_CLONES, false); events.ScheduleEvent(EVENT_MAGUS_RELOCATE, 3500); Talk(SAY_SPLIT); break; } events.ScheduleEvent(EVENT_MAGUS_HEALTH1, 1000); break; case EVENT_MAGUS_HEALTH2: if (me->HealthBelowPct(11)) { me->CastSpell(me, SPELL_START_SUMMON_CLONES, false); events.ScheduleEvent(EVENT_MAGUS_RELOCATE, 3500); Talk(SAY_SPLIT); break; } events.ScheduleEvent(EVENT_MAGUS_HEALTH2, 1000); break; case EVENT_MAGUS_FIREBOMB: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) me->CastSpell(target, SPELL_FIREBOMB, false); events.ScheduleEvent(EVENT_MAGUS_FIREBOMB, 3000); break; case EVENT_MAGUS_ICE_NOVA: me->CastSpell(me, SPELL_ICE_NOVA, false); events.ScheduleEvent(EVENT_MAGUS_ICE_NOVA, 15000); break; case EVENT_MAGUS_GRAVITY_WELL: me->CastSpell(me, SPELL_GRAVITY_WELL, false); events.ScheduleEvent(EVENT_MAGUS_GRAVITY_WELL, 15000); break; case EVENT_MAGUS_FAIL_ACHIEVEMENT: achievement = false; break; case EVENT_MAGUS_RELOCATE: me->NearTeleportTo(505.04f, 88.915f, -16.13f, 2.98f); break; case EVENT_MAGUS_MERGED: me->CastSpell(me, SPELL_TELESTRA_BACK, true); me->RemoveAllAuras(); Talk(SAY_MERGE); break; } DoMeleeAttackIfReady(); } }; }; class spell_boss_magus_telestra_summon_telestra_clones : public SpellScriptLoader { public: spell_boss_magus_telestra_summon_telestra_clones() : SpellScriptLoader("spell_boss_magus_telestra_summon_telestra_clones") { } class spell_boss_magus_telestra_summon_telestra_clones_AuraScript : public AuraScript { PrepareAuraScript(spell_boss_magus_telestra_summon_telestra_clones_AuraScript); bool Load() { return GetUnitOwner()->GetTypeId() == TYPEID_UNIT; } void HandleApply(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { GetUnitOwner()->CastSpell(GetUnitOwner(), SPELL_FIRE_MAGUS_SUMMON, true); GetUnitOwner()->CastSpell(GetUnitOwner(), SPELL_FROST_MAGUS_SUMMON, true); GetUnitOwner()->CastSpell(GetUnitOwner(), SPELL_ARCANE_MAGUS_SUMMON, true); GetUnitOwner()->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); GetUnitOwner()->SetControlled(true, UNIT_STATE_STUNNED); GetUnitOwner()->ToCreature()->LoadEquipment(0, true); } void HandleRemove(AuraEffect const* /*aurEff*/, AuraEffectHandleModes /*mode*/) { GetUnitOwner()->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); GetUnitOwner()->SetControlled(false, UNIT_STATE_STUNNED); GetUnitOwner()->ToCreature()->LoadEquipment(1, true); } void Register() { AfterEffectApply += AuraEffectApplyFn(spell_boss_magus_telestra_summon_telestra_clones_AuraScript::HandleApply, EFFECT_1, SPELL_AURA_TRANSFORM, AURA_EFFECT_HANDLE_REAL); AfterEffectRemove += AuraEffectRemoveFn(spell_boss_magus_telestra_summon_telestra_clones_AuraScript::HandleRemove, EFFECT_1, SPELL_AURA_TRANSFORM, AURA_EFFECT_HANDLE_REAL); } }; AuraScript* GetAuraScript() const { return new spell_boss_magus_telestra_summon_telestra_clones_AuraScript(); } }; class spell_boss_magus_telestra_gravity_well : public SpellScriptLoader { public: spell_boss_magus_telestra_gravity_well() : SpellScriptLoader("spell_boss_magus_telestra_gravity_well") { } class spell_boss_magus_telestra_gravity_well_SpellScript : public SpellScript { PrepareSpellScript(spell_boss_magus_telestra_gravity_well_SpellScript); void SelectTarget(std::list<WorldObject*>& targets) { targets.remove_if(acore::RandomCheck(50)); } void HandlePull(SpellEffIndex effIndex) { PreventHitDefaultEffect(effIndex); Unit* target = GetHitUnit(); if (!target) return; Position pos; if (target->GetDistance(GetCaster()) < 5.0f) { pos.Relocate(GetCaster()->GetPositionX(), GetCaster()->GetPositionY(), GetCaster()->GetPositionZ()+1.0f); float o = frand(0, 2*M_PI); target->MovePositionToFirstCollision(pos, 20.0f, o); pos.m_positionZ += frand(5.0f, 15.0f); } else pos.Relocate(GetCaster()->GetPositionX(), GetCaster()->GetPositionY(), GetCaster()->GetPositionZ()+1.0f); float speedXY = float(GetSpellInfo()->Effects[effIndex].MiscValue) * 0.1f; float speedZ = target->GetDistance(pos) / speedXY * 0.5f * Movement::gravity; target->GetMotionMaster()->MoveJump(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), speedXY, speedZ); } void Register() { OnObjectAreaTargetSelect += SpellObjectAreaTargetSelectFn(spell_boss_magus_telestra_gravity_well_SpellScript::SelectTarget, EFFECT_0, TARGET_UNIT_SRC_AREA_ENEMY); OnEffectHitTarget += SpellEffectFn(spell_boss_magus_telestra_gravity_well_SpellScript::HandlePull, EFFECT_0, SPELL_EFFECT_PULL_TOWARDS_DEST); } }; SpellScript* GetSpellScript() const { return new spell_boss_magus_telestra_gravity_well_SpellScript(); } }; class achievement_split_personality : public AchievementCriteriaScript { public: achievement_split_personality() : AchievementCriteriaScript("achievement_split_personality") { } bool OnCheck(Player* /*player*/, Unit* target) { if (!target) return false; return target->GetAI()->GetData(target->GetEntry()); } }; void AddSC_boss_magus_telestra() { new boss_magus_telestra(); new spell_boss_magus_telestra_summon_telestra_clones(); new spell_boss_magus_telestra_gravity_well(); new achievement_split_personality(); } <|endoftext|>
<commit_before><commit_msg>increment table position correctly if more than one table is inserted<commit_after><|endoftext|>
<commit_before>#include "consoletools.h" #include "client.h" #include "log/logger.h" #include "settings.h" #include "controller/logincontroller.h" #include "webrequester.h" #include "network/requests/registerdevicerequest.h" #include <QTextStream> #include <QCoreApplication> #include <QCommandLineParser> #include <QCommandLineOption> #include <QTimer> #include <QDebug> #ifdef Q_OS_UNIX #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #include <unistd.h> #include <errno.h> #endif // Q_OS_UNIX LOGGER(main); class DeviceRegistrationWatcher : public QObject { Q_OBJECT public: DeviceRegistrationWatcher(LoginController* controller) : m_controller(controller) { connect(controller, SIGNAL(finished()), this, SLOT(onLoginOrRegistrationFinished())); connect(&m_requester, SIGNAL(statusChanged(WebRequester::Status)), this, SLOT(onStatusChanged(WebRequester::Status))); m_requester.setRequest(&m_request); m_requester.setResponse(&m_response); } private slots: void onLoginOrRegistrationFinished() { // Already registered? if (m_controller->registeredDevice()) { return; } LOG_INFO("Automatically registering device"); m_requester.start(); } void onStatusChanged(WebRequester::Status status) { switch (status) { case WebRequester::Error: LOG_ERROR(QString("Device registration failed, quitting. (%1)").arg(m_requester.errorString())); qApp->quit(); break; case WebRequester::Finished: LOG_INFO("Device successfully registered"); break; default: break; } } protected: LoginController* m_controller; WebRequester m_requester; RegisterDeviceRequest m_request; RegisterDeviceResponse m_response; }; class LoginWatcher : public QObject { Q_OBJECT public: LoginWatcher(LoginController* controller) : m_controller(controller) { connect(controller, SIGNAL(statusChanged()), this, SLOT(onStatusChanged())); } private slots: void onStatusChanged() { switch (m_controller->status()) { case LoginController::Error: LOG_INFO("Login/Registration failed, quitting."); qApp->quit(); break; case LoginController::Finished: LOG_INFO("Login successful"); deleteLater(); break; default: break; } } protected: LoginController* m_controller; }; struct LoginData { enum Type { Register, Login }; Type type; QString userId; QString password; }; int main(int argc, char* argv[]) { QCoreApplication::setOrganizationDomain("de.hsaugsburg.informatik"); QCoreApplication::setOrganizationName("HS-Augsburg"); QCoreApplication::setApplicationName("mPlaneClient"); QCoreApplication::setApplicationVersion("0.1"); QCoreApplication app(argc, argv); QTextStream out(stdout); QCommandLineParser parser; parser.setApplicationDescription("glimpse commandline version"); parser.addHelpOption(); parser.addVersionOption(); #ifdef Q_OS_UNIX QCommandLineOption userOption("user", "Run as user", "user"); parser.addOption(userOption); //QCommandLineOption groupOption("group", "Run as group", "group"); //parser.addOption(groupOption); QCommandLineOption daemonOption("daemon", "Run as daemon"); parser.addOption(daemonOption); //QCommandLineOption pidFileOption("pidfile", "Set the pidfile", "path"); //parser.addOption(pidFileOption); #endif // Q_OS_UNIX QCommandLineOption controllerUrl("controller", "Override the controller host", "hostname:port"); parser.addOption(controllerUrl); QCommandLineOption registerAnonymous("register-anonymous", "Register anonymous on server"); parser.addOption(registerAnonymous); QCommandLineOption registerOption("register", "Register on server", "mail"); parser.addOption(registerOption); QCommandLineOption loginOption("login", "Login on server", "mail"); parser.addOption(loginOption); QCommandLineOption passiveOption("passive", "Passive probe which does not receive tasks"); parser.addOption(passiveOption); parser.process(app); if (parser.isSet(registerOption) && parser.isSet(registerAnonymous)) { out << "'--register' and '--register-anonymous' cannot be set on the same time.\n"; return 1; } if ((parser.isSet(registerAnonymous)||parser.isSet(registerOption)) && parser.isSet(loginOption)) { out << "'--register(-anonymous)' and '--login' cannot be set on the same time.\n"; return 1; } QCommandLineOption* passwordOption = NULL; LoginData loginData; if (parser.isSet(registerOption)) { loginData.type = LoginData::Register; passwordOption = &registerOption; } if (parser.isSet(loginOption)) { loginData.type = LoginData::Login; passwordOption = &loginOption; } if (passwordOption) { loginData.userId = parser.value(*passwordOption); ConsoleTools tools; do { out << '[' << argv[0] << ']' << " Password: "; out.flush(); loginData.password = tools.readPassword(); } while (loginData.password.isEmpty()); } #ifdef Q_OS_UNIX if (parser.isSet(userOption)) { QByteArray user = parser.value(userOption).toLatin1(); passwd* pwd = getpwnam(user.constData()); if (pwd) { if (-1 == setuid(pwd->pw_uid)) { out << "Cannot set uid to " << pwd->pw_uid << ": " << strerror(errno) << "\n"; return 1; } else { LOG_DEBUG(QString("User id set to %1 (%2)").arg(pwd->pw_uid).arg(QString::fromLatin1(user))); } } else { out << "No user named " << QString::fromLatin1(user) << " found\n"; return 1; } } // NOTE: This should be the last option since this creates a process fork! if (parser.isSet(daemonOption)) { pid_t pid = fork(); if (pid == -1) { out << "fork() failed: " << strerror(errno) << "\n"; } else if (pid > 0) { // Fork successful, we're exiting now out << "Daemon started with pid " << pid << "\n"; return 0; } else { // Child process umask(0); pid_t sid = setsid(); if (sid < 0) { return 1; } //chdir("/"); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } } #endif // Q_OS_UNIX // If there may be anything left, we flush it before the client starts out.flush(); // Initialize the client instance Client* client = Client::instance(); if (parser.isSet(passiveOption)) { int setPassive = parser.value(passiveOption).toInt(); client->settings()->setPassive((bool) setPassive); } if (client->init()) { LOG_ERROR("Client initialization failed") return 1; } if (parser.isSet(controllerUrl)) { client->settings()->config()->setControllerAddress(parser.value(controllerUrl)); } new LoginWatcher(client->loginController()); new DeviceRegistrationWatcher(client->loginController()); if (passwordOption) { switch (loginData.type) { case LoginData::Register: client->loginController()->registration(loginData.userId, loginData.password); break; case LoginData::Login: client->settings()->setUserId(loginData.userId); client->settings()->setPassword(loginData.password); client->loginController()->login(); break; } } else if (parser.isSet(registerAnonymous)) { client->loginController()->anonymousRegistration(); } else { if (!client->autoLogin()) { LOG_ERROR("No login data found for autologin"); return 1; } } int value = app.exec(); out << "Application shutting down.\n"; Client::instance()->deleteLater(); QTimer::singleShot(1, &app, SLOT(quit())); app.exec(); return value; } #include "main.moc" <commit_msg>typo fix<commit_after>#include "consoletools.h" #include "client.h" #include "log/logger.h" #include "settings.h" #include "controller/logincontroller.h" #include "webrequester.h" #include "network/requests/registerdevicerequest.h" #include <QTextStream> #include <QCoreApplication> #include <QCommandLineParser> #include <QCommandLineOption> #include <QTimer> #include <QDebug> #ifdef Q_OS_UNIX #include <sys/types.h> #include <sys/stat.h> #include <pwd.h> #include <unistd.h> #include <errno.h> #endif // Q_OS_UNIX LOGGER(main); class DeviceRegistrationWatcher : public QObject { Q_OBJECT public: DeviceRegistrationWatcher(LoginController* controller) : m_controller(controller) { connect(controller, SIGNAL(finished()), this, SLOT(onLoginOrRegistrationFinished())); connect(&m_requester, SIGNAL(statusChanged(WebRequester::Status)), this, SLOT(onStatusChanged(WebRequester::Status))); m_requester.setRequest(&m_request); m_requester.setResponse(&m_response); } private slots: void onLoginOrRegistrationFinished() { // Already registered? if (m_controller->registeredDevice()) { return; } LOG_INFO("Automatically registering device"); m_requester.start(); } void onStatusChanged(WebRequester::Status status) { switch (status) { case WebRequester::Error: LOG_ERROR(QString("Device registration failed, quitting. (%1)").arg(m_requester.errorString())); qApp->quit(); break; case WebRequester::Finished: LOG_INFO("Device successfully registered"); break; default: break; } } protected: LoginController* m_controller; WebRequester m_requester; RegisterDeviceRequest m_request; RegisterDeviceResponse m_response; }; class LoginWatcher : public QObject { Q_OBJECT public: LoginWatcher(LoginController* controller) : m_controller(controller) { connect(controller, SIGNAL(statusChanged()), this, SLOT(onStatusChanged())); } private slots: void onStatusChanged() { switch (m_controller->status()) { case LoginController::Error: LOG_INFO("Login/Registration failed, quitting."); qApp->quit(); break; case LoginController::Finished: LOG_INFO("Login successful"); deleteLater(); break; default: break; } } protected: LoginController* m_controller; }; struct LoginData { enum Type { Register, Login }; Type type; QString userId; QString password; }; int main(int argc, char* argv[]) { QCoreApplication::setOrganizationDomain("de.hsaugsburg.informatik"); QCoreApplication::setOrganizationName("HS-Augsburg"); QCoreApplication::setApplicationName("mPlaneClient"); QCoreApplication::setApplicationVersion("0.1"); QCoreApplication app(argc, argv); QTextStream out(stdout); QCommandLineParser parser; parser.setApplicationDescription("glimpse commandline version"); parser.addHelpOption(); parser.addVersionOption(); #ifdef Q_OS_UNIX QCommandLineOption userOption("user", "Run as user", "user"); parser.addOption(userOption); //QCommandLineOption groupOption("group", "Run as group", "group"); //parser.addOption(groupOption); QCommandLineOption daemonOption("daemon", "Run as daemon"); parser.addOption(daemonOption); //QCommandLineOption pidFileOption("pidfile", "Set the pidfile", "path"); //parser.addOption(pidFileOption); #endif // Q_OS_UNIX QCommandLineOption controllerUrl("controller", "Override the controller host", "hostname:port"); parser.addOption(controllerUrl); QCommandLineOption registerAnonymous("register-anonymous", "Register anonymous on server"); parser.addOption(registerAnonymous); QCommandLineOption registerOption("register", "Register on server", "mail"); parser.addOption(registerOption); QCommandLineOption loginOption("login", "Login on server", "mail"); parser.addOption(loginOption); QCommandLineOption passiveOption("passive", "Passive probe which does not receive tasks"); parser.addOption(passiveOption); parser.process(app); if (parser.isSet(registerOption) && parser.isSet(registerAnonymous)) { out << "'--register' and '--register-anonymous' cannot be set on the same time.\n"; return 1; } if ((parser.isSet(registerAnonymous)||parser.isSet(registerOption)) && parser.isSet(loginOption)) { out << "'--register(-anonymous)' and '--login' cannot be set on the same time.\n"; return 1; } QCommandLineOption* passwordOption = NULL; LoginData loginData; if (parser.isSet(registerOption)) { loginData.type = LoginData::Register; passwordOption = &registerOption; } if (parser.isSet(loginOption)) { loginData.type = LoginData::Login; passwordOption = &loginOption; } if (passwordOption) { loginData.userId = parser.value(*passwordOption); ConsoleTools tools; do { out << '[' << argv[0] << ']' << " Password: "; out.flush(); loginData.password = tools.readPassword(); } while (loginData.password.isEmpty()); } #ifdef Q_OS_UNIX if (parser.isSet(userOption)) { QByteArray user = parser.value(userOption).toLatin1(); passwd* pwd = getpwnam(user.constData()); if (pwd) { if (-1 == setuid(pwd->pw_uid)) { out << "Cannot set uid to " << pwd->pw_uid << ": " << strerror(errno) << "\n"; return 1; } else { LOG_DEBUG(QString("User id set to %1 (%2)").arg(pwd->pw_uid).arg(QString::fromLatin1(user))); } } else { out << "No user named " << QString::fromLatin1(user) << " found\n"; return 1; } } // NOTE: This should be the last option since this creates a process fork! if (parser.isSet(daemonOption)) { pid_t pid = fork(); if (pid == -1) { out << "fork() failed: " << strerror(errno) << "\n"; } else if (pid > 0) { // Fork successful, we're exiting now out << "Daemon started with pid " << pid << "\n"; return 0; } else { // Child process umask(0); pid_t sid = setsid(); if (sid < 0) { return 1; } //chdir("/"); close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } } #endif // Q_OS_UNIX // If there may be anything left, we flush it before the client starts out.flush(); // Initialize the client instance Client* client = Client::instance(); if (parser.isSet(passiveOption)) { int setPassive = parser.value(passiveOption).toInt(); client->settings()->setPassive((bool) setPassive); } if (!client->init()) { LOG_ERROR("Client initialization failed") return 1; } if (parser.isSet(controllerUrl)) { client->settings()->config()->setControllerAddress(parser.value(controllerUrl)); } new LoginWatcher(client->loginController()); new DeviceRegistrationWatcher(client->loginController()); if (passwordOption) { switch (loginData.type) { case LoginData::Register: client->loginController()->registration(loginData.userId, loginData.password); break; case LoginData::Login: client->settings()->setUserId(loginData.userId); client->settings()->setPassword(loginData.password); client->loginController()->login(); break; } } else if (parser.isSet(registerAnonymous)) { client->loginController()->anonymousRegistration(); } else { if (!client->autoLogin()) { LOG_ERROR("No login data found for autologin"); return 1; } } int value = app.exec(); out << "Application shutting down.\n"; Client::instance()->deleteLater(); QTimer::singleShot(1, &app, SLOT(quit())); app.exec(); return value; } #include "main.moc" <|endoftext|>
<commit_before>/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: [email protected] (Bryan McQuade) #include "net/instaweb/rewriter/public/rewrite_options.h" #include <set> #include "net/instaweb/util/public/gtest.h" #include "net/instaweb/util/public/null_message_handler.h" namespace { using net_instaweb::NullMessageHandler; using net_instaweb::RewriteOptions; class RewriteOptionsTest : public ::testing::Test { protected: typedef std::set<RewriteOptions::Filter> FilterSet; bool NoneEnabled() { FilterSet s; return OnlyEnabled(s); } bool OnlyEnabled(const FilterSet& filters) { bool ret = true; for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; ret && (f <= RewriteOptions::kLastFilter); f = static_cast<RewriteOptions::Filter>(f + 1)) { if (filters.find(f) != filters.end()) { if (!options_.Enabled(f)) { ret = false; } } else { if (options_.Enabled(f)) { ret = false; } } } return ret; } bool OnlyEnabled(RewriteOptions::Filter filter) { FilterSet s; s.insert(filter); return OnlyEnabled(s); } RewriteOptions options_; }; TEST_F(RewriteOptionsTest, BotDetectEnabledByDefault) { ASSERT_FALSE(options_.botdetect_enabled()); } TEST_F(RewriteOptionsTest, BotDetectEnable) { options_.set_botdetect_enabled(true); ASSERT_TRUE(options_.botdetect_enabled()); } TEST_F(RewriteOptionsTest, BotDetectDisable) { options_.set_botdetect_enabled(false); ASSERT_FALSE(options_.botdetect_enabled()); } TEST_F(RewriteOptionsTest, NoneEnabledByDefault) { ASSERT_TRUE(NoneEnabled()); } TEST_F(RewriteOptionsTest, InstrumentationDisabled) { // Make sure the kCoreFilters enables some filters. options_.SetRewriteLevel(RewriteOptions::kCoreFilters); ASSERT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); // Now disable all filters and make sure none are enabled. for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; f <= RewriteOptions::kLastFilter; f = static_cast<RewriteOptions::Filter>(f + 1)) { options_.DisableFilter(f); } ASSERT_TRUE(NoneEnabled()); } TEST_F(RewriteOptionsTest, DisableTrumpsEnable) { for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; f <= RewriteOptions::kLastFilter; f = static_cast<RewriteOptions::Filter>(f + 1)) { options_.DisableFilter(f); options_.EnableFilter(f); ASSERT_TRUE(NoneEnabled()); } } TEST_F(RewriteOptionsTest, CoreFilters) { options_.SetRewriteLevel(RewriteOptions::kCoreFilters); FilterSet s; for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; f <= RewriteOptions::kLastFilter; f = static_cast<RewriteOptions::Filter>(f + 1)) { if (options_.Enabled(f)) { s.insert(f); } } // Make sure that more than one filter is enabled in the core filter // set. ASSERT_GT(s.size(), 1); } TEST_F(RewriteOptionsTest, Enable) { FilterSet s; for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; f <= RewriteOptions::kLastFilter; f = static_cast<RewriteOptions::Filter>(f + 1)) { s.insert(f); options_.EnableFilter(f); ASSERT_TRUE(OnlyEnabled(s)); } } TEST_F(RewriteOptionsTest, CommaSeparatedList) { FilterSet s; s.insert(RewriteOptions::kAddInstrumentation); s.insert(RewriteOptions::kLeftTrimUrls); const char* kList = "add_instrumentation,trim_urls"; NullMessageHandler handler; ASSERT_TRUE( options_.EnableFiltersByCommaSeparatedList(kList, &handler)); ASSERT_TRUE(OnlyEnabled(s)); ASSERT_TRUE( options_.DisableFiltersByCommaSeparatedList(kList, &handler)); ASSERT_TRUE(NoneEnabled()); } TEST_F(RewriteOptionsTest, CompoundFlag) { FilterSet s; // TODO(jmaessen): add kConvertJpegToWebp here when it becomes part of // rewrite_images. s.insert(RewriteOptions::kInlineImages); s.insert(RewriteOptions::kInsertImageDimensions); s.insert(RewriteOptions::kRecompressImages); s.insert(RewriteOptions::kResizeImages); const char* kList = "rewrite_images"; NullMessageHandler handler; ASSERT_TRUE( options_.EnableFiltersByCommaSeparatedList(kList, &handler)); ASSERT_TRUE(OnlyEnabled(s)); ASSERT_TRUE( options_.DisableFiltersByCommaSeparatedList(kList, &handler)); ASSERT_TRUE(NoneEnabled()); } TEST_F(RewriteOptionsTest, ParseRewriteLevel) { RewriteOptions::RewriteLevel level; ASSERT_TRUE(RewriteOptions::ParseRewriteLevel("PassThrough", &level)); ASSERT_EQ(RewriteOptions::kPassThrough, level); ASSERT_TRUE(RewriteOptions::ParseRewriteLevel("CoreFilters", &level)); ASSERT_EQ(RewriteOptions::kCoreFilters, level); ASSERT_FALSE(RewriteOptions::ParseRewriteLevel(NULL, &level)); ASSERT_FALSE(RewriteOptions::ParseRewriteLevel("", &level)); ASSERT_FALSE(RewriteOptions::ParseRewriteLevel("Garbage", &level)); } TEST_F(RewriteOptionsTest, MergeLevelsDefault) { RewriteOptions one, two; options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kPassThrough, options_.level()); } TEST_F(RewriteOptionsTest, MergeLevelsOneCore) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kCoreFilters, options_.level()); } TEST_F(RewriteOptionsTest, MergeLevelsOneCoreTwoPass) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); two.SetRewriteLevel(RewriteOptions::kPassThrough); // overrides default options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kPassThrough, options_.level()); } TEST_F(RewriteOptionsTest, MergeLevelsOnePassTwoCore) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kPassThrough); // overrides default two.SetRewriteLevel(RewriteOptions::kCoreFilters); // overrides one options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kCoreFilters, options_.level()); } TEST_F(RewriteOptionsTest, MergeLevelsBothCore) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); two.SetRewriteLevel(RewriteOptions::kCoreFilters); options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kCoreFilters, options_.level()); } TEST_F(RewriteOptionsTest, MergeFilterPassThrough) { RewriteOptions one, two; options_.Merge(one, two); EXPECT_FALSE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeFilterEnaOne) { RewriteOptions one, two; one.EnableFilter(RewriteOptions::kAddHead); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeFilterEnaTwo) { RewriteOptions one, two; two.EnableFilter(RewriteOptions::kAddHead); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeFilterEnaOneDisTwo) { RewriteOptions one, two; one.EnableFilter(RewriteOptions::kAddHead); two.DisableFilter(RewriteOptions::kAddHead); options_.Merge(one, two); EXPECT_FALSE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeFilterDisOneEnaTwo) { RewriteOptions one, two; one.DisableFilter(RewriteOptions::kAddHead); two.EnableFilter(RewriteOptions::kAddHead); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeCoreFilter) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterEnaOne) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); one.EnableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterEnaTwo) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); two.EnableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterEnaOneDisTwo) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); one.EnableFilter(RewriteOptions::kExtendCache); two.DisableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_FALSE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterDisOne) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); one.DisableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_FALSE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterDisOneEnaTwo) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); one.DisableFilter(RewriteOptions::kExtendCache); two.EnableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeThresholdDefault) { RewriteOptions one, two; options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kDefaultCssInlineMaxBytes, options_.css_inline_max_bytes()); } TEST_F(RewriteOptionsTest, MergeThresholdOne) { RewriteOptions one, two; one.set_css_inline_max_bytes(5); options_.Merge(one, two); EXPECT_EQ(5, options_.css_inline_max_bytes()); } TEST_F(RewriteOptionsTest, MergeThresholdTwo) { RewriteOptions one, two; two.set_css_inline_max_bytes(6); options_.Merge(one, two); EXPECT_EQ(6, options_.css_inline_max_bytes()); } TEST_F(RewriteOptionsTest, MergeThresholdOverride) { RewriteOptions one, two; one.set_css_inline_max_bytes(5); two.set_css_inline_max_bytes(6); options_.Merge(one, two); EXPECT_EQ(6, options_.css_inline_max_bytes()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampDefault) { RewriteOptions one, two; options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kDefaultCacheInvalidationTimestamp, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampOne) { RewriteOptions one, two; one.set_cache_invalidation_timestamp(11111111); options_.Merge(one, two); EXPECT_EQ(11111111, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampTwo) { RewriteOptions one, two; two.set_cache_invalidation_timestamp(22222222); options_.Merge(one, two); EXPECT_EQ(22222222, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampOneLarger) { RewriteOptions one, two; one.set_cache_invalidation_timestamp(33333333); two.set_cache_invalidation_timestamp(22222222); options_.Merge(one, two); EXPECT_EQ(33333333, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampTwoLarger) { RewriteOptions one, two; one.set_cache_invalidation_timestamp(11111111); two.set_cache_invalidation_timestamp(22222222); options_.Merge(one, two); EXPECT_EQ(22222222, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, Allow) { options_.Allow("*.css"); EXPECT_TRUE(options_.IsAllowed("abcd.css")); options_.Disallow("a*.css"); EXPECT_FALSE(options_.IsAllowed("abcd.css")); options_.Allow("ab*.css"); EXPECT_TRUE(options_.IsAllowed("abcd.css")); options_.Disallow("abc*.css"); EXPECT_FALSE(options_.IsAllowed("abcd.css")); } TEST_F(RewriteOptionsTest, MergeAllow) { RewriteOptions one, two; one.Allow("*.css"); EXPECT_TRUE(one.IsAllowed("abcd.css")); one.Disallow("a*.css"); EXPECT_FALSE(one.IsAllowed("abcd.css")); two.Allow("ab*.css"); EXPECT_TRUE(two.IsAllowed("abcd.css")); two.Disallow("abc*.css"); EXPECT_FALSE(two.IsAllowed("abcd.css")); options_.Merge(one, two); EXPECT_FALSE(options_.IsAllowed("abcd.css")); EXPECT_FALSE(options_.IsAllowed("abc.css")); EXPECT_TRUE(options_.IsAllowed("ab.css")); EXPECT_FALSE(options_.IsAllowed("a.css")); } TEST_F(RewriteOptionsTest, DisableAllFiltersNotExplicitlyEnabled) { RewriteOptions one, two; one.EnableFilter(RewriteOptions::kAddHead); two.EnableFilter(RewriteOptions::kExtendCache); two.DisableAllFiltersNotExplicitlyEnabled(); // Should disable AddHead. options_.Merge(one, two); // Make sure AddHead enabling didn't leak through. EXPECT_FALSE(options_.Enabled(RewriteOptions::kAddHead)); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, DisableAllFiltersOverrideFilterLevel) { options_.SetRewriteLevel(RewriteOptions::kCoreFilters); options_.EnableFilter(RewriteOptions::kAddHead); options_.DisableAllFiltersNotExplicitlyEnabled(); // Check that *only* AddHead is enabled, even though we have CoreFilters // level set. EXPECT_TRUE(OnlyEnabled(RewriteOptions::kAddHead)); } } // namespace <commit_msg>Add test ensuring that Level "All" does not imply "strip_scripts", which is dangerous.<commit_after>/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: [email protected] (Bryan McQuade) #include "net/instaweb/rewriter/public/rewrite_options.h" #include <set> #include "net/instaweb/util/public/gtest.h" #include "net/instaweb/util/public/null_message_handler.h" namespace { using net_instaweb::NullMessageHandler; using net_instaweb::RewriteOptions; class RewriteOptionsTest : public ::testing::Test { protected: typedef std::set<RewriteOptions::Filter> FilterSet; bool NoneEnabled() { FilterSet s; return OnlyEnabled(s); } bool OnlyEnabled(const FilterSet& filters) { bool ret = true; for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; ret && (f <= RewriteOptions::kLastFilter); f = static_cast<RewriteOptions::Filter>(f + 1)) { if (filters.find(f) != filters.end()) { if (!options_.Enabled(f)) { ret = false; } } else { if (options_.Enabled(f)) { ret = false; } } } return ret; } bool OnlyEnabled(RewriteOptions::Filter filter) { FilterSet s; s.insert(filter); return OnlyEnabled(s); } RewriteOptions options_; }; TEST_F(RewriteOptionsTest, BotDetectEnabledByDefault) { ASSERT_FALSE(options_.botdetect_enabled()); } TEST_F(RewriteOptionsTest, BotDetectEnable) { options_.set_botdetect_enabled(true); ASSERT_TRUE(options_.botdetect_enabled()); } TEST_F(RewriteOptionsTest, BotDetectDisable) { options_.set_botdetect_enabled(false); ASSERT_FALSE(options_.botdetect_enabled()); } TEST_F(RewriteOptionsTest, NoneEnabledByDefault) { ASSERT_TRUE(NoneEnabled()); } TEST_F(RewriteOptionsTest, InstrumentationDisabled) { // Make sure the kCoreFilters enables some filters. options_.SetRewriteLevel(RewriteOptions::kCoreFilters); ASSERT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); // Now disable all filters and make sure none are enabled. for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; f <= RewriteOptions::kLastFilter; f = static_cast<RewriteOptions::Filter>(f + 1)) { options_.DisableFilter(f); } ASSERT_TRUE(NoneEnabled()); } TEST_F(RewriteOptionsTest, DisableTrumpsEnable) { for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; f <= RewriteOptions::kLastFilter; f = static_cast<RewriteOptions::Filter>(f + 1)) { options_.DisableFilter(f); options_.EnableFilter(f); ASSERT_TRUE(NoneEnabled()); } } TEST_F(RewriteOptionsTest, CoreFilters) { options_.SetRewriteLevel(RewriteOptions::kCoreFilters); FilterSet s; for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; f <= RewriteOptions::kLastFilter; f = static_cast<RewriteOptions::Filter>(f + 1)) { if (options_.Enabled(f)) { s.insert(f); } } // Make sure that more than one filter is enabled in the core filter // set. ASSERT_GT(s.size(), 1); } TEST_F(RewriteOptionsTest, Enable) { FilterSet s; for (RewriteOptions::Filter f = RewriteOptions::kFirstFilter; f <= RewriteOptions::kLastFilter; f = static_cast<RewriteOptions::Filter>(f + 1)) { s.insert(f); options_.EnableFilter(f); ASSERT_TRUE(OnlyEnabled(s)); } } TEST_F(RewriteOptionsTest, CommaSeparatedList) { FilterSet s; s.insert(RewriteOptions::kAddInstrumentation); s.insert(RewriteOptions::kLeftTrimUrls); const char* kList = "add_instrumentation,trim_urls"; NullMessageHandler handler; ASSERT_TRUE( options_.EnableFiltersByCommaSeparatedList(kList, &handler)); ASSERT_TRUE(OnlyEnabled(s)); ASSERT_TRUE( options_.DisableFiltersByCommaSeparatedList(kList, &handler)); ASSERT_TRUE(NoneEnabled()); } TEST_F(RewriteOptionsTest, CompoundFlag) { FilterSet s; // TODO(jmaessen): add kConvertJpegToWebp here when it becomes part of // rewrite_images. s.insert(RewriteOptions::kInlineImages); s.insert(RewriteOptions::kInsertImageDimensions); s.insert(RewriteOptions::kRecompressImages); s.insert(RewriteOptions::kResizeImages); const char* kList = "rewrite_images"; NullMessageHandler handler; ASSERT_TRUE( options_.EnableFiltersByCommaSeparatedList(kList, &handler)); ASSERT_TRUE(OnlyEnabled(s)); ASSERT_TRUE( options_.DisableFiltersByCommaSeparatedList(kList, &handler)); ASSERT_TRUE(NoneEnabled()); } TEST_F(RewriteOptionsTest, ParseRewriteLevel) { RewriteOptions::RewriteLevel level; ASSERT_TRUE(RewriteOptions::ParseRewriteLevel("PassThrough", &level)); ASSERT_EQ(RewriteOptions::kPassThrough, level); ASSERT_TRUE(RewriteOptions::ParseRewriteLevel("CoreFilters", &level)); ASSERT_EQ(RewriteOptions::kCoreFilters, level); ASSERT_FALSE(RewriteOptions::ParseRewriteLevel(NULL, &level)); ASSERT_FALSE(RewriteOptions::ParseRewriteLevel("", &level)); ASSERT_FALSE(RewriteOptions::ParseRewriteLevel("Garbage", &level)); } TEST_F(RewriteOptionsTest, MergeLevelsDefault) { RewriteOptions one, two; options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kPassThrough, options_.level()); } TEST_F(RewriteOptionsTest, MergeLevelsOneCore) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kCoreFilters, options_.level()); } TEST_F(RewriteOptionsTest, MergeLevelsOneCoreTwoPass) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); two.SetRewriteLevel(RewriteOptions::kPassThrough); // overrides default options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kPassThrough, options_.level()); } TEST_F(RewriteOptionsTest, MergeLevelsOnePassTwoCore) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kPassThrough); // overrides default two.SetRewriteLevel(RewriteOptions::kCoreFilters); // overrides one options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kCoreFilters, options_.level()); } TEST_F(RewriteOptionsTest, MergeLevelsBothCore) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); two.SetRewriteLevel(RewriteOptions::kCoreFilters); options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kCoreFilters, options_.level()); } TEST_F(RewriteOptionsTest, MergeFilterPassThrough) { RewriteOptions one, two; options_.Merge(one, two); EXPECT_FALSE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeFilterEnaOne) { RewriteOptions one, two; one.EnableFilter(RewriteOptions::kAddHead); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeFilterEnaTwo) { RewriteOptions one, two; two.EnableFilter(RewriteOptions::kAddHead); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeFilterEnaOneDisTwo) { RewriteOptions one, two; one.EnableFilter(RewriteOptions::kAddHead); two.DisableFilter(RewriteOptions::kAddHead); options_.Merge(one, two); EXPECT_FALSE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeFilterDisOneEnaTwo) { RewriteOptions one, two; one.DisableFilter(RewriteOptions::kAddHead); two.EnableFilter(RewriteOptions::kAddHead); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, MergeCoreFilter) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterEnaOne) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); one.EnableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterEnaTwo) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); two.EnableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterEnaOneDisTwo) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); one.EnableFilter(RewriteOptions::kExtendCache); two.DisableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_FALSE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterDisOne) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); one.DisableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_FALSE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeCoreFilterDisOneEnaTwo) { RewriteOptions one, two; one.SetRewriteLevel(RewriteOptions::kCoreFilters); one.DisableFilter(RewriteOptions::kExtendCache); two.EnableFilter(RewriteOptions::kExtendCache); options_.Merge(one, two); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, MergeThresholdDefault) { RewriteOptions one, two; options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kDefaultCssInlineMaxBytes, options_.css_inline_max_bytes()); } TEST_F(RewriteOptionsTest, MergeThresholdOne) { RewriteOptions one, two; one.set_css_inline_max_bytes(5); options_.Merge(one, two); EXPECT_EQ(5, options_.css_inline_max_bytes()); } TEST_F(RewriteOptionsTest, MergeThresholdTwo) { RewriteOptions one, two; two.set_css_inline_max_bytes(6); options_.Merge(one, two); EXPECT_EQ(6, options_.css_inline_max_bytes()); } TEST_F(RewriteOptionsTest, MergeThresholdOverride) { RewriteOptions one, two; one.set_css_inline_max_bytes(5); two.set_css_inline_max_bytes(6); options_.Merge(one, two); EXPECT_EQ(6, options_.css_inline_max_bytes()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampDefault) { RewriteOptions one, two; options_.Merge(one, two); EXPECT_EQ(RewriteOptions::kDefaultCacheInvalidationTimestamp, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampOne) { RewriteOptions one, two; one.set_cache_invalidation_timestamp(11111111); options_.Merge(one, two); EXPECT_EQ(11111111, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampTwo) { RewriteOptions one, two; two.set_cache_invalidation_timestamp(22222222); options_.Merge(one, two); EXPECT_EQ(22222222, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampOneLarger) { RewriteOptions one, two; one.set_cache_invalidation_timestamp(33333333); two.set_cache_invalidation_timestamp(22222222); options_.Merge(one, two); EXPECT_EQ(33333333, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, MergeCacheInvalidationTimeStampTwoLarger) { RewriteOptions one, two; one.set_cache_invalidation_timestamp(11111111); two.set_cache_invalidation_timestamp(22222222); options_.Merge(one, two); EXPECT_EQ(22222222, options_.cache_invalidation_timestamp()); } TEST_F(RewriteOptionsTest, Allow) { options_.Allow("*.css"); EXPECT_TRUE(options_.IsAllowed("abcd.css")); options_.Disallow("a*.css"); EXPECT_FALSE(options_.IsAllowed("abcd.css")); options_.Allow("ab*.css"); EXPECT_TRUE(options_.IsAllowed("abcd.css")); options_.Disallow("abc*.css"); EXPECT_FALSE(options_.IsAllowed("abcd.css")); } TEST_F(RewriteOptionsTest, MergeAllow) { RewriteOptions one, two; one.Allow("*.css"); EXPECT_TRUE(one.IsAllowed("abcd.css")); one.Disallow("a*.css"); EXPECT_FALSE(one.IsAllowed("abcd.css")); two.Allow("ab*.css"); EXPECT_TRUE(two.IsAllowed("abcd.css")); two.Disallow("abc*.css"); EXPECT_FALSE(two.IsAllowed("abcd.css")); options_.Merge(one, two); EXPECT_FALSE(options_.IsAllowed("abcd.css")); EXPECT_FALSE(options_.IsAllowed("abc.css")); EXPECT_TRUE(options_.IsAllowed("ab.css")); EXPECT_FALSE(options_.IsAllowed("a.css")); } TEST_F(RewriteOptionsTest, DisableAllFiltersNotExplicitlyEnabled) { RewriteOptions one, two; one.EnableFilter(RewriteOptions::kAddHead); two.EnableFilter(RewriteOptions::kExtendCache); two.DisableAllFiltersNotExplicitlyEnabled(); // Should disable AddHead. options_.Merge(one, two); // Make sure AddHead enabling didn't leak through. EXPECT_FALSE(options_.Enabled(RewriteOptions::kAddHead)); EXPECT_TRUE(options_.Enabled(RewriteOptions::kExtendCache)); } TEST_F(RewriteOptionsTest, DisableAllFiltersOverrideFilterLevel) { options_.SetRewriteLevel(RewriteOptions::kCoreFilters); options_.EnableFilter(RewriteOptions::kAddHead); options_.DisableAllFiltersNotExplicitlyEnabled(); // Check that *only* AddHead is enabled, even though we have CoreFilters // level set. EXPECT_TRUE(OnlyEnabled(RewriteOptions::kAddHead)); } TEST_F(RewriteOptionsTest, AllDoesNotImplyStripScrips) { options_.SetRewriteLevel(RewriteOptions::kAllFilters); EXPECT_TRUE(options_.Enabled(RewriteOptions::kCombineCss)); EXPECT_FALSE(options_.Enabled(RewriteOptions::kStripScripts)); } } // namespace <|endoftext|>
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * libtest * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <config.h> #include <libtest/common.h> #include <cassert> #include <cstdlib> #include <cstring> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #include <ctime> #include <fnmatch.h> #include <iostream> #include <signal.h> #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wold-style-cast" #endif using namespace libtest; static void stats_print(Stats *stats) { if (stats->collection_failed == 0 and stats->collection_success == 0) { return; } Out << "\tTotal Collections\t\t\t\t" << stats->collection_total; Out << "\tFailed Collections\t\t\t\t" << stats->collection_failed; Out << "\tSkipped Collections\t\t\t\t" << stats->collection_skipped; Out << "\tSucceeded Collections\t\t\t\t" << stats->collection_success; Outn(); Out << "Total\t\t\t\t" << stats->total; Out << "\tFailed\t\t\t" << stats->failed; Out << "\tSkipped\t\t\t" << stats->skipped; Out << "\tSucceeded\t\t" << stats->success; } static long int timedif(struct timeval a, struct timeval b) { long us, s; us = (long)(a.tv_usec - b.tv_usec); us /= 1000; s = (long)(a.tv_sec - b.tv_sec); s *= 1000; return s + us; } #include <getopt.h> #include <unistd.h> int main(int argc, char *argv[]) { bool opt_massive= false; unsigned long int opt_repeat= 1; // Run all tests once bool opt_quiet= false; std::string collection_to_run; // Options parsing { enum long_option_t { OPT_LIBYATL_VERSION, OPT_LIBYATL_MATCH_COLLECTION, OPT_LIBYATL_MASSIVE, OPT_LIBYATL_QUIET, OPT_LIBYATL_REPEAT }; static struct option long_options[]= { { "version", no_argument, NULL, OPT_LIBYATL_VERSION }, { "quiet", no_argument, NULL, OPT_LIBYATL_QUIET }, { "repeat", no_argument, NULL, OPT_LIBYATL_REPEAT }, { "collection", required_argument, NULL, OPT_LIBYATL_MATCH_COLLECTION }, { "massive", no_argument, NULL, OPT_LIBYATL_MASSIVE }, { 0, 0, 0, 0 } }; int option_index= 0; while (1) { int option_rv= getopt_long(argc, argv, "", long_options, &option_index); if (option_rv == -1) { break; } switch (option_rv) { case OPT_LIBYATL_VERSION: break; case OPT_LIBYATL_QUIET: opt_quiet= true; break; case OPT_LIBYATL_REPEAT: opt_repeat= strtoul(optarg, (char **) NULL, 10); break; case OPT_LIBYATL_MATCH_COLLECTION: collection_to_run= optarg; break; case OPT_LIBYATL_MASSIVE: opt_massive= true; break; case '?': /* getopt_long already printed an error message. */ Error << "unknown option to getopt_long()"; exit(EXIT_FAILURE); default: break; } } } srandom((unsigned int)time(NULL)); if (bool(getenv("YATL_REPEAT")) and (strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10) > 1)) { opt_repeat= strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10); } if ((bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "0") == 0)) or opt_quiet) { opt_quiet= true; } else if (getenv("JENKINS_URL")) { if (bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "1") == 0)) { } else { opt_quiet= true; } } if (opt_quiet) { close(STDOUT_FILENO); } char buffer[1024]; if (getenv("LIBTEST_TMP")) { snprintf(buffer, sizeof(buffer), "%s", getenv("LIBTEST_TMP")); } else { snprintf(buffer, sizeof(buffer), "%s", LIBTEST_TEMP); } if (chdir(buffer) == -1) { char getcwd_buffer[1024]; char *dir= getcwd(getcwd_buffer, sizeof(getcwd_buffer)); Error << "Unable to chdir() from " << dir << " to " << buffer << " errno:" << strerror(errno); return EXIT_FAILURE; } if (libtest::libtool() == NULL) { Error << "Failed to locate libtool"; return EXIT_FAILURE; } int exit_code; try { do { exit_code= EXIT_SUCCESS; Framework world; fatal_assert(sigignore(SIGPIPE) == 0); libtest::SignalThread signal; if (signal.setup() == false) { Error << "Failed to setup signals"; return EXIT_FAILURE; } Stats stats; get_world(&world); test_return_t error; void *creators_ptr= world.create(error); switch (error) { case TEST_SUCCESS: break; case TEST_SKIPPED: Out << "SKIP " << argv[0]; return EXIT_SUCCESS; case TEST_FAILURE: return EXIT_FAILURE; } if (getenv("YATL_COLLECTION_TO_RUN")) { if (strlen(getenv("YATL_COLLECTION_TO_RUN"))) { collection_to_run= getenv("YATL_COLLECTION_TO_RUN"); } } if (collection_to_run.empty() == false) { Out << "Only testing " << collection_to_run; } char *wildcard= NULL; if (argc == 3) { wildcard= argv[2]; } for (collection_st *next= world.collections; next and next->name and (not signal.is_shutdown()); next++) { bool failed= false; bool skipped= false; if (collection_to_run.empty() == false and fnmatch(collection_to_run.c_str(), next->name, 0)) { continue; } stats.collection_total++; test_return_t collection_rc= world.startup(creators_ptr); if (collection_rc == TEST_SUCCESS and next->pre) { collection_rc= world.runner()->pre(next->pre, creators_ptr); } switch (collection_rc) { case TEST_SUCCESS: break; case TEST_FAILURE: Out << next->name << " [ failed ]"; failed= true; signal.set_shutdown(SHUTDOWN_GRACEFUL); goto cleanup; case TEST_SKIPPED: Out << next->name << " [ skipping ]"; skipped= true; goto cleanup; default: fatal_message("invalid return code"); } Out << "Collection: " << next->name; for (test_st *run= next->tests; run->name; run++) { struct timeval start_time, end_time; long int load_time= 0; if (wildcard && fnmatch(wildcard, run->name, 0)) { continue; } test_return_t return_code; try { if (test_success(return_code= world.item.startup(creators_ptr))) { if (test_success(return_code= world.item.flush(creators_ptr, run))) { // @note pre will fail is SKIPPED is returned if (test_success(return_code= world.item.pre(creators_ptr))) { { // Runner Code gettimeofday(&start_time, NULL); assert(world.runner()); assert(run->test_fn); try { return_code= world.runner()->run(run->test_fn, creators_ptr); } // Special case where check for the testing of the exception // system. catch (libtest::fatal &e) { if (fatal::is_disabled()) { fatal::increment_disabled_counter(); return_code= TEST_SUCCESS; } else { throw; } } gettimeofday(&end_time, NULL); load_time= timedif(end_time, start_time); } } // @todo do something if post fails (void)world.item.post(creators_ptr); } else if (return_code == TEST_SKIPPED) { } else if (return_code == TEST_FAILURE) { Error << " item.flush(failure)"; signal.set_shutdown(SHUTDOWN_GRACEFUL); } } else if (return_code == TEST_SKIPPED) { } else if (return_code == TEST_FAILURE) { Error << " item.startup(failure)"; signal.set_shutdown(SHUTDOWN_GRACEFUL); } } catch (libtest::fatal &e) { Error << "Fatal exception was thrown: " << e.what(); return_code= TEST_FAILURE; } catch (std::exception &e) { Error << "Exception was thrown: " << e.what(); return_code= TEST_FAILURE; } catch (...) { Error << "Unknown exception occurred"; return_code= TEST_FAILURE; } stats.total++; switch (return_code) { case TEST_SUCCESS: Out << "\tTesting " << run->name << "\t\t\t\t\t" << load_time / 1000 << "." << load_time % 1000 << "[ " << test_strerror(return_code) << " ]"; stats.success++; break; case TEST_FAILURE: stats.failed++; failed= true; Out << "\tTesting " << run->name << "\t\t\t\t\t" << "[ " << test_strerror(return_code) << " ]"; break; case TEST_SKIPPED: stats.skipped++; skipped= true; Out << "\tTesting " << run->name << "\t\t\t\t\t" << "[ " << test_strerror(return_code) << " ]"; break; default: fatal_message("invalid return code"); } if (test_failed(world.on_error(return_code, creators_ptr))) { Error << "Failed while running on_error()"; signal.set_shutdown(SHUTDOWN_GRACEFUL); break; } } (void) world.runner()->post(next->post, creators_ptr); cleanup: if (failed == false and skipped == false) { stats.collection_success++; } if (failed) { stats.collection_failed++; } if (skipped) { stats.collection_skipped++; } world.shutdown(creators_ptr); Outn(); } if (not signal.is_shutdown()) { signal.set_shutdown(SHUTDOWN_GRACEFUL); } shutdown_t status= signal.get_shutdown(); if (status == SHUTDOWN_FORCED) { Out << "Tests were aborted."; exit_code= EXIT_FAILURE; } else if (stats.collection_failed) { Out << "Some test failed."; exit_code= EXIT_FAILURE; } else if (stats.collection_skipped and stats.collection_failed and stats.collection_success) { Out << "Some tests were skipped."; } else if (stats.collection_success and stats.collection_failed == 0) { Out << "All tests completed successfully."; } stats_print(&stats); Outn(); // Generate a blank to break up the messages if make check/test has been run } while (exit_code == EXIT_SUCCESS and --opt_repeat); } catch (libtest::fatal& e) { std::cerr << e.what() << std::endl; } catch (std::exception& e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "Unknown exception halted execution." << std::endl; } return exit_code; } <commit_msg>Add none support for testing.<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * libtest * * Copyright (C) 2011 Data Differential, http://datadifferential.com/ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <config.h> #include <libtest/common.h> #include <cassert> #include <cstdlib> #include <cstring> #include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <unistd.h> #include <ctime> #include <fnmatch.h> #include <iostream> #include <signal.h> #ifndef __INTEL_COMPILER #pragma GCC diagnostic ignored "-Wold-style-cast" #endif using namespace libtest; static void stats_print(Stats *stats) { if (stats->collection_failed == 0 and stats->collection_success == 0) { return; } Out << "\tTotal Collections\t\t\t\t" << stats->collection_total; Out << "\tFailed Collections\t\t\t\t" << stats->collection_failed; Out << "\tSkipped Collections\t\t\t\t" << stats->collection_skipped; Out << "\tSucceeded Collections\t\t\t\t" << stats->collection_success; Outn(); Out << "Total\t\t\t\t" << stats->total; Out << "\tFailed\t\t\t" << stats->failed; Out << "\tSkipped\t\t\t" << stats->skipped; Out << "\tSucceeded\t\t" << stats->success; } static long int timedif(struct timeval a, struct timeval b) { long us, s; us = (long)(a.tv_usec - b.tv_usec); us /= 1000; s = (long)(a.tv_sec - b.tv_sec); s *= 1000; return s + us; } #include <getopt.h> #include <unistd.h> int main(int argc, char *argv[]) { bool opt_massive= false; unsigned long int opt_repeat= 1; // Run all tests once bool opt_quiet= false; std::string collection_to_run; // Options parsing { enum long_option_t { OPT_LIBYATL_VERSION, OPT_LIBYATL_MATCH_COLLECTION, OPT_LIBYATL_MASSIVE, OPT_LIBYATL_QUIET, OPT_LIBYATL_REPEAT }; static struct option long_options[]= { { "version", no_argument, NULL, OPT_LIBYATL_VERSION }, { "quiet", no_argument, NULL, OPT_LIBYATL_QUIET }, { "repeat", no_argument, NULL, OPT_LIBYATL_REPEAT }, { "collection", required_argument, NULL, OPT_LIBYATL_MATCH_COLLECTION }, { "massive", no_argument, NULL, OPT_LIBYATL_MASSIVE }, { 0, 0, 0, 0 } }; int option_index= 0; while (1) { int option_rv= getopt_long(argc, argv, "", long_options, &option_index); if (option_rv == -1) { break; } switch (option_rv) { case OPT_LIBYATL_VERSION: break; case OPT_LIBYATL_QUIET: opt_quiet= true; break; case OPT_LIBYATL_REPEAT: opt_repeat= strtoul(optarg, (char **) NULL, 10); break; case OPT_LIBYATL_MATCH_COLLECTION: collection_to_run= optarg; break; case OPT_LIBYATL_MASSIVE: opt_massive= true; break; case '?': /* getopt_long already printed an error message. */ Error << "unknown option to getopt_long()"; exit(EXIT_FAILURE); default: break; } } } srandom((unsigned int)time(NULL)); if (bool(getenv("YATL_REPEAT")) and (strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10) > 1)) { opt_repeat= strtoul(getenv("YATL_REPEAT"), (char **) NULL, 10); } if ((bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "0") == 0)) or opt_quiet) { opt_quiet= true; } else if (getenv("JENKINS_URL")) { if (bool(getenv("YATL_QUIET")) and (strcmp(getenv("YATL_QUIET"), "1") == 0)) { } else { opt_quiet= true; } } if (opt_quiet) { close(STDOUT_FILENO); } char buffer[1024]; if (getenv("LIBTEST_TMP")) { snprintf(buffer, sizeof(buffer), "%s", getenv("LIBTEST_TMP")); } else { snprintf(buffer, sizeof(buffer), "%s", LIBTEST_TEMP); } if (chdir(buffer) == -1) { char getcwd_buffer[1024]; char *dir= getcwd(getcwd_buffer, sizeof(getcwd_buffer)); Error << "Unable to chdir() from " << dir << " to " << buffer << " errno:" << strerror(errno); return EXIT_FAILURE; } if (libtest::libtool() == NULL) { Error << "Failed to locate libtool"; return EXIT_FAILURE; } int exit_code; try { do { exit_code= EXIT_SUCCESS; Framework world; fatal_assert(sigignore(SIGPIPE) == 0); libtest::SignalThread signal; if (signal.setup() == false) { Error << "Failed to setup signals"; return EXIT_FAILURE; } Stats stats; get_world(&world); test_return_t error; void *creators_ptr= world.create(error); switch (error) { case TEST_SUCCESS: break; case TEST_SKIPPED: Out << "SKIP " << argv[0]; return EXIT_SUCCESS; case TEST_FAILURE: return EXIT_FAILURE; } if (getenv("YATL_COLLECTION_TO_RUN")) { if (strlen(getenv("YATL_COLLECTION_TO_RUN"))) { collection_to_run= getenv("YATL_COLLECTION_TO_RUN"); } } if (collection_to_run.compare("none") == 0) { return EXIT_SUCCESS; } if (collection_to_run.empty() == false) { Out << "Only testing " << collection_to_run; } char *wildcard= NULL; if (argc == 3) { wildcard= argv[2]; } for (collection_st *next= world.collections; next and next->name and (not signal.is_shutdown()); next++) { bool failed= false; bool skipped= false; if (collection_to_run.empty() == false and fnmatch(collection_to_run.c_str(), next->name, 0)) { continue; } stats.collection_total++; test_return_t collection_rc= world.startup(creators_ptr); if (collection_rc == TEST_SUCCESS and next->pre) { collection_rc= world.runner()->pre(next->pre, creators_ptr); } switch (collection_rc) { case TEST_SUCCESS: break; case TEST_FAILURE: Out << next->name << " [ failed ]"; failed= true; signal.set_shutdown(SHUTDOWN_GRACEFUL); goto cleanup; case TEST_SKIPPED: Out << next->name << " [ skipping ]"; skipped= true; goto cleanup; default: fatal_message("invalid return code"); } Out << "Collection: " << next->name; for (test_st *run= next->tests; run->name; run++) { struct timeval start_time, end_time; long int load_time= 0; if (wildcard && fnmatch(wildcard, run->name, 0)) { continue; } test_return_t return_code; try { if (test_success(return_code= world.item.startup(creators_ptr))) { if (test_success(return_code= world.item.flush(creators_ptr, run))) { // @note pre will fail is SKIPPED is returned if (test_success(return_code= world.item.pre(creators_ptr))) { { // Runner Code gettimeofday(&start_time, NULL); assert(world.runner()); assert(run->test_fn); try { return_code= world.runner()->run(run->test_fn, creators_ptr); } // Special case where check for the testing of the exception // system. catch (libtest::fatal &e) { if (fatal::is_disabled()) { fatal::increment_disabled_counter(); return_code= TEST_SUCCESS; } else { throw; } } gettimeofday(&end_time, NULL); load_time= timedif(end_time, start_time); } } // @todo do something if post fails (void)world.item.post(creators_ptr); } else if (return_code == TEST_SKIPPED) { } else if (return_code == TEST_FAILURE) { Error << " item.flush(failure)"; signal.set_shutdown(SHUTDOWN_GRACEFUL); } } else if (return_code == TEST_SKIPPED) { } else if (return_code == TEST_FAILURE) { Error << " item.startup(failure)"; signal.set_shutdown(SHUTDOWN_GRACEFUL); } } catch (libtest::fatal &e) { Error << "Fatal exception was thrown: " << e.what(); return_code= TEST_FAILURE; } catch (std::exception &e) { Error << "Exception was thrown: " << e.what(); return_code= TEST_FAILURE; } catch (...) { Error << "Unknown exception occurred"; return_code= TEST_FAILURE; } stats.total++; switch (return_code) { case TEST_SUCCESS: Out << "\tTesting " << run->name << "\t\t\t\t\t" << load_time / 1000 << "." << load_time % 1000 << "[ " << test_strerror(return_code) << " ]"; stats.success++; break; case TEST_FAILURE: stats.failed++; failed= true; Out << "\tTesting " << run->name << "\t\t\t\t\t" << "[ " << test_strerror(return_code) << " ]"; break; case TEST_SKIPPED: stats.skipped++; skipped= true; Out << "\tTesting " << run->name << "\t\t\t\t\t" << "[ " << test_strerror(return_code) << " ]"; break; default: fatal_message("invalid return code"); } if (test_failed(world.on_error(return_code, creators_ptr))) { Error << "Failed while running on_error()"; signal.set_shutdown(SHUTDOWN_GRACEFUL); break; } } (void) world.runner()->post(next->post, creators_ptr); cleanup: if (failed == false and skipped == false) { stats.collection_success++; } if (failed) { stats.collection_failed++; } if (skipped) { stats.collection_skipped++; } world.shutdown(creators_ptr); Outn(); } if (not signal.is_shutdown()) { signal.set_shutdown(SHUTDOWN_GRACEFUL); } shutdown_t status= signal.get_shutdown(); if (status == SHUTDOWN_FORCED) { Out << "Tests were aborted."; exit_code= EXIT_FAILURE; } else if (stats.collection_failed) { Out << "Some test failed."; exit_code= EXIT_FAILURE; } else if (stats.collection_skipped and stats.collection_failed and stats.collection_success) { Out << "Some tests were skipped."; } else if (stats.collection_success and stats.collection_failed == 0) { Out << "All tests completed successfully."; } stats_print(&stats); Outn(); // Generate a blank to break up the messages if make check/test has been run } while (exit_code == EXIT_SUCCESS and --opt_repeat); } catch (libtest::fatal& e) { std::cerr << e.what() << std::endl; } catch (std::exception& e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "Unknown exception halted execution." << std::endl; } return exit_code; } <|endoftext|>
<commit_before>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <fstream> #include <string> #include <vector> #include <exception> // StdAir #include <stdair/stdair_demand_types.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/service/Logger.hpp> // Distribution #include <simcrs/SIMCRS_Service.hpp> // TRADEMGEN #include <trademgen/TRADEMGEN_Service.hpp> // Airsched #include <airsched/AIRSCHED_Service.hpp> // Dsim #include <dsim/DSIM_Types.hpp> #include <dsim/command/Simulator.hpp> namespace DSIM { // //////////////////////////////////////////////////////////////////// void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) { // DEBUG STDAIR_LOG_DEBUG ("The simulation is starting"); // Retrieve the expected (mean value of the) number of events to be // generated const stdair::Count_T& lExpectedNbOfEventsToBeGenerated = ioTRADEMGEN_Service.getExpectedTotalNumberOfRequestsToBeGenerated(); /** Initialisation step. <br>Generate the first event for each demand stream. */ const stdair::Count_T& lActualNbOfEventsToBeGenerated = ioTRADEMGEN_Service.generateFirstRequests(); // Initialise the (Boost) progress display object // boost::progress_display lProgressDisplay(lActualNbOfEventsToBeGenerated); // DEBUG STDAIR_LOG_DEBUG ("Expected number of events: " << lExpectedNbOfEventsToBeGenerated << ", actual: " << lActualNbOfEventsToBeGenerated); /** Main loop. <ul> <li>Pop a request and get its associated type/demand stream.</li> <li>Generate the next request for the same type/demand stream.</li> </ul> */ while (ioTRADEMGEN_Service.isQueueDone() == false) { // Get the next event from the event queue const stdair::EventStruct& lEventStruct = ioTRADEMGEN_Service.popEvent(); // DEBUG STDAIR_LOG_DEBUG ("Poped event: '" << lEventStruct.describe() << "'."); // Extract the corresponding demand/booking request const stdair::BookingRequestStruct& lPoppedRequest = lEventStruct.getBookingRequest(); // DEBUG STDAIR_LOG_DEBUG ("Poped booking request: '" << lPoppedRequest.describe() << "'."); // Play booking request playBookingRequest (ioSIMCRS_Service, lPoppedRequest); // Retrieve the corresponding demand stream const stdair::DemandStreamKeyStr_T& lDemandStreamKey = lEventStruct.getDemandStreamKey(); // Assess whether more events should be generated for that demand stream const bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated (lDemandStreamKey); // DEBUG STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. " << "Still generate events for that demand stream? " << stillHavingRequestsToBeGenerated); // If there are still events to be generated for that demand stream, // generate and add them to the event queue if (stillHavingRequestsToBeGenerated) { stdair::BookingRequestPtr_T lNextRequest_ptr = ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey); assert (lNextRequest_ptr != NULL); // Sanity check const stdair::Duration_T lDuration = lNextRequest_ptr->getRequestDateTime() - lPoppedRequest.getRequestDateTime(); if (lDuration.total_milliseconds() < 0) { STDAIR_LOG_ERROR ("[" << lDemandStreamKey << "] The date-time of the generated event (" << lNextRequest_ptr->getRequestDateTime() << ") is lower than the date-time " << "of the current event (" << lPoppedRequest.getRequestDateTime() << ")"); assert (false); } // DEBUG STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '" << lNextRequest_ptr->describe() << "'. Is queue done? " << ioTRADEMGEN_Service.isQueueDone()); } // Update the progress display //++lProgressDisplay; } // DEBUG STDAIR_LOG_DEBUG ("The simulation has ended"); } // //////////////////////////////////////////////////////////////////// void Simulator:: playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, const stdair::BookingRequestStruct& iBookingRequest) { // Retrieve a list of travel solutions corresponding the given // booking request. stdair::TravelSolutionList_T lTravelSolutionList = ioSIMCRS_Service.calculateSegmentPathList (iBookingRequest); if (lTravelSolutionList.empty() == false) { // Get the fare quote for each travel solution. ioSIMCRS_Service.fareQuote (iBookingRequest, lTravelSolutionList); // Get the availability for each travel solution. ioSIMCRS_Service.calculateAvailability (lTravelSolutionList); // Hardcode a travel solution choice. stdair::TravelSolutionList_T::const_iterator itTS = lTravelSolutionList.begin(); const stdair::TravelSolutionStruct& lChosenTS = *itTS; // DEBUG STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS); // Retrieve and convert the party size const stdair::NbOfSeats_T& lPartySizeDouble = iBookingRequest.getPartySize(); const stdair::PartySize_T lPartySize = std::floor (lPartySizeDouble); // Delegate the sell to the corresponding SimCRS service ioSIMCRS_Service.sell (lChosenTS, lPartySize); } else { // DEBUG STDAIR_LOG_DEBUG ("No travel solution has been found/chosen for: " << iBookingRequest); } } } <commit_msg>[Dev] Adapted the code to the new StdAir API for EventStruct.<commit_after>// ////////////////////////////////////////////////////////////////////// // Import section // ////////////////////////////////////////////////////////////////////// // STL #include <fstream> #include <string> #include <vector> #include <exception> // StdAir #include <stdair/stdair_demand_types.hpp> #include <stdair/bom/EventStruct.hpp> #include <stdair/bom/EventQueue.hpp> #include <stdair/bom/BookingRequestStruct.hpp> #include <stdair/bom/TravelSolutionStruct.hpp> #include <stdair/service/Logger.hpp> // Distribution #include <simcrs/SIMCRS_Service.hpp> // TRADEMGEN #include <trademgen/TRADEMGEN_Service.hpp> // Airsched #include <airsched/AIRSCHED_Service.hpp> // Dsim #include <dsim/DSIM_Types.hpp> #include <dsim/command/Simulator.hpp> namespace DSIM { // //////////////////////////////////////////////////////////////////// void Simulator::simulate (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, TRADEMGEN::TRADEMGEN_Service& ioTRADEMGEN_Service) { // DEBUG STDAIR_LOG_DEBUG ("The simulation is starting"); // Retrieve the expected (mean value of the) number of events to be // generated const stdair::Count_T& lExpectedNbOfEventsToBeGenerated = ioTRADEMGEN_Service.getExpectedTotalNumberOfRequestsToBeGenerated(); /** Initialisation step. <br>Generate the first event for each demand stream. */ const stdair::Count_T& lActualNbOfEventsToBeGenerated = ioTRADEMGEN_Service.generateFirstRequests(); // Initialise the (Boost) progress display object // boost::progress_display lProgressDisplay(lActualNbOfEventsToBeGenerated); // DEBUG STDAIR_LOG_DEBUG ("Expected number of events: " << lExpectedNbOfEventsToBeGenerated << ", actual: " << lActualNbOfEventsToBeGenerated); /** Main loop. <ul> <li>Pop a request and get its associated type/demand stream.</li> <li>Generate the next request for the same type/demand stream.</li> </ul> */ while (ioTRADEMGEN_Service.isQueueDone() == false) { // Get the next event from the event queue const stdair::EventStruct& lEventStruct = ioTRADEMGEN_Service.popEvent(); // DEBUG STDAIR_LOG_DEBUG ("Poped event: '" << lEventStruct.describe() << "'."); // Extract the corresponding demand/booking request const stdair::BookingRequestStruct& lPoppedRequest = lEventStruct.getBookingRequest(); // DEBUG STDAIR_LOG_DEBUG ("Poped booking request: '" << lPoppedRequest.describe() << "'."); // Play booking request playBookingRequest (ioSIMCRS_Service, lPoppedRequest); // Retrieve the corresponding demand stream const stdair::EventContentKey_T& lDemandStreamKey = lEventStruct.getEventContentKey(); // Assess whether more events should be generated for that demand stream const bool stillHavingRequestsToBeGenerated = ioTRADEMGEN_Service.stillHavingRequestsToBeGenerated (lDemandStreamKey); // DEBUG STDAIR_LOG_DEBUG ("=> [" << lDemandStreamKey << "] is now processed. " << "Still generate events for that demand stream? " << stillHavingRequestsToBeGenerated); // If there are still events to be generated for that demand stream, // generate and add them to the event queue if (stillHavingRequestsToBeGenerated) { stdair::BookingRequestPtr_T lNextRequest_ptr = ioTRADEMGEN_Service.generateNextRequest (lDemandStreamKey); assert (lNextRequest_ptr != NULL); // Sanity check const stdair::Duration_T lDuration = lNextRequest_ptr->getRequestDateTime() - lPoppedRequest.getRequestDateTime(); if (lDuration.total_milliseconds() < 0) { STDAIR_LOG_ERROR ("[" << lDemandStreamKey << "] The date-time of the generated event (" << lNextRequest_ptr->getRequestDateTime() << ") is lower than the date-time " << "of the current event (" << lPoppedRequest.getRequestDateTime() << ")"); assert (false); } // DEBUG STDAIR_LOG_DEBUG ("[" << lDemandStreamKey << "] Added request: '" << lNextRequest_ptr->describe() << "'. Is queue done? " << ioTRADEMGEN_Service.isQueueDone()); } // Update the progress display //++lProgressDisplay; } // DEBUG STDAIR_LOG_DEBUG ("The simulation has ended"); } // //////////////////////////////////////////////////////////////////// void Simulator:: playBookingRequest (SIMCRS::SIMCRS_Service& ioSIMCRS_Service, const stdair::BookingRequestStruct& iBookingRequest) { // Retrieve a list of travel solutions corresponding the given // booking request. stdair::TravelSolutionList_T lTravelSolutionList = ioSIMCRS_Service.calculateSegmentPathList (iBookingRequest); if (lTravelSolutionList.empty() == false) { // Get the fare quote for each travel solution. ioSIMCRS_Service.fareQuote (iBookingRequest, lTravelSolutionList); // Get the availability for each travel solution. ioSIMCRS_Service.calculateAvailability (lTravelSolutionList); // Hardcode a travel solution choice. stdair::TravelSolutionList_T::const_iterator itTS = lTravelSolutionList.begin(); const stdair::TravelSolutionStruct& lChosenTS = *itTS; // DEBUG STDAIR_LOG_DEBUG ("Chosen TS: " << lChosenTS); // Retrieve and convert the party size const stdair::NbOfSeats_T& lPartySizeDouble = iBookingRequest.getPartySize(); const stdair::PartySize_T lPartySize = std::floor (lPartySizeDouble); // Delegate the sell to the corresponding SimCRS service ioSIMCRS_Service.sell (lChosenTS, lPartySize); } else { // DEBUG STDAIR_LOG_DEBUG ("No travel solution has been found/chosen for: " << iBookingRequest); } } } <|endoftext|>
<commit_before>//===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Utility for creating a in-memory buffer that will be written to a file. // //===----------------------------------------------------------------------===// #include "llvm/Support/FileOutputBuffer.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/system_error.h" using llvm::sys::fs::mapped_file_region; namespace llvm { FileOutputBuffer::FileOutputBuffer(mapped_file_region * R, StringRef Path, StringRef TmpPath) : Region(R) , FinalPath(Path) , TempPath(TmpPath) { } FileOutputBuffer::~FileOutputBuffer() { bool Existed; sys::fs::remove(Twine(TempPath), Existed); } error_code FileOutputBuffer::create(StringRef FilePath, size_t Size, OwningPtr<FileOutputBuffer> &Result, unsigned Flags) { // If file already exists, it must be a regular file (to be mappable). sys::fs::file_status Stat; error_code EC = sys::fs::status(FilePath, Stat); switch (Stat.type()) { case sys::fs::file_type::file_not_found: // If file does not exist, we'll create one. break; case sys::fs::file_type::regular_file: { // If file is not currently writable, error out. // FIXME: There is no sys::fs:: api for checking this. // FIXME: In posix, you use the access() call to check this. } break; default: if (EC) return EC; else return make_error_code(errc::operation_not_permitted); } // Delete target file. bool Existed; EC = sys::fs::remove(FilePath, Existed); if (EC) return EC; // Create new file in same directory but with random name. SmallString<128> TempFilePath; int FD; EC = sys::fs::createUniqueFile(Twine(FilePath) + ".tmp%%%%%%%", FD, TempFilePath); if (EC) return EC; OwningPtr<mapped_file_region> MappedFile(new mapped_file_region( FD, true, mapped_file_region::readwrite, Size, 0, EC)); if (EC) return EC; // If requested, make the output file executable. if ( Flags & F_executable ) { sys::fs::file_status Stat2; EC = sys::fs::status(Twine(TempFilePath), Stat2); if (EC) return EC; sys::fs::perms new_perms = Stat2.permissions(); if ( new_perms & sys::fs::owner_read ) new_perms |= sys::fs::owner_exe; if ( new_perms & sys::fs::group_read ) new_perms |= sys::fs::group_exe; if ( new_perms & sys::fs::others_read ) new_perms |= sys::fs::others_exe; new_perms |= sys::fs::add_perms; EC = sys::fs::permissions(Twine(TempFilePath), new_perms); if (EC) return EC; } Result.reset(new FileOutputBuffer(MappedFile.get(), FilePath, TempFilePath)); if (Result) MappedFile.take(); return error_code::success(); } error_code FileOutputBuffer::commit(int64_t NewSmallerSize) { // Unmap buffer, letting OS flush dirty pages to file on disk. Region.reset(0); // If requested, resize file as part of commit. if ( NewSmallerSize != -1 ) { error_code EC = sys::fs::resize_file(Twine(TempPath), NewSmallerSize); if (EC) return EC; } // Rename file to final name. return sys::fs::rename(Twine(TempPath), Twine(FinalPath)); } } // namespace <commit_msg>Create files with the correct permission instead of changing it afterwards.<commit_after>//===- FileOutputBuffer.cpp - File Output Buffer ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Utility for creating a in-memory buffer that will be written to a file. // //===----------------------------------------------------------------------===// #include "llvm/Support/FileOutputBuffer.h" #include "llvm/ADT/OwningPtr.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/system_error.h" using llvm::sys::fs::mapped_file_region; namespace llvm { FileOutputBuffer::FileOutputBuffer(mapped_file_region * R, StringRef Path, StringRef TmpPath) : Region(R) , FinalPath(Path) , TempPath(TmpPath) { } FileOutputBuffer::~FileOutputBuffer() { bool Existed; sys::fs::remove(Twine(TempPath), Existed); } error_code FileOutputBuffer::create(StringRef FilePath, size_t Size, OwningPtr<FileOutputBuffer> &Result, unsigned Flags) { // If file already exists, it must be a regular file (to be mappable). sys::fs::file_status Stat; error_code EC = sys::fs::status(FilePath, Stat); switch (Stat.type()) { case sys::fs::file_type::file_not_found: // If file does not exist, we'll create one. break; case sys::fs::file_type::regular_file: { // If file is not currently writable, error out. // FIXME: There is no sys::fs:: api for checking this. // FIXME: In posix, you use the access() call to check this. } break; default: if (EC) return EC; else return make_error_code(errc::operation_not_permitted); } // Delete target file. bool Existed; EC = sys::fs::remove(FilePath, Existed); if (EC) return EC; unsigned Mode = sys::fs::all_read | sys::fs::all_write; // If requested, make the output file executable. if (Flags & F_executable) Mode |= sys::fs::all_exe; // Create new file in same directory but with random name. SmallString<128> TempFilePath; int FD; EC = sys::fs::createUniqueFile(Twine(FilePath) + ".tmp%%%%%%%", FD, TempFilePath, Mode); if (EC) return EC; OwningPtr<mapped_file_region> MappedFile(new mapped_file_region( FD, true, mapped_file_region::readwrite, Size, 0, EC)); if (EC) return EC; Result.reset(new FileOutputBuffer(MappedFile.get(), FilePath, TempFilePath)); if (Result) MappedFile.take(); return error_code::success(); } error_code FileOutputBuffer::commit(int64_t NewSmallerSize) { // Unmap buffer, letting OS flush dirty pages to file on disk. Region.reset(0); // If requested, resize file as part of commit. if ( NewSmallerSize != -1 ) { error_code EC = sys::fs::resize_file(Twine(TempPath), NewSmallerSize); if (EC) return EC; } // Rename file to final name. return sys::fs::rename(Twine(TempPath), Twine(FinalPath)); } } // namespace <|endoftext|>
<commit_before> #include "spdy_framer.H" #include <phantom/module.H> #include <pd/base/config.H> #include <pd/base/exception.H> #include <string.h> // memset #include "spdy_misc.H" namespace phantom { namespace io_benchmark { namespace method_stream { namespace { struct stream_data_t { inline stream_data_t(const in_segment_t &p) : post_data_str(in_t::ptr_t(p).__chunk()), post_data_ptr(post_data_str) { }; str_t post_data_str; str_t::ptr_t post_data_ptr; }; ssize_t read_callback(spdylay_session* UNUSED(session), int32_t UNUSED(stream_id), uint8_t* buf, size_t length, int* eof, spdylay_data_source* source, void* UNUSED(user_data)) { stream_data_t *sd = (static_cast<stream_data_t*>(source->ptr)); if (!sd->post_data_ptr) { *eof = 1; return 0; } size_t to_copy = min(length, sd->post_data_ptr.size()); out_t out((char*)buf, to_copy); out(sd->post_data_ptr); sd->post_data_ptr += to_copy; return to_copy; } } spdy_framer_t::spdy_framer_t(const ssl_ctx_t& c) : spdy_version_(spdy3_1), ctx_(c), session_(nullptr), in_flight_requests_(0) {} spdy_framer_t::~spdy_framer_t() { spdylay_session_del(session_); } bool spdy_framer_t::start() { log_debug("SPDY: starting framer %lx", this); if (string_t::cmp_eq<ident_t>(ctx_.negotiated_proto, CSTR("spdy/2"))) spdy_version_ = spdy2; else if (string_t::cmp_eq<ident_t>(ctx_.negotiated_proto, CSTR("spdy/3"))) spdy_version_ = spdy3; else if (string_t::cmp_eq<ident_t>(ctx_.negotiated_proto, CSTR("spdy/3.1"))) spdy_version_ = spdy3_1; else throw exception_sys_t(log::error, EPROTO, "Unknown proto negotiated %.*s", (int)ctx_.negotiated_proto.size(), ctx_.negotiated_proto.ptr()); log_debug("SPDY: version %d", spdy_version_); memset(&callbacks_, 0, sizeof(callbacks_)); callbacks_.send_callback = &do_send; callbacks_.on_ctrl_recv_callback = &on_ctrl_recv_callback; callbacks_.on_data_recv_callback = &on_data_recv_callback; callbacks_.on_stream_close_callback = &on_stream_close_callback; // TODO Add more callbacks int rv = spdylay_session_client_new(&session_, spdy_version_, &callbacks_, this); if (rv != 0) return false; // Change WINDOW_SIZE to bloody large one to avoid additional control frames spdylay_settings_entry settings[] = { { SPDYLAY_SETTINGS_INITIAL_WINDOW_SIZE, 0, (1<<30U) - 1} }; rv = spdylay_submit_settings(session_, 0, settings, 1); return rv == 0; } bool spdy_framer_t::receive_data(in_t::ptr_t& in, unsigned int& res_code) { last_res_code_ = 0; if (!in) return false; str_t s = in.__chunk(); log_debug("SPDY: receive_data %ld", s.size()); while (s.size() > 0) { int processed = spdylay_session_mem_recv( session_, reinterpret_cast<const uint8_t*>(s.ptr()), s.size()); if (processed < 0) return false; s = str_t(s.ptr() + processed, s.size() - processed); } res_code = last_res_code_; return true; } bool spdy_framer_t::send_data(in_segment_t &out) { spdylay_session_send(session_); out = send_buffer_; send_buffer_.clear(); log_debug("SPDY: send_data %lu", out.size()); return true; } int spdy_framer_t::submit_request(uint8_t pri, const char** nv, const in_segment_t& post_body) { stream_data_t* stream_data = nullptr; spdylay_data_provider data_prd; if (post_body) { stream_data = new stream_data_t(post_body); data_prd.source.ptr = stream_data; data_prd.read_callback = read_callback; } in_flight_requests_++; return spdylay_submit_request( session_, pri, nv, stream_data ? &data_prd : nullptr, stream_data); } ssize_t spdy_framer_t::do_send(spdylay_session* UNUSED(session), const uint8_t* data, size_t length, int UNUSED(flags), void *user_data) { spdy_framer_t* self = static_cast<spdy_framer_t*>(user_data); string_t::ctor_t buf(length); for (size_t i = 0; i < length; ++i) buf(*data++); string_t s = buf; self->send_buffer_.append(s); return length; } void spdy_framer_t::on_ctrl_recv_callback(spdylay_session* UNUSED(session), spdylay_frame_type type, spdylay_frame* frame, void* user_data) { spdy_framer_t* self = static_cast<spdy_framer_t*>(user_data); log_debug("SPDY: Got CONTROL frame type %d %d %ld", type, frame->ctrl.hd.flags, self->in_flight_requests_); if (type == SPDYLAY_SYN_REPLY) { // Search for :status and extract it // Iterate over even headers. for (ssize_t i = 0; frame->syn_reply.nv[i]; i +=2 ) { if (strncmp(frame->syn_reply.nv[i], ":status", 7) == 0) { char* end; self->last_res_code_ = strtoul(frame->syn_reply.nv[i+1], &end, 10); if (*end != ' ') { log_debug("Failed to parse status line"); self->last_res_code_ = 500; } log_debug("SPDY: status '%d'", self->last_res_code_); break; } } } } void spdy_framer_t::on_data_recv_callback(spdylay_session* UNUSED(session), uint8_t flags, int32_t stream_id, int32_t length, void* user_data) { spdy_framer_t* self = static_cast<spdy_framer_t*>(user_data); log_debug("SPDY: Got DATA frame for stream %d length %d flags %d (%ld)", stream_id, length, flags, self->in_flight_requests_); } void spdy_framer_t::on_stream_close_callback( spdylay_session* session, int32_t stream_id, spdylay_status_code status_code, void* user_data) { spdy_framer_t* self = static_cast<spdy_framer_t*>(user_data); log_debug("SPDY: Session closed %d with code %d (%ld)", stream_id, status_code, self->in_flight_requests_); stream_data_t *stream_data = static_cast<stream_data_t*>( spdylay_session_get_stream_user_data(session, stream_id)); delete stream_data; self->in_flight_requests_--; } }}} // namespace phantom::io_benchmark::method_stream <commit_msg>Return fake 100 continue result code when no CONTROL frames arrived<commit_after> #include "spdy_framer.H" #include <phantom/module.H> #include <pd/base/config.H> #include <pd/base/exception.H> #include <string.h> // memset #include "spdy_misc.H" namespace phantom { namespace io_benchmark { namespace method_stream { namespace { struct stream_data_t { inline stream_data_t(const in_segment_t &p) : post_data_str(in_t::ptr_t(p).__chunk()), post_data_ptr(post_data_str) { }; str_t post_data_str; str_t::ptr_t post_data_ptr; }; ssize_t read_callback(spdylay_session* UNUSED(session), int32_t UNUSED(stream_id), uint8_t* buf, size_t length, int* eof, spdylay_data_source* source, void* UNUSED(user_data)) { stream_data_t *sd = (static_cast<stream_data_t*>(source->ptr)); if (!sd->post_data_ptr) { *eof = 1; return 0; } size_t to_copy = min(length, sd->post_data_ptr.size()); out_t out((char*)buf, to_copy); out(sd->post_data_ptr); sd->post_data_ptr += to_copy; return to_copy; } } spdy_framer_t::spdy_framer_t(const ssl_ctx_t& c) : spdy_version_(spdy3_1), ctx_(c), session_(nullptr), in_flight_requests_(0) {} spdy_framer_t::~spdy_framer_t() { spdylay_session_del(session_); } bool spdy_framer_t::start() { log_debug("SPDY: starting framer %lx", this); if (string_t::cmp_eq<ident_t>(ctx_.negotiated_proto, CSTR("spdy/2"))) spdy_version_ = spdy2; else if (string_t::cmp_eq<ident_t>(ctx_.negotiated_proto, CSTR("spdy/3"))) spdy_version_ = spdy3; else if (string_t::cmp_eq<ident_t>(ctx_.negotiated_proto, CSTR("spdy/3.1"))) spdy_version_ = spdy3_1; else throw exception_sys_t(log::error, EPROTO, "Unknown proto negotiated %.*s", (int)ctx_.negotiated_proto.size(), ctx_.negotiated_proto.ptr()); log_debug("SPDY: version %d", spdy_version_); memset(&callbacks_, 0, sizeof(callbacks_)); callbacks_.send_callback = &do_send; callbacks_.on_ctrl_recv_callback = &on_ctrl_recv_callback; callbacks_.on_data_recv_callback = &on_data_recv_callback; callbacks_.on_stream_close_callback = &on_stream_close_callback; // TODO Add more callbacks int rv = spdylay_session_client_new(&session_, spdy_version_, &callbacks_, this); if (rv != 0) return false; // Change WINDOW_SIZE to bloody large one to avoid additional control frames spdylay_settings_entry settings[] = { { SPDYLAY_SETTINGS_INITIAL_WINDOW_SIZE, 0, (1<<30U) - 1} }; rv = spdylay_submit_settings(session_, 0, settings, 1); return rv == 0; } bool spdy_framer_t::receive_data(in_t::ptr_t& in, unsigned int& res_code) { last_res_code_ = 100; // Fake "100 Continue" if (!in) return false; str_t s = in.__chunk(); log_debug("SPDY: receive_data %ld", s.size()); while (s.size() > 0) { int processed = spdylay_session_mem_recv( session_, reinterpret_cast<const uint8_t*>(s.ptr()), s.size()); if (processed < 0) return false; s = str_t(s.ptr() + processed, s.size() - processed); } res_code = last_res_code_; return true; } bool spdy_framer_t::send_data(in_segment_t &out) { spdylay_session_send(session_); out = send_buffer_; send_buffer_.clear(); log_debug("SPDY: send_data %lu", out.size()); return true; } int spdy_framer_t::submit_request(uint8_t pri, const char** nv, const in_segment_t& post_body) { stream_data_t* stream_data = nullptr; spdylay_data_provider data_prd; if (post_body) { stream_data = new stream_data_t(post_body); data_prd.source.ptr = stream_data; data_prd.read_callback = read_callback; } in_flight_requests_++; return spdylay_submit_request( session_, pri, nv, stream_data ? &data_prd : nullptr, stream_data); } ssize_t spdy_framer_t::do_send(spdylay_session* UNUSED(session), const uint8_t* data, size_t length, int UNUSED(flags), void *user_data) { spdy_framer_t* self = static_cast<spdy_framer_t*>(user_data); string_t::ctor_t buf(length); for (size_t i = 0; i < length; ++i) buf(*data++); string_t s = buf; self->send_buffer_.append(s); return length; } void spdy_framer_t::on_ctrl_recv_callback(spdylay_session* UNUSED(session), spdylay_frame_type type, spdylay_frame* frame, void* user_data) { spdy_framer_t* self = static_cast<spdy_framer_t*>(user_data); log_debug("SPDY: Got CONTROL frame type %d %d %ld", type, frame->ctrl.hd.flags, self->in_flight_requests_); if (type == SPDYLAY_SYN_REPLY) { // Search for :status and extract it // Iterate over even headers. for (ssize_t i = 0; frame->syn_reply.nv[i]; i +=2 ) { if (strncmp(frame->syn_reply.nv[i], ":status", 7) == 0) { char* end; self->last_res_code_ = strtoul(frame->syn_reply.nv[i+1], &end, 10); if (*end != ' ') { log_debug("Failed to parse status line"); self->last_res_code_ = 500; } log_debug("SPDY: status '%d'", self->last_res_code_); break; } } } } void spdy_framer_t::on_data_recv_callback(spdylay_session* UNUSED(session), uint8_t flags, int32_t stream_id, int32_t length, void* user_data) { spdy_framer_t* self = static_cast<spdy_framer_t*>(user_data); log_debug("SPDY: Got DATA frame for stream %d length %d flags %d (%ld)", stream_id, length, flags, self->in_flight_requests_); } void spdy_framer_t::on_stream_close_callback( spdylay_session* session, int32_t stream_id, spdylay_status_code status_code, void* user_data) { spdy_framer_t* self = static_cast<spdy_framer_t*>(user_data); log_debug("SPDY: Session closed %d with code %d (%ld)", stream_id, status_code, self->in_flight_requests_); stream_data_t *stream_data = static_cast<stream_data_t*>( spdylay_session_get_stream_user_data(session, stream_id)); delete stream_data; self->in_flight_requests_--; } }}} // namespace phantom::io_benchmark::method_stream <|endoftext|>
<commit_before>#include "base.hpp" using namespace std; namespace Origen { namespace TestMethod { Base::Base() { async(false); syncup(false); } Base::~Base() { } /// Returns 1 when running in offline mode int Base::offline() { int flag; GET_SYSTEM_FLAG("offline", &flag); return flag; } void Base::initialize() { addParameter("testName", "string", &_testName, testmethod::TM_PARAMETER_INPUT); addParameter("forcePass", "int", &_forcePass, testmethod::TM_PARAMETER_INPUT); addParameter("onPassFlag", "string", &_onPassFlag, testmethod::TM_PARAMETER_INPUT); addParameter("onFailFlag", "string", &_onFailFlag, testmethod::TM_PARAMETER_INPUT); bFirstRun = true; init(); } void Base::run() { ARRAY_I sites; RDI_INIT(); ON_FIRST_INVOCATION_BEGIN(); enableHiddenUpload(); GET_ACTIVE_SITES(activeSites); numberOfPhysicalSites = GET_CONFIGURED_SITES(sites); GET_TESTSUITE_NAME(suiteName); suiteFailed.resize(numberOfPhysicalSites + 1); _setup(); callPreBody(); ON_FIRST_INVOCATION_END(); suiteFailed[CURRENT_SITE_NUMBER()] = 0; body(); callPostBody(this); if (suiteFailed[CURRENT_SITE_NUMBER()]) { if (_onFailFlag != "") { SET_USER_DOUBLE(_onFailFlag, 1); } } else { if (_onPassFlag != "") { SET_USER_DOUBLE(_onPassFlag, 1); } } bFirstRun = false; } void Base::datalog(double value) { TESTSET().testnumber(testNumber()).cont(true).TEST("", testName(), noLimits(), value); } void Base::datalog(string testName, double value) { TESTSET().testnumber(testNumber(testName)).cont(true).TEST("", testName, noLimits(), value); } void Base::judgeAndDatalog(double value) { bool alreadyFailed = suiteFailed[CURRENT_SITE_NUMBER()]; if (!alreadyFailed) { suiteFailed[CURRENT_SITE_NUMBER()] = !preJudge(value); } TESTSET().testnumber(testNumber()).cont(true).judgeAndLog_ParametricTest("", testName(), _forcePass ? toNALimit(testLimits().TEST_API_LIMIT) : testLimits().TEST_API_LIMIT, value); // Preserve the first bin assigned within this test suite as the final one if (!alreadyFailed) { SET_MULTIBIN(testLimits().BinsNumString, testLimits().BinhNum); } } void Base::judgeAndDatalog(string testName, double value) { bool alreadyFailed = suiteFailed[CURRENT_SITE_NUMBER()]; if (!alreadyFailed) { suiteFailed[CURRENT_SITE_NUMBER()] = !preJudge(testName, value); } TESTSET().testnumber(testNumber(testName)).cont(true).judgeAndLog_ParametricTest("", testName, _forcePass ? toNALimit(testLimits(testName).TEST_API_LIMIT) : testLimits(testName).TEST_API_LIMIT, value); // Preserve the first bin assigned within this test suite as the final one if (!alreadyFailed) { SET_MULTIBIN(testLimits().BinsNumString, testLimits().BinhNum); } } /// Returns true if the given value will pass the current test, but does not affect the site status if it fails bool Base::preJudge(double value) { return isWithinLimits(value, testLimits().TEST_API_LIMIT); } /// Returns true if the given value will pass the given test, but does not affect the site status if it fails bool Base::preJudge(string testName, double value) { return isWithinLimits(value, testLimits(testName).TEST_API_LIMIT); } /// Returns true if the given value is within the given limits bool Base::isWithinLimits(double value, LIMIT limits) { bool passed = true; double dHigh(0), dLow(0); TM::COMPARE cHigh, cLow; limits.get(cLow, dLow, cHigh, dHigh); if (cLow == TM::GT && value <= dLow) { passed = false; } else if (cLow == TM::GE && value < dLow) { passed = false; } if (cHigh == TM::LT && value >= dHigh) { passed = false; } else if (cHigh == TM::LE && value > dHigh) { passed = false; } return passed; } /// Converts the given limits object to an equivalent version with the limit types set to N/A LIMIT Base::toNALimit(LIMIT limits) { LIMIT naLimit(limits); double dHigh(0), dLow(0); limits.getHigh(&dHigh); limits.getLow(&dLow); naLimit.high(TM::NA, dHigh); naLimit.low(TM::NA, dLow); return naLimit; } /// Returns the base test number int Base::testNumber() { return testLimits().TestNumber; } /// Returns the test test number for the given test name int Base::testNumber(string testName) { return testLimits(testName).TestNumber; } /// Returns the base test limits TMLimits::LimitInfo Base::testLimits() { // Doesn't seem like this should be required from the documentation, but had some // problems with getLimitRef not working properly without it when other code has set // a specific key. tmLimits.setDefaultLookupKeys(); return tmLimits.getLimitRef(suiteName, testName()); } /// Returns the test limits for the given test name TMLimits::LimitInfo Base::testLimits(string testName) { // Doesn't seem like this should be required from the documentation, but had some // problems with getLimitRef not working properly without it when other code has set // a specific key. tmLimits.setDefaultLookupKeys(); return tmLimits.getLimitRef(suiteName, testName); } /// Returns the value of the testName parameter supplied from the test suite, or if not supplied falls back /// to the test suite name string Base::testName() { if (_testName == "") { return suiteName; } else { return _testName; } } /// Changes a 0 -> 1 and 1 -> 0 if Origen::invertFunctionalResults has been set to true int Base::invertFunctionalResultIfRequired(int v) { if (Origen::invertFunctionalResults) { return v == 1 ? 0 : 1; } else { return v; } } } } <commit_msg>Don't allow monitor test (forced to pass) to set the bin<commit_after>#include "base.hpp" using namespace std; namespace Origen { namespace TestMethod { Base::Base() { async(false); syncup(false); } Base::~Base() { } /// Returns 1 when running in offline mode int Base::offline() { int flag; GET_SYSTEM_FLAG("offline", &flag); return flag; } void Base::initialize() { addParameter("testName", "string", &_testName, testmethod::TM_PARAMETER_INPUT); addParameter("forcePass", "int", &_forcePass, testmethod::TM_PARAMETER_INPUT); addParameter("onPassFlag", "string", &_onPassFlag, testmethod::TM_PARAMETER_INPUT); addParameter("onFailFlag", "string", &_onFailFlag, testmethod::TM_PARAMETER_INPUT); bFirstRun = true; init(); } void Base::run() { ARRAY_I sites; RDI_INIT(); ON_FIRST_INVOCATION_BEGIN(); enableHiddenUpload(); GET_ACTIVE_SITES(activeSites); numberOfPhysicalSites = GET_CONFIGURED_SITES(sites); GET_TESTSUITE_NAME(suiteName); suiteFailed.resize(numberOfPhysicalSites + 1); _setup(); callPreBody(); ON_FIRST_INVOCATION_END(); suiteFailed[CURRENT_SITE_NUMBER()] = 0; body(); callPostBody(this); if (suiteFailed[CURRENT_SITE_NUMBER()]) { if (_onFailFlag != "") { SET_USER_DOUBLE(_onFailFlag, 1); } } else { if (_onPassFlag != "") { SET_USER_DOUBLE(_onPassFlag, 1); } } bFirstRun = false; } void Base::datalog(double value) { TESTSET().testnumber(testNumber()).cont(true).TEST("", testName(), noLimits(), value); } void Base::datalog(string testName, double value) { TESTSET().testnumber(testNumber(testName)).cont(true).TEST("", testName, noLimits(), value); } void Base::judgeAndDatalog(double value) { bool alreadyFailed = suiteFailed[CURRENT_SITE_NUMBER()]; if (!alreadyFailed) { suiteFailed[CURRENT_SITE_NUMBER()] = !preJudge(value); } TESTSET().testnumber(testNumber()).cont(true).judgeAndLog_ParametricTest("", testName(), _forcePass ? toNALimit(testLimits().TEST_API_LIMIT) : testLimits().TEST_API_LIMIT, value); // Preserve the first bin assigned within this test suite as the final one if ((!alreadyFailed)&&(!_forcePass)&&(suiteFailed[CURRENT_SITE_NUMBER()])) { SET_MULTIBIN(testLimits().BinsNumString, testLimits().BinhNum); } } void Base::judgeAndDatalog(string testName, double value) { bool alreadyFailed = suiteFailed[CURRENT_SITE_NUMBER()]; if (!alreadyFailed) { suiteFailed[CURRENT_SITE_NUMBER()] = !preJudge(testName, value); } TESTSET().testnumber(testNumber(testName)).cont(true).judgeAndLog_ParametricTest("", testName, _forcePass ? toNALimit(testLimits(testName).TEST_API_LIMIT) : testLimits(testName).TEST_API_LIMIT, value); // Preserve the first bin assigned within this test suite as the final one if ((!alreadyFailed)&&(!_forcePass)&&(suiteFailed[CURRENT_SITE_NUMBER()])) { SET_MULTIBIN(testLimits().BinsNumString, testLimits().BinhNum); } } /// Returns true if the given value will pass the current test, but does not affect the site status if it fails bool Base::preJudge(double value) { return isWithinLimits(value, testLimits().TEST_API_LIMIT); } /// Returns true if the given value will pass the given test, but does not affect the site status if it fails bool Base::preJudge(string testName, double value) { return isWithinLimits(value, testLimits(testName).TEST_API_LIMIT); } /// Returns true if the given value is within the given limits bool Base::isWithinLimits(double value, LIMIT limits) { bool passed = true; double dHigh(0), dLow(0); TM::COMPARE cHigh, cLow; limits.get(cLow, dLow, cHigh, dHigh); if (cLow == TM::GT && value <= dLow) { passed = false; } else if (cLow == TM::GE && value < dLow) { passed = false; } if (cHigh == TM::LT && value >= dHigh) { passed = false; } else if (cHigh == TM::LE && value > dHigh) { passed = false; } return passed; } /// Converts the given limits object to an equivalent version with the limit types set to N/A LIMIT Base::toNALimit(LIMIT limits) { LIMIT naLimit(limits); double dHigh(0), dLow(0); limits.getHigh(&dHigh); limits.getLow(&dLow); naLimit.high(TM::NA, dHigh); naLimit.low(TM::NA, dLow); return naLimit; } /// Returns the base test number int Base::testNumber() { return testLimits().TestNumber; } /// Returns the test test number for the given test name int Base::testNumber(string testName) { return testLimits(testName).TestNumber; } /// Returns the base test limits TMLimits::LimitInfo Base::testLimits() { // Doesn't seem like this should be required from the documentation, but had some // problems with getLimitRef not working properly without it when other code has set // a specific key. tmLimits.setDefaultLookupKeys(); return tmLimits.getLimitRef(suiteName, testName()); } /// Returns the test limits for the given test name TMLimits::LimitInfo Base::testLimits(string testName) { // Doesn't seem like this should be required from the documentation, but had some // problems with getLimitRef not working properly without it when other code has set // a specific key. tmLimits.setDefaultLookupKeys(); return tmLimits.getLimitRef(suiteName, testName); } /// Returns the value of the testName parameter supplied from the test suite, or if not supplied falls back /// to the test suite name string Base::testName() { if (_testName == "") { return suiteName; } else { return _testName; } } /// Changes a 0 -> 1 and 1 -> 0 if Origen::invertFunctionalResults has been set to true int Base::invertFunctionalResultIfRequired(int v) { if (Origen::invertFunctionalResults) { return v == 1 ? 0 : 1; } else { return v; } } } } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -std=c++11 -fsyntax-only %s -verify namespace ExplicitConv { struct X { }; // expected-note 2{{candidate constructor}} struct Y { explicit operator X() const; }; void test(const Y& y) { X x(static_cast<X>(y)); X x2((X)y); X x3 = y; // expected-error{{no viable conversion from 'const ExplicitConv::Y' to 'ExplicitConv::X'}} } } <commit_msg>Add test for C++ DR899.<commit_after>// RUN: %clang_cc1 -std=c++11 -fsyntax-only %s -verify namespace ExplicitConv { struct X { }; // expected-note 2{{candidate constructor}} struct Y { explicit operator X() const; }; void test(const Y& y) { X x(static_cast<X>(y)); X x2((X)y); X x3 = y; // expected-error{{no viable conversion from 'const ExplicitConv::Y' to 'ExplicitConv::X'}} } } namespace DR899 { struct C { }; // expected-note 2 {{candidate constructor}} struct A { explicit operator int() const; explicit operator C() const; }; struct B { int i; B(const A& a): i(a) { } }; int main() { A a; int i = a; // expected-error{{no viable conversion}} int j(a); C c = a; // expected-error{{no viable conversion}} C c2(a); } } <|endoftext|>
<commit_before>/* gph-math - math library for graphics programs Copyright (C) 2016 John Tsiombikas <[email protected]> This program is free software. Feel free to use, modify, and/or redistribute it under the terms of the MIT/X11 license. See LICENSE for details. If you intend to redistribute parts of the code without the LICENSE file replace this paragraph with the full contents of the LICENSE file. */ inline Quat operator -(const Quat &q) { return Quat(-q.x, -q.y, -q.z, -q.w); } inline Quat operator +(const Quat &a, const Quat &b) { return Quat(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } inline Quat operator -(const Quat &a, const Quat &b) { return Quat(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } inline Quat operator *(const Quat &a, const Quat &b) { Vec3 a_im = Vec3(a.x, a.y, a.z); Vec3 b_im = Vec3(b.x, b.y, b.z); float w = a.w * b.w - dot(a_im, b_im); Vec3 im = a.w * b_im + b.w * a_im + cross(a_im, b_im); return Quat(im.x, im.y, im.z, w); } inline Quat &operator +=(Quat &a, const Quat &b) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; return a; } inline Quat &operator -=(Quat &a, const Quat &b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; return a; } inline Quat &operator *=(Quat &a, const Quat &b) { Vec3 a_im = Vec3(a.x, a.y, a.z); Vec3 b_im = Vec3(b.x, b.y, b.z); float w = a.w * b.w - dot(a_im, b_im); Vec3 im = a.w * b_im + b.w * a_im + cross(a_im, b_im); a = Quat(im.x, im.y, im.z, w); return a; } inline float length(const Quat &q) { return (float)sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); } inline float length_sq(const Quat &q) { return q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w; } inline void Quat::normalize() { float len = length(*this); if(len != 0.0f) { x /= len; y /= len; z /= len; w /= len; } } inline Quat normalize(const Quat &q) { float len = length(q); if(len != 0.0f) { return Quat(q.x / len, q.y / len, q.z / len, q.w / len); } return q; } inline void Quat::conjugate() { x = -x; y = -y; z = -z; } inline Quat conjugate(const Quat &q) { return Quat(-q.x, -q.y, -q.z, q.w); } inline void Quat::invert() { Quat conj = gph::conjugate(*this); float len_sq = length_sq(conj); if(len_sq != 0.0) { x = conj.x / len_sq; y = conj.y / len_sq; z = conj.z / len_sq; w = conj.w / len_sq; } } inline Quat inverse(const Quat &q) { Quat conj = conjugate(q); float len_sq = length_sq(conj); if(len_sq != 0.0) { return Quat(conj.x / len_sq, conj.y / len_sq, conj.z / len_sq, conj.w / len_sq); } return q; } inline void Quat::set_rotation(const Vec3 &axis, float angle) { float half_angle = angle * 0.5f; w = cos(half_angle); float sin_ha = sin(half_angle); x = axis.x * sin_ha; y = axis.y * sin_ha; z = axis.z * sin_ha; } inline void Quat::rotate(const Vec3 &axis, float angle) { Quat q; float half_angle = angle * 0.5f; q.w = cos(half_angle); float sin_ha = sin(half_angle); q.x = axis.x * sin_ha; q.y = axis.y * sin_ha; q.z = axis.z * sin_ha; *this *= q; } inline void Quat::rotate(const Quat &rq) { *this = rq * *this * gph::conjugate(rq); } inline Mat4 Quat::calc_matrix() const { float xsq2 = 2.0 * x * x; float ysq2 = 2.0 * y * y; float zsq2 = 2.0 * z * z; float sx = 1.0 - ysq2 - zsq2; float sy = 1.0 - xsq2 - zsq2; float sz = 1.0 - xsq2 - ysq2; return Mat4( sx, 2.0 * x * y - 2.0 * w * z, 2.0 * z * x + 2.0 * w * y, 0, 2.0 * x * y + 2.0 * w * z, sy, 2.0 * y * z - 2.0 * w * x, 0, 2.0 * z * x - 2.0 * w * y, 2.0 * y * z + 2.0 * w * x, sz, 0, 0, 0, 0, 1); } inline Quat slerp(const Quat &quat1, const Quat &q2, float t) { Quat q1 = quat1; float dot = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z; if(dot < 0.0) { /* make sure we interpolate across the shortest arc */ q1 = -quat1; dot = -dot; } /* clamp dot to [-1, 1] in order to avoid domain errors in acos due to * floating point imprecisions */ if(dot < -1.0) dot = -1.0; if(dot > 1.0) dot = 1.0; float angle = acos(dot); float a, b; float sin_angle = sin(angle); if(sin_angle == 0.0f) { // use linear interpolation to avoid div/zero a = 1.0f - t; b = t; } else { a = sin((1.0f - t) * angle) / sin_angle; b = sin(t * angle) / sin_angle; } float x = q1.x * a + q2.x * b; float y = q1.y * a + q2.y * b; float z = q1.z * a + q2.z * b; float w = q1.w * a + q2.w * b; return Quat(x, y, z, w); } inline Quat lerp(const Quat &a, const Quat &b, float t) { return slerp(a, b, t); } <commit_msg>Quat::calc_matrix was transposed<commit_after>/* gph-math - math library for graphics programs Copyright (C) 2016 John Tsiombikas <[email protected]> This program is free software. Feel free to use, modify, and/or redistribute it under the terms of the MIT/X11 license. See LICENSE for details. If you intend to redistribute parts of the code without the LICENSE file replace this paragraph with the full contents of the LICENSE file. */ inline Quat operator -(const Quat &q) { return Quat(-q.x, -q.y, -q.z, -q.w); } inline Quat operator +(const Quat &a, const Quat &b) { return Quat(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } inline Quat operator -(const Quat &a, const Quat &b) { return Quat(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } inline Quat operator *(const Quat &a, const Quat &b) { Vec3 a_im = Vec3(a.x, a.y, a.z); Vec3 b_im = Vec3(b.x, b.y, b.z); float w = a.w * b.w - dot(a_im, b_im); Vec3 im = a.w * b_im + b.w * a_im + cross(a_im, b_im); return Quat(im.x, im.y, im.z, w); } inline Quat &operator +=(Quat &a, const Quat &b) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; return a; } inline Quat &operator -=(Quat &a, const Quat &b) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; return a; } inline Quat &operator *=(Quat &a, const Quat &b) { Vec3 a_im = Vec3(a.x, a.y, a.z); Vec3 b_im = Vec3(b.x, b.y, b.z); float w = a.w * b.w - dot(a_im, b_im); Vec3 im = a.w * b_im + b.w * a_im + cross(a_im, b_im); a = Quat(im.x, im.y, im.z, w); return a; } inline float length(const Quat &q) { return (float)sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); } inline float length_sq(const Quat &q) { return q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w; } inline void Quat::normalize() { float len = length(*this); if(len != 0.0f) { x /= len; y /= len; z /= len; w /= len; } } inline Quat normalize(const Quat &q) { float len = length(q); if(len != 0.0f) { return Quat(q.x / len, q.y / len, q.z / len, q.w / len); } return q; } inline void Quat::conjugate() { x = -x; y = -y; z = -z; } inline Quat conjugate(const Quat &q) { return Quat(-q.x, -q.y, -q.z, q.w); } inline void Quat::invert() { Quat conj = gph::conjugate(*this); float len_sq = length_sq(conj); if(len_sq != 0.0) { x = conj.x / len_sq; y = conj.y / len_sq; z = conj.z / len_sq; w = conj.w / len_sq; } } inline Quat inverse(const Quat &q) { Quat conj = conjugate(q); float len_sq = length_sq(conj); if(len_sq != 0.0) { return Quat(conj.x / len_sq, conj.y / len_sq, conj.z / len_sq, conj.w / len_sq); } return q; } inline void Quat::set_rotation(const Vec3 &axis, float angle) { float half_angle = angle * 0.5f; w = cos(half_angle); float sin_ha = sin(half_angle); x = axis.x * sin_ha; y = axis.y * sin_ha; z = axis.z * sin_ha; } inline void Quat::rotate(const Vec3 &axis, float angle) { Quat q; float half_angle = angle * 0.5f; q.w = cos(half_angle); float sin_ha = sin(half_angle); q.x = axis.x * sin_ha; q.y = axis.y * sin_ha; q.z = axis.z * sin_ha; *this *= q; } inline void Quat::rotate(const Quat &rq) { *this = rq * *this * gph::conjugate(rq); } inline Mat4 Quat::calc_matrix() const { float xsq2 = 2.0 * x * x; float ysq2 = 2.0 * y * y; float zsq2 = 2.0 * z * z; float sx = 1.0 - ysq2 - zsq2; float sy = 1.0 - xsq2 - zsq2; float sz = 1.0 - xsq2 - ysq2; return Mat4( sx, 2.0 * x * y + 2.0 * w * z, 2.0 * z * x - 2.0 * w * y, 0, 2.0 * x * y - 2.0 * w * z, sy, 2.0 * y * z + 2.0 * w * x, 0, 2.0 * z * x + 2.0 * w * y, 2.0 * y * z - 2.0 * w * x, sz, 0, 0, 0, 0, 1); } inline Quat slerp(const Quat &quat1, const Quat &q2, float t) { Quat q1 = quat1; float dot = q1.w * q2.w + q1.x * q2.x + q1.y * q2.y + q1.z * q2.z; if(dot < 0.0) { /* make sure we interpolate across the shortest arc */ q1 = -quat1; dot = -dot; } /* clamp dot to [-1, 1] in order to avoid domain errors in acos due to * floating point imprecisions */ if(dot < -1.0) dot = -1.0; if(dot > 1.0) dot = 1.0; float angle = acos(dot); float a, b; float sin_angle = sin(angle); if(sin_angle == 0.0f) { // use linear interpolation to avoid div/zero a = 1.0f - t; b = t; } else { a = sin((1.0f - t) * angle) / sin_angle; b = sin(t * angle) / sin_angle; } float x = q1.x * a + q2.x * b; float y = q1.y * a + q2.y * b; float z = q1.z * a + q2.z * b; float w = q1.w * a + q2.w * b; return Quat(x, y, z, w); } inline Quat lerp(const Quat &a, const Quat &b, float t) { return slerp(a, b, t); } <|endoftext|>
<commit_before>// // testing a subd idea // #include <stdlib.h> #include <iostream> #include <cctype> // std::tolower #include <algorithm> #include <vector> // in project properties, add "../include" to the vc++ directories include path #include "geometric.h" #include "glwin.h" // minimal opengl for windows setup wrapper #include "misc_gl.h" #include "wingmesh.h" #include "minixml.h" void wmwire(const WingMesh &m) { glBegin(GL_LINES); for (auto e : m.edges) { glVertex3fv(m.verts[e.v]); glVertex3fv(m.verts[m.edges[e.next].v]); } glEnd(); } void wmdraw(const WingMesh &m) { gldraw(m.verts, m.GenerateTris()); } std::vector<std::string> split(std::string line, std::string delimeter=" ") { std::vector<std::string> tokens; size_t pos = 0; while ((pos = line.find(delimeter)) != std::string::npos) { auto token = line.substr(0, pos); line.erase(0, pos + delimeter.length()); if (token.length()) tokens.push_back(token); } if (line.length()) tokens.push_back(line); return tokens; } WingMesh WingMeshLoad(const char *filename) { WingMesh wm; std::ifstream filein(filename); if (!filein.is_open()) throw "unable to open file"; std::string line; while (std::getline(filein, line)) { auto tokens = split(line); if (!tokens.size()) continue; auto head = tokens.front(); tokens.erase(tokens.begin()); if (head == "v") { line.erase(0, 1); wm.verts.push_back(StringTo<float3>(line)*0.1f); continue; } if (head == "f") { std::vector<int> vids; for(auto &token:tokens) vids.push_back(StringTo<int>(split(token,"/")[0]) - 1); // ugg obj index from one instead of zero int base = wm.edges.size(); std::vector<float3> fverts; for (int i = 0; i < (int)vids.size(); i++) { int inext = (i + 1) % vids.size(); int iprev = (i + vids.size()-1) % vids.size(); wm.edges.push_back(WingMesh::HalfEdge(base + i, vids[i], -1, base + inext, base + iprev, wm.faces.size())); fverts.push_back(wm.verts[vids[i]]); } wm.faces.push_back(PolyPlane(fverts)); continue; } } wm.LinkMesh(); wm.InitBackLists(); return wm; } int main(int argc, char *argv[]) { std::cout << "Test...\n"; auto body = WingMeshLoad("EntireBody.obj"); auto body1 = WingMeshSubDiv(body); auto body2 = WingMeshSubDiv(body1); //auto box = WingMeshSubDiv(WingMeshSubDiv(WingMeshCube(0.5f))); GLWin glwin("Test CatmullClark"); glwin.keyboardfunc = [](int key, int, int) { switch (std::tolower(key)) { case ' ': break; case 27: // ESC case 'q': exit(0); break; default: std::cout << "unassigned key (" << (int)key << "): '" << key << "'\n"; break; } }; float3 mousevec_prev; float camdist = 2.0f; Pose camera({ 0,0,camdist }, { 0, 0, 0, 1 }); while (glwin.WindowUp()) { if (glwin.MouseState) // on mouse drag { camera.orientation = qmul(camera.orientation,qconj(VirtualTrackBall(float3(0, 0, 2), float3(0, 0, 0), mousevec_prev, glwin.MouseVector))); camera.position = qzdir(camera.orientation)*camdist; } mousevec_prev = glwin.MouseVector; glPushAttrib(GL_ALL_ATTRIB_BITS); // Set up the viewport glViewport(0, 0, glwin.res.x, glwin.res.y); glClearColor(0.1f, 0.1f, 0.15f, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluPerspective(glwin.ViewAngle, (double)glwin.aspect_ratio(), 0.01, 10); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(camera.inverse().matrix()); glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); glColor3f(0, 1, 1); glEnable(GL_CULL_FACE); //glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); wmwire(body ); glTranslatef(0.3f,0,0 ); wmwire(body1); glTranslatef( 0.3f,0,0); wmwire(body2); // Restore state glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); //should be currently in modelview mode glPopAttrib(); glwin.PrintString({ 0, 0 }, "Press ESC to quit."); glwin.SwapBuffers(); } std::cout << "\n"; return 0; } <commit_msg>added simple editing<commit_after>// // testing a subd idea // #include <stdlib.h> #include <iostream> #include <cctype> // std::tolower #include <algorithm> #include <vector> // in project properties, add "../include" to the vc++ directories include path #include "geometric.h" #include "glwin.h" // minimal opengl for windows setup wrapper #include "misc_gl.h" #include "wingmesh.h" #include "minixml.h" void wmwire(const WingMesh &m) { glBegin(GL_LINES); for (auto e : m.edges) { glVertex3fv(m.verts[e.v]); glVertex3fv(m.verts[m.edges[e.next].v]); } glEnd(); } void wmdraw(const WingMesh &m) { gldraw(m.verts, m.GenerateTris()); } std::vector<std::string> split(std::string line, std::string delimeter=" ") { std::vector<std::string> tokens; size_t pos = 0; while ((pos = line.find(delimeter)) != std::string::npos) { auto token = line.substr(0, pos); line.erase(0, pos + delimeter.length()); if (token.length()) tokens.push_back(token); } if (line.length()) tokens.push_back(line); return tokens; } WingMesh WingMeshLoad(const char *filename) { WingMesh wm; std::ifstream filein(filename); if (!filein.is_open()) throw "unable to open file"; std::string line; while (std::getline(filein, line)) { auto tokens = split(line); if (!tokens.size()) continue; auto head = tokens.front(); tokens.erase(tokens.begin()); if (head == "v") { line.erase(0, 1); wm.verts.push_back(StringTo<float3>(line)*0.1f); continue; } if (head == "f") { std::vector<int> vids; for(auto &token:tokens) vids.push_back(StringTo<int>(split(token,"/")[0]) - 1); // ugg obj index from one instead of zero int base = wm.edges.size(); std::vector<float3> fverts; for (int i = 0; i < (int)vids.size(); i++) { int inext = (i + 1) % vids.size(); int iprev = (i + vids.size()-1) % vids.size(); wm.edges.push_back(WingMesh::HalfEdge(base + i, vids[i], -1, base + inext, base + iprev, wm.faces.size())); fverts.push_back(wm.verts[vids[i]]); } wm.faces.push_back(PolyPlane(fverts)); continue; } } wm.LinkMesh(); wm.InitBackLists(); return wm; } float3 *HitCheckPoint(std::vector<float3> &points,const float3 &v0,float3 v1,float box_radius) // typically used for vertex selection { float3 *point_hit = NULL; float w = -box_radius; std::vector<float4> planes = { { 1, 0, 0, w },{ 0, 1, 0, w },{ 0, 0, 1, w },{ -1, 0, 0, w },{ 0, -1, 0, w },{ 0, 0, -1, w } }; for (float3 &p : points) { if (auto h = ConvexHitCheck(planes, Pose(p, { 0, 0, 0, 1 }), v0, v1)) { point_hit = &p; v1 = h.impact; } } return point_hit; } int main(int argc, char *argv[]) { std::cout << "Test...\n"; auto body = WingMeshLoad("EntireBody.obj"); //auto box = WingMeshSubDiv(WingMeshSubDiv(WingMeshCube(0.5f))); GLWin glwin("Test CatmullClark"); glwin.keyboardfunc = [](int key, int, int) { switch (std::tolower(key)) { case ' ': break; case 27: // ESC case 'q': exit(0); break; default: std::cout << "unassigned key (" << (int)key << "): '" << key << "'\n"; break; } }; float3 mousevec_prev; float camdist = 2.0f; Pose camera({ 0,0,camdist }, { 0, 0, 0, 1 }); float boxr = 0.002f; float3 *selected = NULL; while (glwin.WindowUp()) { if (!glwin.MouseState) { selected = HitCheckPoint(body.verts, camera.position, camera*(glwin.MouseVector*100.0f), boxr); } else if (selected) { *selected += (qrot(camera.orientation, glwin.MouseVector) - qrot(camera.orientation, glwin.OldMouseVector)) * length(*selected - camera.position); *selected = camera.position + (*selected - camera.position) * powf(1.1f, (float)glwin.mousewheel); glwin.mousewheel = 0; } else // on mouse drag { camera.orientation = qmul(camera.orientation,qconj(VirtualTrackBall(float3(0, 0, 2), float3(0, 0, 0), mousevec_prev, glwin.MouseVector))); camera.position = qzdir(camera.orientation)*camdist; } mousevec_prev = glwin.MouseVector; auto body1 = WingMeshSubDiv(body); auto body2 = WingMeshSubDiv(body1); glPushAttrib(GL_ALL_ATTRIB_BITS); // Set up the viewport glViewport(0, 0, glwin.res.x, glwin.res.y); glClearColor(0.1f, 0.1f, 0.15f, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluPerspective(glwin.ViewAngle, (double)glwin.aspect_ratio(), 0.01, 10); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glMultMatrixf(camera.inverse().matrix()); glEnable(GL_DEPTH_TEST); glDisable(GL_BLEND); for (auto &p : body.verts) glcolorbox(float3(&p==selected?2:1)*boxr, Pose(p, { 0,0,0,1 })); glColor3f(0, 1, 1); glEnable(GL_CULL_FACE); //glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); wmwire(body ); glTranslatef(0.3f,0,0 ); wmwire(body1); glTranslatef( 0.3f,0,0); wmwire(body2); // Restore state glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); //should be currently in modelview mode glPopAttrib(); glwin.PrintString({ 0, 0 }, "Press ESC to quit."); glwin.SwapBuffers(); } std::cout << "\n"; return 0; } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <globals.h> #include <prototypes.h> #include <pthread.h> #include <iostream.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> // DT: 3/97 needed for time function #include "../rtstuff/heap/heap.h" #include "../rtstuff/rtdefs.h" #include "../H/dbug.h" //#define TBUG //#define ALLBUG double baseTime; long elapsed; IBusClass checkClass(BusSlot *slot) { if (slot == NULL) return UNKNOWN; if ((slot->auxin_count > 0) && (slot->auxout_count > 0)) return AUX_TO_AUX; if ((slot->auxout_count > 0) && (slot->out_count > 0)) return TO_AUX_AND_OUT; if (slot->auxout_count > 0) return TO_AUX; if (slot->out_count > 0) return TO_OUT; return UNKNOWN; } extern "C" { void *inTraverse(void *arg) { short rtInst; short playEm; int i,j,chunksamps; int heapSize,rtQSize,allQSize; int offset,endsamp; int keepGoing; int dummy; short bus_q_offset; Instrument *Iptr; unsigned long bufEndSamp; unsigned long chunkStart; unsigned long heapChunkStart; struct timeval tv; struct timezone tz; double sec,usec; Bool aux_pb_done,frame_done; short bus,bus_count,play_bus,busq,endbus,t_bus,t_count; IBusClass bus_class,qStatus,t_class; BusType bus_type; // cout << "ENTERING inTraverse() FUNCTION *****\n"; // Wait for the ok to go ahead if (!audio_config) { cout << "inTraverse(): waiting for audio_config . . . "; } while (!audio_config) { // Do nothing } if (audio_config && rtInteractive) { cout << "audio set.\n\n"; } gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; // Initialize everything bufStartSamp = 0; // current end sample for buffer bufEndSamp = RTBUFSAMPS; chunkStart = 0; heapSize = 0; chunkStart = 0; elapsed = 0; rtInst = 0; playEm = 0; // printf("ENTERING inTraverse() FUNCTION\n"); // NOTE: audioin, aux and output buffers are zero'd during allocation // read in an input buffer (if audio input is active) if (audio_on) { rtgetsamps(); rtsendzeros(0); // send a buffer of zeros to audio device } if (rtsetparams_called) // otherwise, disk-based only playEm = 1; while(playEm) { // the big loop ========================================== pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); if (heapSize > 0) { heapChunkStart = rtHeap.getTop(); } pthread_mutex_unlock(&heapLock); // Pop elements off rtHeap and insert into rtQueue ---------------------- while ((heapChunkStart < bufEndSamp) && (heapSize > 0)) { rtInst = 1; pthread_mutex_lock(&heapLock); Iptr = rtHeap.deleteMin(); // get next instrument off heap pthread_mutex_unlock(&heapLock); if (!Iptr) break; #ifdef TBUG if ((Bus_Configed == NO) && (print_is_on)) { printf("WARNING: no bus_configs defined, using default\n"); } #endif // DJT Now we push things onto different queues bus_class = checkClass(Iptr->bus_config); switch (bus_class) { case TO_AUX: bus_count = Iptr->bus_config->auxout_count; bus_q_offset = 0; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_AUX[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case AUX_TO_AUX: bus_count = Iptr->bus_config->auxout_count; bus_q_offset = MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on AUX_TO_AUX[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case TO_OUT: bus_count = Iptr->bus_config->out_count; bus_q_offset = MAXBUS*2; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->out[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_OUT[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case TO_AUX_AND_OUT: bus_count = Iptr->bus_config->out_count; bus_q_offset = MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->out[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_OUT2[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } bus_count = Iptr->bus_config->auxout_count; bus_q_offset = 2*MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_AUX2[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); if (heapSize > 0) heapChunkStart = rtHeap.getTop(); pthread_mutex_unlock(&heapLock); } qStatus = TO_AUX; play_bus = 0; aux_pb_done = NO; allQSize = 0; // rtQueue[] playback shuffling ---------------------------------------- while (!aux_pb_done) { switch (qStatus) { case TO_AUX: bus_q_offset = 0; bus_type = BUS_AUX_OUT; bus = ToAuxPlayList[play_bus++]; break; case AUX_TO_AUX: bus_q_offset = MAXBUS; bus = AuxToAuxPlayList[play_bus++]; bus_type = BUS_AUX_OUT; break; case TO_OUT: bus_q_offset = MAXBUS*2; bus = ToOutPlayList[play_bus++]; bus_type = BUS_OUT; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } if (bus != -1) busq = bus+bus_q_offset; else busq = bus; if (bus == -1) { switch (qStatus) { case TO_AUX: qStatus = AUX_TO_AUX; play_bus = 0; break; case AUX_TO_AUX: qStatus = TO_OUT; play_bus = 0; break; case TO_OUT: #ifdef TBUG cout << "aux_pb_done\n"; #endif aux_pb_done = YES; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } } #ifdef TBUG cout << "bus: " << bus << endl; cout << "busq: " << busq << endl; #endif if (busq != -1) { rtQSize = rtQueue[busq].getSize(); if (rtQSize > 0) { chunkStart = rtQueue[busq].nextChunk(); } } // Play elements on queue (insert back in if needed) - - - - - - - - while ((rtQSize > 0) && (chunkStart < bufEndSamp) && (bus != -1)) { #ifdef ALLBUG cout << "Begin iteration==========\n"; cout << "Q-chunkStart: " << chunkStart << endl; cout << "bufEndSamp: " << bufEndSamp << endl; cout << "RTBUFSAMPS: " << RTBUFSAMPS << endl; #endif Iptr = rtQueue[busq].pop(); // get next instrument off queue endsamp = Iptr->getendsamp(); // difference in sample start (countdown) offset = chunkStart - bufStartSamp; if (offset < 0) { // BGG: added this trap for robustness cout << "WARNING: the scheduler is behind the queue!" << endl; offset = 0; } Iptr->set_output_offset(offset); if (endsamp < bufEndSamp) { // compute # of samples to write chunksamps = endsamp-chunkStart; } else { chunksamps = bufEndSamp-chunkStart; } Iptr->setchunk(chunksamps); // set "chunksamps" #ifdef TBUG cout << "Iptr->exec(" << bus_type << "," << bus << ")\n"; #endif Iptr->exec(bus_type, bus); // write the samples * * * * * * * * * #ifdef TBUG cout << "endbus " << endbus << endl; #endif // ReQueue or delete - - - - - - - - - - - - - - - - - - - if (endsamp > bufEndSamp) { #ifdef ALLBUG cout << "inTraverse(): re queueing instrument\n"; #endif rtQueue[busq].push(Iptr,chunkStart+chunksamps); // put back onto queue } else { t_class = checkClass(Iptr->bus_config); switch (t_class) { case TO_AUX: t_count = Iptr->bus_config->auxout_count; endbus = Iptr->bus_config->auxout[t_count-1]; break; case AUX_TO_AUX: t_count = Iptr->bus_config->auxout_count; endbus = Iptr->bus_config->auxout[t_count-1]; break; case TO_AUX_AND_OUT: if (qStatus == TO_OUT) { t_count = Iptr->bus_config->out_count; endbus = Iptr->bus_config->out[t_count-1]; } else endbus = 1000; /* can never equal this */ break; case TO_OUT: t_count = Iptr->bus_config->out_count; endbus = Iptr->bus_config->out[t_count-1]; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } if ((qStatus == t_class) && (bus == endbus)) { delete Iptr; } } // DJT: not sure this check before new chunkStart is necessary rtQSize = rtQueue[busq].getSize(); if (rtQSize) { chunkStart = rtQueue[busq].nextChunk(); allQSize += rtQSize; } #ifdef TBUG cout << "rtQSize: " << rtQSize << endl; cout << "chunkStart: " << chunkStart << endl; cout << "chunksamps: " << chunksamps << endl; cout << "Iteration done==========\n"; #endif } } // end aux_pb_done ======================================== // Write buf to audio device ------------------------------------------- #ifdef ALLBUG cout << "Writing samples----------\n"; cout << "Q-chunkStart: " << chunkStart << endl; cout << "bufEndSamp: " << bufEndSamp << endl; #endif rtsendsamps(); // zero the buffers clear_aux_buffers(); clear_output_buffers(); // read in an input buffer (if audio input is active) if (audio_on) { // cout << "Reading data from audio port\n"; rtgetsamps(); } gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; elapsed += RTBUFSAMPS; bufStartSamp += RTBUFSAMPS; bufEndSamp += RTBUFSAMPS; if (!rtInteractive) { // Ending condition if ((heapSize == 0) && (allQSize == 0)) { #ifdef TBUG cout << "heapSize: " << heapSize << endl; cout << "rtQSize: " << rtQSize << endl; cout << "PLAYEM = 0\n"; cout << "The end\n\n"; #endif playEm = 0; } } } // end playEm ========================================================= if (rtsetparams_called) { if (play_audio) { // Play zero'd buffers to avoid clicks int count = NCHANS * 4; // DJT: clicks on my box with 2 for (j = 0; j < count; j++) rtsendzeros(0); } close_audio_ports(); rtreportstats(); rtcloseout(); } cout << "\n"; // cout << "EXITING inTraverse() FUNCTION *****\n"; // exit(1); } } /* extern "C" */ <commit_msg>Fixes for timing / real time perf<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ #include <globals.h> #include <prototypes.h> #include <pthread.h> #include <iostream.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> // DT: 3/97 needed for time function #include "../rtstuff/heap/heap.h" #include "../rtstuff/rtdefs.h" #include "../H/dbug.h" // #define TBUG // #define ALLBUG double baseTime; long elapsed; IBusClass checkClass(BusSlot *slot) { if (slot == NULL) return UNKNOWN; if ((slot->auxin_count > 0) && (slot->auxout_count > 0)) return AUX_TO_AUX; if ((slot->auxout_count > 0) && (slot->out_count > 0)) return TO_AUX_AND_OUT; if (slot->auxout_count > 0) return TO_AUX; if (slot->out_count > 0) return TO_OUT; return UNKNOWN; } extern "C" { void *inTraverse(void *arg) { short rtInst; short playEm; int i,j,chunksamps; int heapSize,rtQSize,allQSize; int offset,endsamp; int keepGoing; int dummy; short bus_q_offset; Instrument *Iptr; unsigned long bufEndSamp; unsigned long chunkStart; unsigned long heapChunkStart; struct timeval tv; struct timezone tz; double sec,usec; Bool aux_pb_done,frame_done; short bus,bus_count,play_bus,busq,endbus,t_bus,t_count; IBusClass bus_class,qStatus,t_class; BusType bus_type; #ifdef TBUG cout << "ENTERING inTraverse() FUNCTION *****\n"; #endif // Try and be tight with time gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; // Wait for the ok to go ahead if (!audio_config) { cout << "inTraverse(): waiting for audio_config . . . "; } while (!audio_config) { // Do nothing } if (audio_config && rtInteractive) { cout << "audio set.\n\n"; } // Initialize everything bufStartSamp = 0; // current end sample for buffer bufEndSamp = RTBUFSAMPS; chunkStart = 0; heapSize = 0; chunkStart = 0; elapsed = 0; rtInst = 0; playEm = 0; // Try and be tight with time gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; // printf("ENTERING inTraverse() FUNCTION\n"); // NOTE: audioin, aux and output buffers are zero'd during allocation // read in an input buffer (if audio input is active) if (audio_on) { rtgetsamps(); rtsendzeros(0); // send a buffer of zeros to audio device } if (rtsetparams_called) // otherwise, disk-based only playEm = 1; // Try and be tight with time gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; while(playEm) { // the big loop ========================================== #ifdef TBUG printf("Entering big loop ...\n"); #endif pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); if (heapSize > 0) { heapChunkStart = rtHeap.getTop(); } pthread_mutex_unlock(&heapLock); // Added 6/17/00 DJT: for real time perf // need to wait for something to be on the heap if ((heapSize == 0) && (rtQSize == 0)) { while (heapSize == 0) { pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; if (heapSize > 0) { heapChunkStart = rtHeap.getTop(); } pthread_mutex_unlock(&heapLock); } } #ifdef TBUG cout << "heapSize = " << heapSize << endl; cout << "heapChunkStart = " << heapChunkStart << endl; cout << "Bus_Configed = " << Bus_Configed << endl; #endif // Pop elements off rtHeap and insert into rtQueue +++++++++++++++++++++ while ((heapChunkStart < bufEndSamp) && (heapSize > 0)) { rtInst = 1; pthread_mutex_lock(&heapLock); Iptr = rtHeap.deleteMin(); // get next instrument off heap pthread_mutex_unlock(&heapLock); if (!Iptr) break; #ifdef TBUG if ((Bus_Configed == NO) && (print_is_on)) { printf("WARNING: no bus_configs defined, using default\n"); } #endif // DJT Now we push things onto different queues bus_class = checkClass(Iptr->bus_config); switch (bus_class) { case TO_AUX: bus_count = Iptr->bus_config->auxout_count; bus_q_offset = 0; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_AUX[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case AUX_TO_AUX: bus_count = Iptr->bus_config->auxout_count; bus_q_offset = MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on AUX_TO_AUX[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case TO_OUT: bus_count = Iptr->bus_config->out_count; bus_q_offset = MAXBUS*2; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->out[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_OUT[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; case TO_AUX_AND_OUT: bus_count = Iptr->bus_config->out_count; bus_q_offset = MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->out[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_OUT2[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } bus_count = Iptr->bus_config->auxout_count; bus_q_offset = 2*MAXBUS; for(i=0;i<bus_count;i++) { bus = Iptr->bus_config->auxout[i]; busq = bus+bus_q_offset; #ifdef TBUG cout << "Pushing on TO_AUX2[" << busq << "] rtQueue\n"; #endif rtQueue[busq].push(Iptr,heapChunkStart); } break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } pthread_mutex_lock(&heapLock); heapSize = rtHeap.getSize(); if (heapSize > 0) heapChunkStart = rtHeap.getTop(); pthread_mutex_unlock(&heapLock); } // End rtHeap popping and rtQueue insertion ---------------------------- qStatus = TO_AUX; play_bus = 0; aux_pb_done = NO; allQSize = 0; // rtQueue[] playback shuffling ++++++++++++++++++++++++++++++++++++++++ while (!aux_pb_done) { switch (qStatus) { case TO_AUX: bus_q_offset = 0; bus_type = BUS_AUX_OUT; bus = ToAuxPlayList[play_bus++]; break; case AUX_TO_AUX: bus_q_offset = MAXBUS; bus = AuxToAuxPlayList[play_bus++]; bus_type = BUS_AUX_OUT; break; case TO_OUT: bus_q_offset = MAXBUS*2; bus = ToOutPlayList[play_bus++]; bus_type = BUS_OUT; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } if (bus != -1) busq = bus+bus_q_offset; else busq = bus; if (bus == -1) { switch (qStatus) { case TO_AUX: qStatus = AUX_TO_AUX; play_bus = 0; break; case AUX_TO_AUX: qStatus = TO_OUT; play_bus = 0; break; case TO_OUT: #ifdef TBUG cout << "aux_pb_done\n"; #endif aux_pb_done = YES; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } } #ifdef TBUG cout << "bus: " << bus << endl; cout << "busq: " << busq << endl; #endif if (busq != -1) { rtQSize = rtQueue[busq].getSize(); if (rtQSize > 0) { chunkStart = rtQueue[busq].nextChunk(); } } // Play elements on queue (insert back in if needed) - - - - - - - - while ((rtQSize > 0) && (chunkStart < bufEndSamp) && (bus != -1)) { #ifdef ALLBUG cout << "Begin iteration==========\n"; cout << "Q-chunkStart: " << chunkStart << endl; cout << "bufEndSamp: " << bufEndSamp << endl; cout << "RTBUFSAMPS: " << RTBUFSAMPS << endl; #endif Iptr = rtQueue[busq].pop(); // get next instrument off queue endsamp = Iptr->getendsamp(); // difference in sample start (countdown) offset = chunkStart - bufStartSamp; if (offset < 0) { // BGG: added this trap for robustness cout << "WARNING: the scheduler is behind the queue!" << endl; offset = 0; } Iptr->set_output_offset(offset); if (endsamp < bufEndSamp) { // compute # of samples to write chunksamps = endsamp-chunkStart; } else { chunksamps = bufEndSamp-chunkStart; } Iptr->setchunk(chunksamps); // set "chunksamps" #ifdef TBUG cout << "Iptr->exec(" << bus_type << "," << bus << ")\n"; #endif Iptr->exec(bus_type, bus); // write the samples * * * * * * * * * #ifdef TBUG cout << "endbus " << endbus << endl; #endif // ReQueue or delete - - - - - - - - - - - - - - - - - - - if (endsamp > bufEndSamp) { #ifdef ALLBUG cout << "inTraverse(): re queueing instrument\n"; #endif rtQueue[busq].push(Iptr,chunkStart+chunksamps); // put back onto queue } else { t_class = checkClass(Iptr->bus_config); switch (t_class) { case TO_AUX: t_count = Iptr->bus_config->auxout_count; endbus = Iptr->bus_config->auxout[t_count-1]; break; case AUX_TO_AUX: t_count = Iptr->bus_config->auxout_count; endbus = Iptr->bus_config->auxout[t_count-1]; break; case TO_AUX_AND_OUT: if (qStatus == TO_OUT) { t_count = Iptr->bus_config->out_count; endbus = Iptr->bus_config->out[t_count-1]; } else endbus = 1000; /* can never equal this */ break; case TO_OUT: t_count = Iptr->bus_config->out_count; endbus = Iptr->bus_config->out[t_count-1]; break; default: cout << "ERROR (intraverse): unknown bus_class\n"; break; } if ((qStatus == t_class) && (bus == endbus)) { delete Iptr; } } // DJT: not sure this check before new chunkStart is necessary rtQSize = rtQueue[busq].getSize(); if (rtQSize) { chunkStart = rtQueue[busq].nextChunk(); allQSize += rtQSize; } #ifdef TBUG cout << "rtQSize: " << rtQSize << endl; cout << "chunkStart: " << chunkStart << endl; cout << "chunksamps: " << chunksamps << endl; cout << "Iteration done==========\n"; #endif } } // end aux_pb_done ======================================== // Write buf to audio device ------------------------------------------- #ifdef ALLBUG cout << "Writing samples----------\n"; cout << "Q-chunkStart: " << chunkStart << endl; cout << "bufEndSamp: " << bufEndSamp << endl; #endif rtsendsamps(); gettimeofday(&tv, &tz); sec = (double)tv.tv_sec; usec = (double)tv.tv_usec; baseTime = (sec * 1e6) + usec; elapsed += RTBUFSAMPS; bufStartSamp += RTBUFSAMPS; bufEndSamp += RTBUFSAMPS; // zero the buffers clear_aux_buffers(); clear_output_buffers(); // read in an input buffer (if audio input is active) if (audio_on) { // cout << "Reading data from audio port\n"; rtgetsamps(); } if (!rtInteractive) { // Ending condition if ((heapSize == 0) && (allQSize == 0)) { #ifdef TBUG cout << "heapSize: " << heapSize << endl; cout << "rtQSize: " << rtQSize << endl; cout << "PLAYEM = 0\n"; cout << "The end\n\n"; #endif playEm = 0; } } } // end playEm ========================================================= if (rtsetparams_called) { if (play_audio) { // Play zero'd buffers to avoid clicks int count = NCHANS * 4; // DJT: clicks on my box with 2 for (j = 0; j < count; j++) rtsendzeros(0); } close_audio_ports(); rtreportstats(); rtcloseout(); } cout << "\n"; #ifdef TBUG cout << "EXITING inTraverse() FUNCTION *****\n"; exit(1); #endif } } /* extern "C" */ <|endoftext|>
<commit_before>#include "emitterutils.h" #include "exp.h" #include "indentation.h" #include "exceptions.h" #include "stringsource.h" #include <sstream> #include <iomanip> namespace YAML { namespace Utils { namespace { bool IsPrintable(char ch) { return (0x20 <= ch && ch <= 0x7E); } bool IsValidPlainScalar(const std::string& str, bool inFlow) { // first check the start const RegEx& start = (inFlow ? Exp::PlainScalarInFlow : Exp::PlainScalar); if(!start.Matches(str)) return false; // and check the end for plain whitespace (which can't be faithfully kept in a plain scalar) if(!str.empty() && *str.rbegin() == ' ') return false; // then check until something is disallowed const RegEx& disallowed = (inFlow ? Exp::EndScalarInFlow : Exp::EndScalar) || (Exp::BlankOrBreak + Exp::Comment) || (!Exp::Printable) || Exp::Break || Exp::Tab; StringCharSource buffer(str.c_str(), str.size()); while(buffer) { if(disallowed.Matches(buffer)) return false; ++buffer; } return true; } unsigned ToUnsigned(char ch) { return static_cast<unsigned int>(static_cast<unsigned char>(ch)); } unsigned AdvanceAndGetNextChar(std::string::const_iterator& it, std::string::const_iterator end) { std::string::const_iterator jt = it; ++jt; if(jt == end) return 0; ++it; return ToUnsigned(*it); } std::string WriteUnicode(unsigned value) { std::stringstream str; // TODO: for the common escaped characters, give their usual symbol if(value <= 0xFF) str << "\\x" << std::hex << std::setfill('0') << std::setw(2) << value; else if(value <= 0xFFFF) str << "\\u" << std::hex << std::setfill('0') << std::setw(4) << value; else str << "\\U" << std::hex << std::setfill('0') << std::setw(8) << value; return str.str(); } std::string WriteSingleByte(unsigned ch) { return WriteUnicode(ch); } std::string WriteTwoBytes(unsigned ch, unsigned ch1) { // Note: if no second byte is provided (signalled by ch1 == 0) // then we just write the first one as a single byte. // Should we throw an error instead? Or write something else? // (The same question goes for the other WriteNBytes functions) if(ch1 == 0) return WriteSingleByte(ch); unsigned value = ((ch - 0xC0) << 6) + (ch1 - 0x80); return WriteUnicode(value); } std::string WriteThreeBytes(unsigned ch, unsigned ch1, unsigned ch2) { if(ch1 == 0) return WriteSingleByte(ch); if(ch2 == 0) return WriteSingleByte(ch) + WriteSingleByte(ch1); unsigned value = ((ch - 0xE0) << 12) + ((ch1 - 0x80) << 6) + (ch2 - 0x80); return WriteUnicode(value); } std::string WriteFourBytes(unsigned ch, unsigned ch1, unsigned ch2, unsigned ch3) { if(ch1 == 0) return WriteSingleByte(ch); if(ch2 == 0) return WriteSingleByte(ch) + WriteSingleByte(ch1); if(ch3 == 0) return WriteSingleByte(ch) + WriteSingleByte(ch1) + WriteSingleByte(ch2); unsigned value = ((ch - 0xF0) << 18) + ((ch1 - 0x80) << 12) + ((ch2 - 0x80) << 6) + (ch3 - 0x80); return WriteUnicode(value); } // WriteNonPrintable // . Writes the next UTF-8 code point to the stream std::string::const_iterator WriteNonPrintable(ostream& out, std::string::const_iterator start, std::string::const_iterator end) { std::string::const_iterator it = start; unsigned ch = ToUnsigned(*it); if(ch <= 0xC1) { // this may include invalid first characters (0x80 - 0xBF) // or "overlong" UTF-8 (0xC0 - 0xC1) // We just copy them as bytes // TODO: should we do something else? throw an error? out << WriteSingleByte(ch); return start; } else if(ch <= 0xDF) { unsigned ch1 = AdvanceAndGetNextChar(it, end); out << WriteTwoBytes(ch, ch1); return it; } else if(ch <= 0xEF) { unsigned ch1 = AdvanceAndGetNextChar(it, end); unsigned ch2 = AdvanceAndGetNextChar(it, end); out << WriteThreeBytes(ch, ch1, ch2); return it; } else { unsigned ch1 = AdvanceAndGetNextChar(it, end); unsigned ch2 = AdvanceAndGetNextChar(it, end); unsigned ch3 = AdvanceAndGetNextChar(it, end); out << WriteFourBytes(ch, ch1, ch2, ch3); return it; } return start; } } bool WriteString(ostream& out, const std::string& str, bool inFlow) { if(IsValidPlainScalar(str, inFlow)) { out << str; return true; } else return WriteDoubleQuotedString(out, str); } bool WriteSingleQuotedString(ostream& out, const std::string& str) { out << "'"; for(std::size_t i=0;i<str.size();i++) { char ch = str[i]; if(!IsPrintable(ch)) return false; if(ch == '\'') out << "''"; else out << ch; } out << "'"; return true; } bool WriteDoubleQuotedString(ostream& out, const std::string& str) { out << "\""; for(std::string::const_iterator it=str.begin();it!=str.end();++it) { char ch = *it; if(IsPrintable(ch)) { if(ch == '\"') out << "\\\""; else if(ch == '\\') out << "\\\\"; else out << ch; } else { it = WriteNonPrintable(out, it, str.end()); } } out << "\""; return true; } bool WriteLiteralString(ostream& out, const std::string& str, int indent) { out << "|\n"; out << IndentTo(indent); for(std::size_t i=0;i<str.size();i++) { if(str[i] == '\n') out << "\n" << IndentTo(indent); else out << str[i]; } return true; } bool WriteComment(ostream& out, const std::string& str, int postCommentIndent) { unsigned curIndent = out.col(); out << "#" << Indentation(postCommentIndent); for(std::size_t i=0;i<str.size();i++) { if(str[i] == '\n') out << "\n" << IndentTo(curIndent) << "#" << Indentation(postCommentIndent); else out << str[i]; } return true; } bool WriteAlias(ostream& out, const std::string& str) { out << "*"; for(std::size_t i=0;i<str.size();i++) { if(!IsPrintable(str[i]) || str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r') return false; out << str[i]; } return true; } bool WriteAnchor(ostream& out, const std::string& str) { out << "&"; for(std::size_t i=0;i<str.size();i++) { if(!IsPrintable(str[i]) || str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r') return false; out << str[i]; } return true; } } } <commit_msg>Refactored the UTF-8 emitting<commit_after>#include "emitterutils.h" #include "exp.h" #include "indentation.h" #include "exceptions.h" #include "stringsource.h" #include <sstream> #include <iomanip> #include <cassert> namespace YAML { namespace Utils { namespace { bool IsPrintable(char ch) { return (0x20 <= ch && ch <= 0x7E); } bool IsValidPlainScalar(const std::string& str, bool inFlow) { // first check the start const RegEx& start = (inFlow ? Exp::PlainScalarInFlow : Exp::PlainScalar); if(!start.Matches(str)) return false; // and check the end for plain whitespace (which can't be faithfully kept in a plain scalar) if(!str.empty() && *str.rbegin() == ' ') return false; // then check until something is disallowed const RegEx& disallowed = (inFlow ? Exp::EndScalarInFlow : Exp::EndScalar) || (Exp::BlankOrBreak + Exp::Comment) || (!Exp::Printable) || Exp::Break || Exp::Tab; StringCharSource buffer(str.c_str(), str.size()); while(buffer) { if(disallowed.Matches(buffer)) return false; ++buffer; } return true; } typedef unsigned char byte; byte ToByte(char ch) { return static_cast<byte>(ch); } typedef std::string::const_iterator StrIter; std::string WriteUnicode(unsigned value) { std::stringstream str; // TODO: for the common escaped characters, give their usual symbol if(value <= 0xFF) str << "\\x" << std::hex << std::setfill('0') << std::setw(2) << value; else if(value <= 0xFFFF) str << "\\u" << std::hex << std::setfill('0') << std::setw(4) << value; else str << "\\U" << std::hex << std::setfill('0') << std::setw(8) << value; return str.str(); } // GetBytesToRead // . Returns the length of the UTF-8 sequence starting with 'signal' int GetBytesToRead(byte signal) { if(signal <= 0x7F) // ASCII return 1; else if(signal <= 0xBF) // invalid first characters return 0; else if(signal <= 0xDF) // Note: this allows "overlong" UTF8 (0xC0 - 0xC1) to pass unscathed. OK? return 2; else if(signal <= 0xEF) return 3; else return 4; } // ReadBytes // . Reads the next 'bytesToRead', if we can. // . Returns zero if we fail, otherwise fills the byte buffer with // the data and returns the number of bytes read. int ReadBytes(byte bytes[4], StrIter start, StrIter end, int bytesToRead) { for(int i=0;i<bytesToRead;i++) { if(start == end) return 0; bytes[i] = ToByte(*start); ++start; } return bytesToRead; } // IsValidUTF8 // . Assumes bytes[0] is a valid signal byte with the right size passed bool IsValidUTF8(byte bytes[4], int size) { for(int i=1;i<size;i++) if(bytes[i] & 0x80 != 0x80) return false; return true; } byte UTF8SignalPrefix(int size) { switch(size) { case 1: return 0; case 2: return 0xC0; case 3: return 0xE0; case 4: return 0xF0; } assert(false); return 0; } unsigned UTF8ToUnicode(byte bytes[4], int size) { unsigned value = bytes[0] - UTF8SignalPrefix(size); for(int i=1;i<size;i++) value = (value << 6) + (bytes[i] - 0x80); return value; } // ReadUTF8 // . Returns the Unicode code point starting at 'start', // and sets 'bytesRead' to the length of the UTF-8 Sequence // . If it's invalid UTF8, we set 'bytesRead' to zero. unsigned ReadUTF8(StrIter start, StrIter end, int& bytesRead) { int bytesToRead = GetBytesToRead(ToByte(*start)); if(!bytesToRead) { bytesRead = 0; return 0; } byte bytes[4]; bytesRead = ReadBytes(bytes, start, end, bytesToRead); if(!bytesRead) return 0; if(!IsValidUTF8(bytes, bytesRead)) { bytesRead = 0; return 0; } return UTF8ToUnicode(bytes, bytesRead); } // WriteNonPrintable // . Writes the next UTF-8 code point to the stream int WriteNonPrintable(ostream& out, StrIter start, StrIter end) { int bytesRead = 0; unsigned value = ReadUTF8(start, end, bytesRead); if(bytesRead == 0) { // TODO: is it ok to just write the replacement character here, // or should we instead write the invalid byte (as \xNN)? out << WriteUnicode(0xFFFD); return 1; } out << WriteUnicode(value); return bytesRead; } } bool WriteString(ostream& out, const std::string& str, bool inFlow) { if(IsValidPlainScalar(str, inFlow)) { out << str; return true; } else return WriteDoubleQuotedString(out, str); } bool WriteSingleQuotedString(ostream& out, const std::string& str) { out << "'"; for(std::size_t i=0;i<str.size();i++) { char ch = str[i]; if(!IsPrintable(ch)) return false; if(ch == '\'') out << "''"; else out << ch; } out << "'"; return true; } bool WriteDoubleQuotedString(ostream& out, const std::string& str) { out << "\""; for(StrIter it=str.begin();it!=str.end();++it) { char ch = *it; if(IsPrintable(ch)) { if(ch == '\"') out << "\\\""; else if(ch == '\\') out << "\\\\"; else out << ch; } else { int bytesRead = WriteNonPrintable(out, it, str.end()); if(bytesRead >= 1) it += (bytesRead - 1); } } out << "\""; return true; } bool WriteLiteralString(ostream& out, const std::string& str, int indent) { out << "|\n"; out << IndentTo(indent); for(std::size_t i=0;i<str.size();i++) { if(str[i] == '\n') out << "\n" << IndentTo(indent); else out << str[i]; } return true; } bool WriteComment(ostream& out, const std::string& str, int postCommentIndent) { unsigned curIndent = out.col(); out << "#" << Indentation(postCommentIndent); for(std::size_t i=0;i<str.size();i++) { if(str[i] == '\n') out << "\n" << IndentTo(curIndent) << "#" << Indentation(postCommentIndent); else out << str[i]; } return true; } bool WriteAlias(ostream& out, const std::string& str) { out << "*"; for(std::size_t i=0;i<str.size();i++) { if(!IsPrintable(str[i]) || str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r') return false; out << str[i]; } return true; } bool WriteAnchor(ostream& out, const std::string& str) { out << "&"; for(std::size_t i=0;i<str.size();i++) { if(!IsPrintable(str[i]) || str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r') return false; out << str[i]; } return true; } } } <|endoftext|>
<commit_before> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkUtils.h" #include "SkOnce.h" #if 0 #define assign_16_longs(dst, value) \ do { \ (dst)[0] = value; (dst)[1] = value; \ (dst)[2] = value; (dst)[3] = value; \ (dst)[4] = value; (dst)[5] = value; \ (dst)[6] = value; (dst)[7] = value; \ (dst)[8] = value; (dst)[9] = value; \ (dst)[10] = value; (dst)[11] = value; \ (dst)[12] = value; (dst)[13] = value; \ (dst)[14] = value; (dst)[15] = value; \ } while (0) #else #define assign_16_longs(dst, value) \ do { \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ } while (0) #define copy_16_longs(dst, src) \ do { \ *(dst)++ = *(src)++; *(dst)++ = *(src)++; \ *(dst)++ = *(src)++; *(dst)++ = *(src)++; \ *(dst)++ = *(src)++; *(dst)++ = *(src)++; \ *(dst)++ = *(src)++; *(dst)++ = *(src)++; \ *(dst)++ = *(src)++; *(dst)++ = *(src)++; \ *(dst)++ = *(src)++; *(dst)++ = *(src)++; \ *(dst)++ = *(src)++; *(dst)++ = *(src)++; \ *(dst)++ = *(src)++; *(dst)++ = *(src)++; \ } while (0) #endif /////////////////////////////////////////////////////////////////////////////// static void sk_memset16_portable(uint16_t dst[], uint16_t value, int count) { SkASSERT(dst != NULL && count >= 0); if (count <= 0) { return; } // not sure if this helps to short-circuit on small values of count if (count < 8) { do { *dst++ = (uint16_t)value; } while (--count != 0); return; } // ensure we're on a long boundary if ((size_t)dst & 2) { *dst++ = (uint16_t)value; count -= 1; } uint32_t value32 = ((uint32_t)value << 16) | value; // handle the bulk with our unrolled macro { int sixteenlongs = count >> 5; if (sixteenlongs) { uint32_t* dst32 = (uint32_t*)dst; do { assign_16_longs(dst32, value32); } while (--sixteenlongs != 0); dst = (uint16_t*)dst32; count &= 31; } } // handle (most) of the rest { int longs = count >> 1; if (longs) { do { *(uint32_t*)dst = value32; dst += 2; } while (--longs != 0); } } // cleanup a possible trailing short if (count & 1) { *dst = (uint16_t)value; } } static void sk_memset32_portable(uint32_t dst[], uint32_t value, int count) { SkASSERT(dst != NULL && count >= 0); int sixteenlongs = count >> 4; if (sixteenlongs) { do { assign_16_longs(dst, value); } while (--sixteenlongs != 0); count &= 15; } if (count) { do { *dst++ = value; } while (--count != 0); } } static void sk_memcpy32_portable(uint32_t dst[], const uint32_t src[], int count) { SkASSERT(dst != NULL && count >= 0); int sixteenlongs = count >> 4; if (sixteenlongs) { do { copy_16_longs(dst, src); } while (--sixteenlongs != 0); count &= 15; } if (count) { do { *dst++ = *src++; } while (--count != 0); } } static void choose_memset16(SkMemset16Proc* proc) { *proc = SkMemset16GetPlatformProc(); if (NULL == *proc) { *proc = &sk_memset16_portable; } } void sk_memset16(uint16_t dst[], uint16_t value, int count) { SK_DECLARE_STATIC_ONCE(once); static SkMemset16Proc proc = NULL; SkOnce(&once, choose_memset16, &proc); SkASSERT(proc != NULL); return proc(dst, value, count); } static void choose_memset32(SkMemset32Proc* proc) { *proc = SkMemset32GetPlatformProc(); if (NULL == *proc) { *proc = &sk_memset32_portable; } } void sk_memset32(uint32_t dst[], uint32_t value, int count) { SK_DECLARE_STATIC_ONCE(once); static SkMemset32Proc proc = NULL; SkOnce(&once, choose_memset32, &proc); SkASSERT(proc != NULL); return proc(dst, value, count); } static void choose_memcpy32(SkMemcpy32Proc* proc) { *proc = SkMemcpy32GetPlatformProc(); if (NULL == *proc) { *proc = &sk_memcpy32_portable; } } void sk_memcpy32(uint32_t dst[], const uint32_t src[], int count) { SK_DECLARE_STATIC_ONCE(once); static SkMemcpy32Proc proc = NULL; SkOnce(&once, choose_memcpy32, &proc); SkASSERT(proc != NULL); return proc(dst, src, count); } /////////////////////////////////////////////////////////////////////////////// /* 0xxxxxxx 1 total 10xxxxxx // never a leading byte 110xxxxx 2 total 1110xxxx 3 total 11110xxx 4 total 11 10 01 01 xx xx xx xx 0... 0xE5XX0000 0xE5 << 24 */ #ifdef SK_DEBUG static void assert_utf8_leadingbyte(unsigned c) { SkASSERT(c <= 0xF7); // otherwise leading byte is too big (more than 4 bytes) SkASSERT((c & 0xC0) != 0x80); // can't begin with a middle char } int SkUTF8_LeadByteToCount(unsigned c) { assert_utf8_leadingbyte(c); return (((0xE5 << 24) >> (c >> 4 << 1)) & 3) + 1; } #else #define assert_utf8_leadingbyte(c) #endif int SkUTF8_CountUnichars(const char utf8[]) { SkASSERT(utf8); int count = 0; for (;;) { int c = *(const uint8_t*)utf8; if (c == 0) { break; } utf8 += SkUTF8_LeadByteToCount(c); count += 1; } return count; } int SkUTF8_CountUnichars(const char utf8[], size_t byteLength) { SkASSERT(NULL != utf8 || 0 == byteLength); int count = 0; const char* stop = utf8 + byteLength; while (utf8 < stop) { utf8 += SkUTF8_LeadByteToCount(*(const uint8_t*)utf8); count += 1; } return count; } SkUnichar SkUTF8_ToUnichar(const char utf8[]) { SkASSERT(NULL != utf8); const uint8_t* p = (const uint8_t*)utf8; int c = *p; int hic = c << 24; assert_utf8_leadingbyte(c); if (hic < 0) { uint32_t mask = (uint32_t)~0x3F; hic <<= 1; do { c = (c << 6) | (*++p & 0x3F); mask <<= 5; } while ((hic <<= 1) < 0); c &= ~mask; } return c; } SkUnichar SkUTF8_NextUnichar(const char** ptr) { SkASSERT(NULL != ptr && NULL != *ptr); const uint8_t* p = (const uint8_t*)*ptr; int c = *p; int hic = c << 24; assert_utf8_leadingbyte(c); if (hic < 0) { uint32_t mask = (uint32_t)~0x3F; hic <<= 1; do { c = (c << 6) | (*++p & 0x3F); mask <<= 5; } while ((hic <<= 1) < 0); c &= ~mask; } *ptr = (char*)p + 1; return c; } SkUnichar SkUTF8_PrevUnichar(const char** ptr) { SkASSERT(NULL != ptr && NULL != *ptr); const char* p = *ptr; if (*--p & 0x80) { while (*--p & 0x40) { ; } } *ptr = (char*)p; return SkUTF8_NextUnichar(&p); } size_t SkUTF8_FromUnichar(SkUnichar uni, char utf8[]) { if ((uint32_t)uni > 0x10FFFF) { SkDEBUGFAIL("bad unichar"); return 0; } if (uni <= 127) { if (utf8) { *utf8 = (char)uni; } return 1; } char tmp[4]; char* p = tmp; size_t count = 1; SkDEBUGCODE(SkUnichar orig = uni;) while (uni > 0x7F >> count) { *p++ = (char)(0x80 | (uni & 0x3F)); uni >>= 6; count += 1; } if (utf8) { p = tmp; utf8 += count; while (p < tmp + count - 1) { *--utf8 = *p++; } *--utf8 = (char)(~(0xFF >> count) | uni); } SkASSERT(utf8 == NULL || orig == SkUTF8_ToUnichar(utf8)); return count; } /////////////////////////////////////////////////////////////////////////////// int SkUTF16_CountUnichars(const uint16_t src[]) { SkASSERT(src); int count = 0; unsigned c; while ((c = *src++) != 0) { SkASSERT(!SkUTF16_IsLowSurrogate(c)); if (SkUTF16_IsHighSurrogate(c)) { c = *src++; SkASSERT(SkUTF16_IsLowSurrogate(c)); } count += 1; } return count; } int SkUTF16_CountUnichars(const uint16_t src[], int numberOf16BitValues) { SkASSERT(src); const uint16_t* stop = src + numberOf16BitValues; int count = 0; while (src < stop) { unsigned c = *src++; SkASSERT(!SkUTF16_IsLowSurrogate(c)); if (SkUTF16_IsHighSurrogate(c)) { SkASSERT(src < stop); c = *src++; SkASSERT(SkUTF16_IsLowSurrogate(c)); } count += 1; } return count; } SkUnichar SkUTF16_NextUnichar(const uint16_t** srcPtr) { SkASSERT(srcPtr && *srcPtr); const uint16_t* src = *srcPtr; SkUnichar c = *src++; SkASSERT(!SkUTF16_IsLowSurrogate(c)); if (SkUTF16_IsHighSurrogate(c)) { unsigned c2 = *src++; SkASSERT(SkUTF16_IsLowSurrogate(c2)); // c = ((c & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000 // c = (((c & 0x3FF) + 64) << 10) + (c2 & 0x3FF) c = (c << 10) + c2 + (0x10000 - (0xD800 << 10) - 0xDC00); } *srcPtr = src; return c; } SkUnichar SkUTF16_PrevUnichar(const uint16_t** srcPtr) { SkASSERT(srcPtr && *srcPtr); const uint16_t* src = *srcPtr; SkUnichar c = *--src; SkASSERT(!SkUTF16_IsHighSurrogate(c)); if (SkUTF16_IsLowSurrogate(c)) { unsigned c2 = *--src; SkASSERT(SkUTF16_IsHighSurrogate(c2)); c = (c2 << 10) + c + (0x10000 - (0xD800 << 10) - 0xDC00); } *srcPtr = src; return c; } size_t SkUTF16_FromUnichar(SkUnichar uni, uint16_t dst[]) { SkASSERT((unsigned)uni <= 0x10FFFF); int extra = (uni > 0xFFFF); if (dst) { if (extra) { // dst[0] = SkToU16(0xD800 | ((uni - 0x10000) >> 10)); // dst[0] = SkToU16(0xD800 | ((uni >> 10) - 64)); dst[0] = SkToU16((0xD800 - 64) + (uni >> 10)); dst[1] = SkToU16(0xDC00 | (uni & 0x3FF)); SkASSERT(SkUTF16_IsHighSurrogate(dst[0])); SkASSERT(SkUTF16_IsLowSurrogate(dst[1])); } else { dst[0] = SkToU16(uni); SkASSERT(!SkUTF16_IsHighSurrogate(dst[0])); SkASSERT(!SkUTF16_IsLowSurrogate(dst[0])); } } return 1 + extra; } size_t SkUTF16_ToUTF8(const uint16_t utf16[], int numberOf16BitValues, char utf8[]) { SkASSERT(numberOf16BitValues >= 0); if (numberOf16BitValues <= 0) { return 0; } SkASSERT(utf16 != NULL); const uint16_t* stop = utf16 + numberOf16BitValues; size_t size = 0; if (utf8 == NULL) { // just count while (utf16 < stop) { size += SkUTF8_FromUnichar(SkUTF16_NextUnichar(&utf16), NULL); } } else { char* start = utf8; while (utf16 < stop) { utf8 += SkUTF8_FromUnichar(SkUTF16_NextUnichar(&utf16), utf8); } size = utf8 - start; } return size; } <commit_msg>sk_memcpy32 should fall back on libc memcpy.<commit_after> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkUtils.h" #include "SkOnce.h" #if 0 #define assign_16_longs(dst, value) \ do { \ (dst)[0] = value; (dst)[1] = value; \ (dst)[2] = value; (dst)[3] = value; \ (dst)[4] = value; (dst)[5] = value; \ (dst)[6] = value; (dst)[7] = value; \ (dst)[8] = value; (dst)[9] = value; \ (dst)[10] = value; (dst)[11] = value; \ (dst)[12] = value; (dst)[13] = value; \ (dst)[14] = value; (dst)[15] = value; \ } while (0) #else #define assign_16_longs(dst, value) \ do { \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ *(dst)++ = value; *(dst)++ = value; \ } while (0) #endif /////////////////////////////////////////////////////////////////////////////// static void sk_memset16_portable(uint16_t dst[], uint16_t value, int count) { SkASSERT(dst != NULL && count >= 0); if (count <= 0) { return; } // not sure if this helps to short-circuit on small values of count if (count < 8) { do { *dst++ = (uint16_t)value; } while (--count != 0); return; } // ensure we're on a long boundary if ((size_t)dst & 2) { *dst++ = (uint16_t)value; count -= 1; } uint32_t value32 = ((uint32_t)value << 16) | value; // handle the bulk with our unrolled macro { int sixteenlongs = count >> 5; if (sixteenlongs) { uint32_t* dst32 = (uint32_t*)dst; do { assign_16_longs(dst32, value32); } while (--sixteenlongs != 0); dst = (uint16_t*)dst32; count &= 31; } } // handle (most) of the rest { int longs = count >> 1; if (longs) { do { *(uint32_t*)dst = value32; dst += 2; } while (--longs != 0); } } // cleanup a possible trailing short if (count & 1) { *dst = (uint16_t)value; } } static void sk_memset32_portable(uint32_t dst[], uint32_t value, int count) { SkASSERT(dst != NULL && count >= 0); int sixteenlongs = count >> 4; if (sixteenlongs) { do { assign_16_longs(dst, value); } while (--sixteenlongs != 0); count &= 15; } if (count) { do { *dst++ = value; } while (--count != 0); } } static void sk_memcpy32_portable(uint32_t dst[], const uint32_t src[], int count) { memcpy(dst, src, count * sizeof(uint32_t)); } static void choose_memset16(SkMemset16Proc* proc) { *proc = SkMemset16GetPlatformProc(); if (NULL == *proc) { *proc = &sk_memset16_portable; } } void sk_memset16(uint16_t dst[], uint16_t value, int count) { SK_DECLARE_STATIC_ONCE(once); static SkMemset16Proc proc = NULL; SkOnce(&once, choose_memset16, &proc); SkASSERT(proc != NULL); return proc(dst, value, count); } static void choose_memset32(SkMemset32Proc* proc) { *proc = SkMemset32GetPlatformProc(); if (NULL == *proc) { *proc = &sk_memset32_portable; } } void sk_memset32(uint32_t dst[], uint32_t value, int count) { SK_DECLARE_STATIC_ONCE(once); static SkMemset32Proc proc = NULL; SkOnce(&once, choose_memset32, &proc); SkASSERT(proc != NULL); return proc(dst, value, count); } static void choose_memcpy32(SkMemcpy32Proc* proc) { *proc = SkMemcpy32GetPlatformProc(); if (NULL == *proc) { *proc = &sk_memcpy32_portable; } } void sk_memcpy32(uint32_t dst[], const uint32_t src[], int count) { SK_DECLARE_STATIC_ONCE(once); static SkMemcpy32Proc proc = NULL; SkOnce(&once, choose_memcpy32, &proc); SkASSERT(proc != NULL); return proc(dst, src, count); } /////////////////////////////////////////////////////////////////////////////// /* 0xxxxxxx 1 total 10xxxxxx // never a leading byte 110xxxxx 2 total 1110xxxx 3 total 11110xxx 4 total 11 10 01 01 xx xx xx xx 0... 0xE5XX0000 0xE5 << 24 */ #ifdef SK_DEBUG static void assert_utf8_leadingbyte(unsigned c) { SkASSERT(c <= 0xF7); // otherwise leading byte is too big (more than 4 bytes) SkASSERT((c & 0xC0) != 0x80); // can't begin with a middle char } int SkUTF8_LeadByteToCount(unsigned c) { assert_utf8_leadingbyte(c); return (((0xE5 << 24) >> (c >> 4 << 1)) & 3) + 1; } #else #define assert_utf8_leadingbyte(c) #endif int SkUTF8_CountUnichars(const char utf8[]) { SkASSERT(utf8); int count = 0; for (;;) { int c = *(const uint8_t*)utf8; if (c == 0) { break; } utf8 += SkUTF8_LeadByteToCount(c); count += 1; } return count; } int SkUTF8_CountUnichars(const char utf8[], size_t byteLength) { SkASSERT(NULL != utf8 || 0 == byteLength); int count = 0; const char* stop = utf8 + byteLength; while (utf8 < stop) { utf8 += SkUTF8_LeadByteToCount(*(const uint8_t*)utf8); count += 1; } return count; } SkUnichar SkUTF8_ToUnichar(const char utf8[]) { SkASSERT(NULL != utf8); const uint8_t* p = (const uint8_t*)utf8; int c = *p; int hic = c << 24; assert_utf8_leadingbyte(c); if (hic < 0) { uint32_t mask = (uint32_t)~0x3F; hic <<= 1; do { c = (c << 6) | (*++p & 0x3F); mask <<= 5; } while ((hic <<= 1) < 0); c &= ~mask; } return c; } SkUnichar SkUTF8_NextUnichar(const char** ptr) { SkASSERT(NULL != ptr && NULL != *ptr); const uint8_t* p = (const uint8_t*)*ptr; int c = *p; int hic = c << 24; assert_utf8_leadingbyte(c); if (hic < 0) { uint32_t mask = (uint32_t)~0x3F; hic <<= 1; do { c = (c << 6) | (*++p & 0x3F); mask <<= 5; } while ((hic <<= 1) < 0); c &= ~mask; } *ptr = (char*)p + 1; return c; } SkUnichar SkUTF8_PrevUnichar(const char** ptr) { SkASSERT(NULL != ptr && NULL != *ptr); const char* p = *ptr; if (*--p & 0x80) { while (*--p & 0x40) { ; } } *ptr = (char*)p; return SkUTF8_NextUnichar(&p); } size_t SkUTF8_FromUnichar(SkUnichar uni, char utf8[]) { if ((uint32_t)uni > 0x10FFFF) { SkDEBUGFAIL("bad unichar"); return 0; } if (uni <= 127) { if (utf8) { *utf8 = (char)uni; } return 1; } char tmp[4]; char* p = tmp; size_t count = 1; SkDEBUGCODE(SkUnichar orig = uni;) while (uni > 0x7F >> count) { *p++ = (char)(0x80 | (uni & 0x3F)); uni >>= 6; count += 1; } if (utf8) { p = tmp; utf8 += count; while (p < tmp + count - 1) { *--utf8 = *p++; } *--utf8 = (char)(~(0xFF >> count) | uni); } SkASSERT(utf8 == NULL || orig == SkUTF8_ToUnichar(utf8)); return count; } /////////////////////////////////////////////////////////////////////////////// int SkUTF16_CountUnichars(const uint16_t src[]) { SkASSERT(src); int count = 0; unsigned c; while ((c = *src++) != 0) { SkASSERT(!SkUTF16_IsLowSurrogate(c)); if (SkUTF16_IsHighSurrogate(c)) { c = *src++; SkASSERT(SkUTF16_IsLowSurrogate(c)); } count += 1; } return count; } int SkUTF16_CountUnichars(const uint16_t src[], int numberOf16BitValues) { SkASSERT(src); const uint16_t* stop = src + numberOf16BitValues; int count = 0; while (src < stop) { unsigned c = *src++; SkASSERT(!SkUTF16_IsLowSurrogate(c)); if (SkUTF16_IsHighSurrogate(c)) { SkASSERT(src < stop); c = *src++; SkASSERT(SkUTF16_IsLowSurrogate(c)); } count += 1; } return count; } SkUnichar SkUTF16_NextUnichar(const uint16_t** srcPtr) { SkASSERT(srcPtr && *srcPtr); const uint16_t* src = *srcPtr; SkUnichar c = *src++; SkASSERT(!SkUTF16_IsLowSurrogate(c)); if (SkUTF16_IsHighSurrogate(c)) { unsigned c2 = *src++; SkASSERT(SkUTF16_IsLowSurrogate(c2)); // c = ((c & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000 // c = (((c & 0x3FF) + 64) << 10) + (c2 & 0x3FF) c = (c << 10) + c2 + (0x10000 - (0xD800 << 10) - 0xDC00); } *srcPtr = src; return c; } SkUnichar SkUTF16_PrevUnichar(const uint16_t** srcPtr) { SkASSERT(srcPtr && *srcPtr); const uint16_t* src = *srcPtr; SkUnichar c = *--src; SkASSERT(!SkUTF16_IsHighSurrogate(c)); if (SkUTF16_IsLowSurrogate(c)) { unsigned c2 = *--src; SkASSERT(SkUTF16_IsHighSurrogate(c2)); c = (c2 << 10) + c + (0x10000 - (0xD800 << 10) - 0xDC00); } *srcPtr = src; return c; } size_t SkUTF16_FromUnichar(SkUnichar uni, uint16_t dst[]) { SkASSERT((unsigned)uni <= 0x10FFFF); int extra = (uni > 0xFFFF); if (dst) { if (extra) { // dst[0] = SkToU16(0xD800 | ((uni - 0x10000) >> 10)); // dst[0] = SkToU16(0xD800 | ((uni >> 10) - 64)); dst[0] = SkToU16((0xD800 - 64) + (uni >> 10)); dst[1] = SkToU16(0xDC00 | (uni & 0x3FF)); SkASSERT(SkUTF16_IsHighSurrogate(dst[0])); SkASSERT(SkUTF16_IsLowSurrogate(dst[1])); } else { dst[0] = SkToU16(uni); SkASSERT(!SkUTF16_IsHighSurrogate(dst[0])); SkASSERT(!SkUTF16_IsLowSurrogate(dst[0])); } } return 1 + extra; } size_t SkUTF16_ToUTF8(const uint16_t utf16[], int numberOf16BitValues, char utf8[]) { SkASSERT(numberOf16BitValues >= 0); if (numberOf16BitValues <= 0) { return 0; } SkASSERT(utf16 != NULL); const uint16_t* stop = utf16 + numberOf16BitValues; size_t size = 0; if (utf8 == NULL) { // just count while (utf16 < stop) { size += SkUTF8_FromUnichar(SkUTF16_NextUnichar(&utf16), NULL); } } else { char* start = utf8; while (utf16 < stop) { utf8 += SkUTF8_FromUnichar(SkUTF16_NextUnichar(&utf16), utf8); } size = utf8 - start; } return size; } <|endoftext|>
<commit_before>#ifndef CLUSTERING_ADMINISTRATION_MAIN_DIRECTORY_LOCK_HPP_ #define CLUSTERING_ADMINISTRATION_MAIN_DIRECTORY_LOCK_HPP_ #include <unistd.h> #include <exception> #include <string> #include "utils.hpp" #include "arch/io/io_utils.hpp" #define INVALID_GID (static_cast<gid_t>(-1)) #define INVALID_UID (static_cast<uid_t>(-1)) bool check_existence(const base_path_t& base_path); bool check_dir_emptiness(const base_path_t& base_path); class directory_lock_t { public: // Possibly creates, then opens and locks the specified directory // Returns true if the directory was created, false otherwise directory_lock_t(const base_path_t &path, bool create, bool *created_out); ~directory_lock_t(); // Prevents deletion of the directory tree at destruction, if // the directory was created in the constructor void directory_initialized(); // Sets the ownership of the directory to the given user and group. // INVALID_GID or INVALID_UID is a no-op for that field. // The strings are for error messages. void change_ownership(gid_t group_id, const std::string &group_name, uid_t user_id, const std::string &user_name); private: const base_path_t directory_path; scoped_fd_t directory_fd; bool created; bool initialize_done; }; class directory_missing_exc_t : public std::exception { public: explicit directory_missing_exc_t(const base_path_t &path) { info = strprintf("The directory '%s' does not exist, run 'rethinkdb create -d \"%s\"' and try again.", path.path().c_str(), path.path().c_str()); } ~directory_missing_exc_t() throw () { } const char *what() const throw () { return info.c_str(); } private: std::string info; }; class directory_create_failed_exc_t : public std::exception { public: directory_create_failed_exc_t(int err, const base_path_t &path) { info = strprintf("Could not create directory '%s': %s", path.path().c_str(), errno_string(err).c_str()); } ~directory_create_failed_exc_t() throw () { } const char *what() const throw () { return info.c_str(); } private: std::string info; }; class directory_open_failed_exc_t : public std::exception { public: directory_open_failed_exc_t(int err, const base_path_t &path) { info = strprintf("Could not open directory '%s': %s", path.path().c_str(), errno_string(err).c_str()); } ~directory_open_failed_exc_t() throw () { } const char *what() const throw () { return info.c_str(); } private: std::string info; }; class directory_locked_exc_t : public std::exception { public: explicit directory_locked_exc_t(const base_path_t &path) { info = strprintf("Directory '%s' is already in use, perhaps another instance of rethinkdb is using it.", path.path().c_str()); } ~directory_locked_exc_t() throw () { } const char *what() const throw () { return info.c_str(); } private: std::string info; }; #endif // CLUSTERING_ADMINISTRATION_MAIN_DIRECTORY_LOCK_HPP_ <commit_msg>Made directory_lock_t destructor be noexcept(false).<commit_after>#ifndef CLUSTERING_ADMINISTRATION_MAIN_DIRECTORY_LOCK_HPP_ #define CLUSTERING_ADMINISTRATION_MAIN_DIRECTORY_LOCK_HPP_ #include <unistd.h> #include <exception> #include <string> #include "utils.hpp" #include "arch/io/io_utils.hpp" #define INVALID_GID (static_cast<gid_t>(-1)) #define INVALID_UID (static_cast<uid_t>(-1)) bool check_existence(const base_path_t& base_path); bool check_dir_emptiness(const base_path_t& base_path); class directory_lock_t { public: // Possibly creates, then opens and locks the specified directory // Returns true if the directory was created, false otherwise directory_lock_t(const base_path_t &path, bool create, bool *created_out); ~directory_lock_t() noexcept(false); // Prevents deletion of the directory tree at destruction, if // the directory was created in the constructor void directory_initialized(); // Sets the ownership of the directory to the given user and group. // INVALID_GID or INVALID_UID is a no-op for that field. // The strings are for error messages. void change_ownership(gid_t group_id, const std::string &group_name, uid_t user_id, const std::string &user_name); private: const base_path_t directory_path; scoped_fd_t directory_fd; bool created; bool initialize_done; DISABLE_COPYING(directory_lock_t); }; class directory_missing_exc_t : public std::exception { public: explicit directory_missing_exc_t(const base_path_t &path) { info = strprintf("The directory '%s' does not exist, run 'rethinkdb create -d \"%s\"' and try again.", path.path().c_str(), path.path().c_str()); } ~directory_missing_exc_t() throw () { } const char *what() const throw () { return info.c_str(); } private: std::string info; }; class directory_create_failed_exc_t : public std::exception { public: directory_create_failed_exc_t(int err, const base_path_t &path) { info = strprintf("Could not create directory '%s': %s", path.path().c_str(), errno_string(err).c_str()); } ~directory_create_failed_exc_t() throw () { } const char *what() const throw () { return info.c_str(); } private: std::string info; }; class directory_open_failed_exc_t : public std::exception { public: directory_open_failed_exc_t(int err, const base_path_t &path) { info = strprintf("Could not open directory '%s': %s", path.path().c_str(), errno_string(err).c_str()); } ~directory_open_failed_exc_t() throw () { } const char *what() const throw () { return info.c_str(); } private: std::string info; }; class directory_locked_exc_t : public std::exception { public: explicit directory_locked_exc_t(const base_path_t &path) { info = strprintf("Directory '%s' is already in use, perhaps another instance of rethinkdb is using it.", path.path().c_str()); } ~directory_locked_exc_t() throw () { } const char *what() const throw () { return info.c_str(); } private: std::string info; }; #endif // CLUSTERING_ADMINISTRATION_MAIN_DIRECTORY_LOCK_HPP_ <|endoftext|>
<commit_before>#include "spotlightDemo.h" #include "vrambatcher.h" #include <nds/arm9/window.h> #include <cmath> #include <nds/arm9/input.h> #define M_PI 3.14159265358979323846 #define FULL_ROTATION M_PI*2 #define D45 FULL_ROTATION/8 #define MD45 FULL_ROTATION/-8 #define D135 (FULL_ROTATION/4+D45) #define MD135 -D135 #define MAX_SPREAD FULL_ROTATION/2 #define MIN_SPREAD FULL_ROTATION/64 SpotLightDemo::SpotLightDemo() : lightX(128), lightY(96), angle(M_PI/2), spread(M_PI/8) {} SpotLightDemo::~SpotLightDemo() {} float yPosForAngleAndSide(float angle, int side) { return side / std::tan(angle); } void SpotLightDemo::PrepareFrame(VramBatcher &batcher) { WindowingDemo::PrepareFrame(batcher); float leftAngle = angle - spread; float rightAngle = angle + spread; if (leftAngle > FULL_ROTATION/2) leftAngle -= FULL_ROTATION; if (rightAngle > FULL_ROTATION/2) rightAngle -= FULL_ROTATION; if (leftAngle < -FULL_ROTATION/2) leftAngle += FULL_ROTATION; if (rightAngle < -FULL_ROTATION/2) rightAngle += FULL_ROTATION; float tanLeft = std::tan(-leftAngle); float tanRight = std::tan(-rightAngle); float cosLeft = std::cos(leftAngle); float cosRight = std::cos(rightAngle); float normLeft = 1 / tanLeft; float normRight = 1 / tanRight; int top; int bottom; bool pointsLeft=false, pointsRight=false, pointsUp=false, pointsDown=false; if (angle < D45 && angle > MD45) { pointsRight = true; puts("right"); top = lightY + yPosForAngleAndSide(leftAngle, SCREEN_WIDTH - lightX); bottom = lightY + yPosForAngleAndSide(rightAngle, SCREEN_WIDTH - lightX); if (top > lightY) top = lightY; if (bottom < lightY) bottom = lightY; } else if (angle > MD135 && angle < MD45) { pointsUp = true; puts("up"); top = 0; bottom = lightY; } else if (angle > D45 && angle < D135) { pointsDown = true; puts("down"); top = lightY; bottom = SCREEN_HEIGHT; } else { pointsLeft = true; puts("left"); top = lightY + yPosForAngleAndSide(rightAngle, lightX); bottom = lightY + yPosForAngleAndSide(leftAngle, lightX); if (top > lightY) top = lightY; if (bottom < lightY) bottom = lightY; } if (top < 0) top = 0; if (bottom > SCREEN_HEIGHT) bottom = SCREEN_HEIGHT; if (top > bottom) { printf("top > bottom! %i %i\n", top, bottom); } WIN0_Y0=top; WIN0_Y1=bottom-1; //printf("%f %f\n", cosLeft, cosRight); for (int scanline = top; scanline < bottom; ++scanline) { float yLen = lightY - scanline; float xLenLeft = yLen*tanLeft; float xLenRight = yLen*tanRight; float leftXF = lightX+xLenLeft; float rightXF = lightX+xLenRight; int leftX = (leftXF < 0 ? 0 : (leftXF > SCREEN_WIDTH - 1 ? SCREEN_WIDTH - 1 : leftXF )); int rightX = (rightXF < 0 ? 0 : (rightXF > SCREEN_WIDTH - 1 ? SCREEN_WIDTH -1 : rightXF)); if (scanline == 100) { printf("%i %i\n", leftX, rightX); } if (pointsRight) { //left up, right down (right) //left is above, right is bellow //right side of the window is the right screen border if (scanline < lightY) { batcher.AddPoke(scanline, leftX, &WIN0_X0); } else if (scanline > lightY) { batcher.AddPoke(scanline, rightX, &WIN0_X0); } else { batcher.AddPoke(scanline, lightX, &WIN0_X0); } batcher.AddPoke(scanline, SCREEN_WIDTH-1, &WIN0_X1); } else if (pointsLeft) { //left down, right up (left) //left is bellow, right is above //left side of the window is the left screen border batcher.AddPoke(scanline, 0, &WIN0_X0); if (scanline < lightY) { batcher.AddPoke(scanline, rightX, &WIN0_X1); } else if (scanline > lightY) { batcher.AddPoke(scanline, leftX, &WIN0_X1); } else { batcher.AddPoke(scanline, lightX, &WIN0_X1); } } else if (pointsUp) { //both pointing up (up) //left is on the left side of the screen and right is on the right side of the screen batcher.AddPoke(scanline, leftX, &WIN0_X0); batcher.AddPoke(scanline, rightX, &WIN0_X1); } else if(pointsDown) { //left down, right down (down) //left is on the right side of the screen and right is on the left side of the screen batcher.AddPoke(scanline, rightX, &WIN0_X0); batcher.AddPoke(scanline, leftX, &WIN0_X1); } } } void SpotLightDemo::AcceptInput() { WindowingDemo::AcceptInput(); auto keys = keysCurrent(); if (keys & KEY_L) { angle -= 0.02; if (angle <= -FULL_ROTATION/2) angle += FULL_ROTATION; printf("Angle: %f\n", angle); } else if (keys & KEY_R) { angle += 0.02; if (angle >= FULL_ROTATION/2) angle -= FULL_ROTATION; printf("Angle: %f\n", angle); } if (keys & KEY_X && spread < MAX_SPREAD) { spread += 0.02; printf("Spread: %f\n", spread); } else if (keys & KEY_Y && spread > MIN_SPREAD) { spread -= 0.02; printf("Spread: %f\n", spread); } if (keys & KEY_UP) { --lightY; } else if (keys & KEY_DOWN) { ++lightY; } if (keys & KEY_LEFT) { --lightX; } else if (keys & KEY_RIGHT) { ++lightX; } } <commit_msg>Less broken spotlights<commit_after>#include "spotlightDemo.h" #include "vrambatcher.h" #include <nds/arm9/window.h> #include <cmath> #include <nds/arm9/input.h> #define M_PI 3.14159265358979323846 #define FULL_ROTATION M_PI*2 #define D45 FULL_ROTATION/8 #define MD45 FULL_ROTATION/-8 #define D135 (FULL_ROTATION/4+D45) #define MD135 -D135 #define MAX_SPREAD FULL_ROTATION/2 #define MIN_SPREAD FULL_ROTATION/64 SpotLightDemo::SpotLightDemo() : lightX(128), lightY(96), angle(M_PI/2), spread(M_PI/8) {} SpotLightDemo::~SpotLightDemo() {} float yPosForAngleAndSide(float angle, int side) { return side / std::tan(angle); } void SpotLightDemo::PrepareFrame(VramBatcher &batcher) { WindowingDemo::PrepareFrame(batcher); float leftAngle = angle - spread; float rightAngle = angle + spread; if (leftAngle > FULL_ROTATION/2) leftAngle -= FULL_ROTATION; if (rightAngle > FULL_ROTATION/2) rightAngle -= FULL_ROTATION; if (leftAngle < -FULL_ROTATION/2) leftAngle += FULL_ROTATION; if (rightAngle < -FULL_ROTATION/2) rightAngle += FULL_ROTATION; float tanLeft = std::tan(-leftAngle); float tanRight = std::tan(-rightAngle); float cosLeft = std::cos(leftAngle); float cosRight = std::cos(rightAngle); float normLeft = -1 / tanLeft; float normRight = -1 / tanRight; int top; int bottom; bool pointsLeft=false, pointsRight=false, pointsUp=false, pointsDown=false; if (angle < D45 && angle > MD45) { pointsRight = true; puts("right"); top = lightY + yPosForAngleAndSide(leftAngle, SCREEN_WIDTH - lightX); bottom = lightY + yPosForAngleAndSide(rightAngle, SCREEN_WIDTH - lightX); if (top > lightY) top = lightY; if (bottom < lightY) bottom = lightY; } else if (angle > MD135 && angle < MD45) { pointsUp = true; puts("up"); top = 0; bottom = lightY; } else if (angle > D45 && angle < D135) { pointsDown = true; puts("down"); top = lightY; bottom = SCREEN_HEIGHT; } else { pointsLeft = true; puts("left"); top = lightY + yPosForAngleAndSide(rightAngle, lightX); bottom = lightY + yPosForAngleAndSide(leftAngle, lightX); if (top > lightY) top = lightY; if (bottom < lightY) bottom = lightY; } if (top < 0) top = 0; if (bottom > SCREEN_HEIGHT) bottom = SCREEN_HEIGHT; if (top > bottom) { printf("top > bottom! %i %i\n", top, bottom); } WIN0_Y0=top; WIN0_Y1=bottom-1; bool pointsSideways = pointsLeft || pointsRight; //printf("%f %f\n", cosLeft, cosRight); for (int scanline = top; scanline < bottom; ++scanline) { float yLen = lightY - scanline; float xLenLeft = pointsSideways ? (yLen*normLeft) : (yLen*tanLeft); float xLenRight = pointsSideways ? (yLen*normRight) : (yLen*tanRight); float leftXF = lightX+xLenLeft; float rightXF = lightX+xLenRight; int leftX = (leftXF < 0 ? 0 : (leftXF > SCREEN_WIDTH - 1 ? SCREEN_WIDTH - 1 : leftXF )); int rightX = (rightXF < 0 ? 0 : (rightXF > SCREEN_WIDTH - 1 ? SCREEN_WIDTH -1 : rightXF)); if (scanline == 100) { printf("%i %i\n", leftX, rightX); } if (pointsRight) { //left up, right down (right) //left is above, right is bellow //right side of the window is the right screen border if (scanline < lightY) { batcher.AddPoke(scanline, leftX, &WIN0_X0); } else if (scanline > lightY) { batcher.AddPoke(scanline, rightX, &WIN0_X0); } else { batcher.AddPoke(scanline, lightX, &WIN0_X0); } batcher.AddPoke(scanline, SCREEN_WIDTH-1, &WIN0_X1); } else if (pointsLeft) { //left down, right up (left) //left is bellow, right is above //left side of the window is the left screen border batcher.AddPoke(scanline, 0, &WIN0_X0); if (scanline < lightY) { batcher.AddPoke(scanline, rightX, &WIN0_X1); } else if (scanline > lightY) { batcher.AddPoke(scanline, leftX, &WIN0_X1); } else { batcher.AddPoke(scanline, lightX, &WIN0_X1); } } else if (pointsUp) { //both pointing up (up) //left is on the left side of the screen and right is on the right side of the screen batcher.AddPoke(scanline, leftX, &WIN0_X0); batcher.AddPoke(scanline, rightX, &WIN0_X1); } else if(pointsDown) { //left down, right down (down) //left is on the right side of the screen and right is on the left side of the screen batcher.AddPoke(scanline, rightX, &WIN0_X0); batcher.AddPoke(scanline, leftX, &WIN0_X1); } } } void SpotLightDemo::AcceptInput() { WindowingDemo::AcceptInput(); auto keys = keysCurrent(); if (keys & KEY_L) { angle -= 0.02; if (angle <= -FULL_ROTATION/2) angle += FULL_ROTATION; printf("Angle: %f\n", angle); } else if (keys & KEY_R) { angle += 0.02; if (angle >= FULL_ROTATION/2) angle -= FULL_ROTATION; printf("Angle: %f\n", angle); } if (keys & KEY_X && spread < MAX_SPREAD) { spread += 0.02; printf("Spread: %f\n", spread); } else if (keys & KEY_Y && spread > MIN_SPREAD) { spread -= 0.02; printf("Spread: %f\n", spread); } if (keys & KEY_UP) { --lightY; } else if (keys & KEY_DOWN) { ++lightY; } if (keys & KEY_LEFT) { --lightX; } else if (keys & KEY_RIGHT) { ++lightX; } } <|endoftext|>
<commit_before>/** ** \file runner/interpreter.cc ** \brief Implementation of runner::Interpreter. */ // #define ENABLE_DEBUG_TRACES #include <libport/compiler.hh> #include <libport/finally.hh> #include <algorithm> #include <deque> #include <boost/range/iterator_range.hpp> #include <libport/foreach.hh> #include <libport/symbol.hh> #include <kernel/uconnection.hh> #include <object/cxx-conversions.hh> #include <object/global.hh> #include <object/lobby.hh> #include <object/task.hh> #include <runner/call.hh> #include <runner/interpreter.hh> #include <runner/raise.hh> #include <parser/uparser.hh> #include <scheduler/exception.hh> namespace runner { using libport::Finally; // This function takes an expression and attempts to decompose it // into a list of identifiers. typedef std::deque<libport::Symbol> tag_chain_type; static tag_chain_type decompose_tag_chain (ast::rConstExp e) { tag_chain_type res; while (!e->implicit()) { ast::rConstCall c = e.unsafe_cast<const ast::Call>(); if (!c || c->arguments_get()) runner::raise_urbi(SYMBOL(ImplicitTagComponentError)); res.push_front (c->name_get()); e = c->target_get(); } return res; } /*--------------. | Interpreter. | `--------------*/ Interpreter::Interpreter (rLobby lobby, scheduler::Scheduler& sched, ast::rConstAst ast, const libport::Symbol& name) : Runner(lobby, sched, name) , ast_(ast) , code_(0) , result_(0) , stacks_(lobby) { init(); apply_tag(lobby->slot_get(SYMBOL(connectionTag))->as<object::Tag>(), 0); } Interpreter::Interpreter(const Interpreter& model, rObject code, const libport::Symbol& name, const objects_type& args) : Runner(model, name) , ast_(0) , code_(code) , args_(args) , result_(0) , call_stack_(model.call_stack_) , stacks_(model.lobby_) { tag_stack_set(model.tag_stack_get()); init(); } Interpreter::Interpreter(const Interpreter& model, ast::rConstAst ast, const libport::Symbol& name) : Runner(model, name) , ast_(ast) , code_(0) , result_(0) , stacks_(model.lobby_) { tag_stack_set(model.tag_stack_get()); init(); } Interpreter::~Interpreter () { } void Interpreter::init() { // Push a dummy scope tag, in case we do have an "at" at the // toplevel. create_scope_tag(); } void Interpreter::show_exception_ (object::UrbiException& ue) { rObject str = urbi_call(*this, ue.value_get(), SYMBOL(asString)); std::ostringstream o; o << "!!! " << str->as<object::String>()->value_get(); send_message("error", o.str ()); show_backtrace(ue.backtrace_get(), "error"); } void Interpreter::work () { try { assert (ast_ || code_); check_for_pending_exception(); if (ast_) result_ = operator()(ast_.get()); else result_ = apply(lobby_, code_, libport::Symbol::make_empty(), args_); } catch (object::UrbiException& exn) { // If this runner has a parent, let the exception go through // so that it will be handled by Job::run(). if (child_job()) throw; else // This is a detached runner, show the error. { // Yielding inside a catch is forbidden Finally finally (boost::bind(&Runner::non_interruptible_set, this, non_interruptible_get())); non_interruptible_set(true); show_exception_(exn); } } } void Interpreter::scheduling_error(const std::string& msg) { libport::Finally finally; // We may have a situation here. If the stack space is running // near exhaustion, we cannot reasonably hope that we will get // enough stack space to build an exception, which potentially // requires a non-negligible amount of calls. For this reason, we // create another job whose task is to build the exception (in a // freshly allocated stack) and propagate it to us as we are its // parent. CAPTURE_GLOBAL(SchedulingError); object::objects_type args; args.push_back(object::to_urbi(msg)); scheduler::rJob child = new Interpreter(*this, SchedulingError->slot_get(SYMBOL(throwNew)), SYMBOL(SchedulingError), args); register_child(child, finally); child->start_job(); try { // Clear the non-interruptible flag so that we do not // run into an error while waiting for our child. finally << boost::bind(&Job::non_interruptible_set, this, non_interruptible_get()); non_interruptible_set(false); yield_until_terminated(*child); } catch (const scheduler::ChildException& ce) { try { ce.rethrow_child_exception(); } catch (const object::UrbiException& ue) { raise(ue.value_get(), false); } } } object::rObject Interpreter::eval_tag(ast::rConstExp e) { try { // Try to evaluate e as a normal expression. return operator()(e.get()); } catch (object::UrbiException&) { ECHO("Implicit tag: " << *e); // We got a lookup error. It means that we have to automatically // create the tag. In this case, we only accept k1 style tags, // i.e. chains of identifiers, excluding function calls. // The reason to do that is: // - we do not want to mix k1 non-declared syntax with k2 // clean syntax for tags // - we have no way to know whether the lookup error arrived // in a function call or during the direct resolution of // the name // Tag represents the top level tag CAPTURE_GLOBAL(Tags); const rObject& toplevel = Tags; rObject parent = toplevel; rObject where = stacks_.self(); tag_chain_type chain = decompose_tag_chain(e); foreach (const libport::Symbol& elt, chain) { // Check whether the concerned level in the chain already // exists. if (const rObject& owner = where->slot_locate (elt)) { ECHO("Component " << elt << " exists."); where = owner->own_slot_get (elt); object::Tag* parent_ = dynamic_cast<object::Tag*>(where.get()); if (parent_) { ECHO("It is a tag, so use it as the new parent."); parent = parent_; } } else { // We have to create a new tag, which will be attached // to the upper level (hierarchical tags, implicitly // rooted by Tags). where = object::urbi_call (*this, parent, SYMBOL(new), new object::String(elt)); parent->slot_set(elt, where); parent = where; } } return where; } } void Interpreter::show_backtrace(const call_stack_type& bt, const std::string& chan) { rforeach (call_type c, bt) { std::ostringstream o; o << "!!! called from: "; if (c.second) o << *c.second << ": "; o << c.first; send_message(chan, o.str()); } } void Interpreter::show_backtrace(const std::string& chan) { show_backtrace(call_stack_, chan); } Interpreter::backtrace_type Interpreter::backtrace_get() const { backtrace_type res; foreach (call_type c, call_stack_) { std::ostringstream o; if (c.second) o << c.second.get(); res.push_back(std::make_pair(c.first.name_get(), o.str())); } return res; } object::call_stack_type Interpreter::call_stack_get() const { return call_stack_; } void Interpreter::raise(rObject exn, bool skip_last) { CAPTURE_GLOBAL(Exception); if (is_a(exn, Exception)) { std::stringstream o; o << innermost_node_->location_get(); exn->slot_update(*this, SYMBOL(location), new object::String(o.str())); exn->slot_update(*this, SYMBOL(backtrace), as_task()->as<object::Task>()->backtrace()); } call_stack_type bt = call_stack_get(); if (skip_last && !bt.empty()) bt.pop_back(); throw object::UrbiException(exn, bt); } } // namespace runner #ifndef LIBPORT_SPEED // If not in speed mode, compile visit method here # include <runner/interpreter-visit.hxx> #endif <commit_msg>Use a "vector" instead of a "deque" to decompose a tag chain.<commit_after>/** ** \file runner/interpreter.cc ** \brief Implementation of runner::Interpreter. */ // #define ENABLE_DEBUG_TRACES #include <libport/compiler.hh> #include <libport/finally.hh> #include <algorithm> #include <vector> #include <boost/range/iterator_range.hpp> #include <libport/foreach.hh> #include <libport/symbol.hh> #include <kernel/uconnection.hh> #include <object/cxx-conversions.hh> #include <object/global.hh> #include <object/lobby.hh> #include <object/task.hh> #include <runner/call.hh> #include <runner/interpreter.hh> #include <runner/raise.hh> #include <parser/uparser.hh> #include <scheduler/exception.hh> namespace runner { using libport::Finally; // This function takes an expression and attempts to decompose it // into a list of identifiers. The resulting chain is stored in // reverse order, that is the most specific tag first. typedef std::vector<libport::Symbol> tag_chain_type; static tag_chain_type decompose_tag_chain (ast::rConstExp e) { tag_chain_type res; while (!e->implicit()) { ast::rConstCall c = e.unsafe_cast<const ast::Call>(); if (!c || c->arguments_get()) runner::raise_urbi(SYMBOL(ImplicitTagComponentError)); res.push_back (c->name_get()); e = c->target_get(); } return res; } /*--------------. | Interpreter. | `--------------*/ Interpreter::Interpreter (rLobby lobby, scheduler::Scheduler& sched, ast::rConstAst ast, const libport::Symbol& name) : Runner(lobby, sched, name) , ast_(ast) , code_(0) , result_(0) , stacks_(lobby) { init(); apply_tag(lobby->slot_get(SYMBOL(connectionTag))->as<object::Tag>(), 0); } Interpreter::Interpreter(const Interpreter& model, rObject code, const libport::Symbol& name, const objects_type& args) : Runner(model, name) , ast_(0) , code_(code) , args_(args) , result_(0) , call_stack_(model.call_stack_) , stacks_(model.lobby_) { tag_stack_set(model.tag_stack_get()); init(); } Interpreter::Interpreter(const Interpreter& model, ast::rConstAst ast, const libport::Symbol& name) : Runner(model, name) , ast_(ast) , code_(0) , result_(0) , stacks_(model.lobby_) { tag_stack_set(model.tag_stack_get()); init(); } Interpreter::~Interpreter () { } void Interpreter::init() { // Push a dummy scope tag, in case we do have an "at" at the // toplevel. create_scope_tag(); } void Interpreter::show_exception_ (object::UrbiException& ue) { rObject str = urbi_call(*this, ue.value_get(), SYMBOL(asString)); std::ostringstream o; o << "!!! " << str->as<object::String>()->value_get(); send_message("error", o.str ()); show_backtrace(ue.backtrace_get(), "error"); } void Interpreter::work () { try { assert (ast_ || code_); check_for_pending_exception(); if (ast_) result_ = operator()(ast_.get()); else result_ = apply(lobby_, code_, libport::Symbol::make_empty(), args_); } catch (object::UrbiException& exn) { // If this runner has a parent, let the exception go through // so that it will be handled by Job::run(). if (child_job()) throw; else // This is a detached runner, show the error. { // Yielding inside a catch is forbidden Finally finally (boost::bind(&Runner::non_interruptible_set, this, non_interruptible_get())); non_interruptible_set(true); show_exception_(exn); } } } void Interpreter::scheduling_error(const std::string& msg) { libport::Finally finally; // We may have a situation here. If the stack space is running // near exhaustion, we cannot reasonably hope that we will get // enough stack space to build an exception, which potentially // requires a non-negligible amount of calls. For this reason, we // create another job whose task is to build the exception (in a // freshly allocated stack) and propagate it to us as we are its // parent. CAPTURE_GLOBAL(SchedulingError); object::objects_type args; args.push_back(object::to_urbi(msg)); scheduler::rJob child = new Interpreter(*this, SchedulingError->slot_get(SYMBOL(throwNew)), SYMBOL(SchedulingError), args); register_child(child, finally); child->start_job(); try { // Clear the non-interruptible flag so that we do not // run into an error while waiting for our child. finally << boost::bind(&Job::non_interruptible_set, this, non_interruptible_get()); non_interruptible_set(false); yield_until_terminated(*child); } catch (const scheduler::ChildException& ce) { try { ce.rethrow_child_exception(); } catch (const object::UrbiException& ue) { raise(ue.value_get(), false); } } } object::rObject Interpreter::eval_tag(ast::rConstExp e) { try { // Try to evaluate e as a normal expression. return operator()(e.get()); } catch (object::UrbiException&) { ECHO("Implicit tag: " << *e); // We got a lookup error. It means that we have to automatically // create the tag. In this case, we only accept k1 style tags, // i.e. chains of identifiers, excluding function calls. // The reason to do that is: // - we do not want to mix k1 non-declared syntax with k2 // clean syntax for tags // - we have no way to know whether the lookup error arrived // in a function call or during the direct resolution of // the name // Tag represents the top level tag CAPTURE_GLOBAL(Tags); const rObject& toplevel = Tags; rObject parent = toplevel; rObject where = stacks_.self(); tag_chain_type chain = decompose_tag_chain(e); rforeach (const libport::Symbol& elt, chain) { // Check whether the concerned level in the chain already // exists. if (const rObject& owner = where->slot_locate (elt)) { ECHO("Component " << elt << " exists."); where = owner->own_slot_get (elt); object::Tag* parent_ = dynamic_cast<object::Tag*>(where.get()); if (parent_) { ECHO("It is a tag, so use it as the new parent."); parent = parent_; } } else { // We have to create a new tag, which will be attached // to the upper level (hierarchical tags, implicitly // rooted by Tags). where = object::urbi_call (*this, parent, SYMBOL(new), new object::String(elt)); parent->slot_set(elt, where); parent = where; } } return where; } } void Interpreter::show_backtrace(const call_stack_type& bt, const std::string& chan) { rforeach (call_type c, bt) { std::ostringstream o; o << "!!! called from: "; if (c.second) o << *c.second << ": "; o << c.first; send_message(chan, o.str()); } } void Interpreter::show_backtrace(const std::string& chan) { show_backtrace(call_stack_, chan); } Interpreter::backtrace_type Interpreter::backtrace_get() const { backtrace_type res; foreach (call_type c, call_stack_) { std::ostringstream o; if (c.second) o << c.second.get(); res.push_back(std::make_pair(c.first.name_get(), o.str())); } return res; } object::call_stack_type Interpreter::call_stack_get() const { return call_stack_; } void Interpreter::raise(rObject exn, bool skip_last) { CAPTURE_GLOBAL(Exception); if (is_a(exn, Exception)) { std::stringstream o; o << innermost_node_->location_get(); exn->slot_update(*this, SYMBOL(location), new object::String(o.str())); exn->slot_update(*this, SYMBOL(backtrace), as_task()->as<object::Task>()->backtrace()); } call_stack_type bt = call_stack_get(); if (skip_last && !bt.empty()) bt.pop_back(); throw object::UrbiException(exn, bt); } } // namespace runner #ifndef LIBPORT_SPEED // If not in speed mode, compile visit method here # include <runner/interpreter-visit.hxx> #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: fuconuno.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: aw $ $Date: 2002-03-22 09:56:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_FUCONUNO_HXX #define SC_FUCONUNO_HXX #ifndef SC_FUCONSTR_HXX #include "fuconstr.hxx" #endif /************************************************************************* |* |* Control zeichnen |* \************************************************************************/ class FuConstUnoControl : public FuConstruct { protected: UINT32 nInventor; UINT16 nIdentifier; public: FuConstUnoControl(ScTabViewShell* pViewSh, Window* pWin, SdrView* pView, SdrModel* pDoc, SfxRequest& rReq); virtual ~FuConstUnoControl(); // Mouse- & Key-Events virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren // #98185# Create default drawing objects via keyboard virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle); }; #endif // _SD_FUCONCTL_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.906); FILE MERGED 2005/09/05 15:05:24 rt 1.2.906.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuconuno.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:27:56 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_FUCONUNO_HXX #define SC_FUCONUNO_HXX #ifndef SC_FUCONSTR_HXX #include "fuconstr.hxx" #endif /************************************************************************* |* |* Control zeichnen |* \************************************************************************/ class FuConstUnoControl : public FuConstruct { protected: UINT32 nInventor; UINT16 nIdentifier; public: FuConstUnoControl(ScTabViewShell* pViewSh, Window* pWin, SdrView* pView, SdrModel* pDoc, SfxRequest& rReq); virtual ~FuConstUnoControl(); // Mouse- & Key-Events virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren // #98185# Create default drawing objects via keyboard virtual SdrObject* CreateDefaultObject(const sal_uInt16 nID, const Rectangle& rRectangle); }; #endif // _SD_FUCONCTL_HXX <|endoftext|>
<commit_before>//===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the Owen Anderson and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass performs a hybrid of global value numbering and partial redundancy // elimination, known as GVN-PRE. It performs partial redundancy elimination on // values, rather than lexical expressions, allowing a more comprehensive view // the optimization. It replaces redundant values with uses of earlier // occurences of the same value. While this is beneficial in that it eliminates // unneeded computation, it also increases register pressure by creating large // live ranges, and should be used with caution on platforms that a very // sensitive to register pressure. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "gvnpre" #include "llvm/Value.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Instructions.h" #include "llvm/Function.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Compiler.h" #include <algorithm> #include <map> #include <set> #include <cstdio> using namespace llvm; namespace { class VISIBILITY_HIDDEN GVNPRE : public FunctionPass { bool runOnFunction(Function &F); public: static char ID; // Pass identification, replacement for typeid GVNPRE() : FunctionPass((intptr_t)&ID) { nextValueNumber = 0; } private: uint32_t nextValueNumber; struct Expression { char opcode; Value* value; uint32_t lhs; uint32_t rhs; bool operator<(const Expression& other) const { if (opcode < other.opcode) return true; else if (other.opcode < opcode) return false; if (opcode == 0) { if (value < other.value) return true; else return false; } else { if (lhs < other.lhs) return true; else if (other.lhs < lhs) return true; else if (rhs < other.rhs) return true; else return false; } } bool operator==(const Expression& other) const { if (opcode != other.opcode) return false; if (value != other.value) return false; if (lhs != other.lhs) return false; if (rhs != other.rhs) return false; return true; } }; typedef std::map<Expression, uint32_t> ValueTable; virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<DominatorTree>(); AU.addRequired<PostDominatorTree>(); } // Helper fuctions // FIXME: eliminate or document these better void dump(ValueTable& VN, std::set<Expression>& s); void clean(ValueTable VN, std::set<Expression>& set); Expression add(ValueTable& VN, std::set<Expression>& MS, Instruction* V); ValueTable::iterator lookup(ValueTable& VN, Value* V); Expression buildExpression(ValueTable& VN, Value* V); std::set<Expression>::iterator find_leader(ValueTable VN, std::set<Expression>& vals, uint32_t v); void phi_translate(ValueTable& VN, std::set<Expression>& anticIn, BasicBlock* B, std::set<Expression>& out); // For a given block, calculate the generated expressions, temporaries, // and the AVAIL_OUT set void CalculateAvailOut(ValueTable& VN, std::set<Expression>& MS, DominatorTree::Node* DI, std::set<Expression>& currExps, std::set<PHINode*>& currPhis, std::set<Expression>& currTemps, std::set<Expression>& currAvail, std::map<BasicBlock*, std::set<Expression> > availOut); }; char GVNPRE::ID = 0; } FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); } RegisterPass<GVNPRE> X("gvnpre", "Global Value Numbering/Partial Redundancy Elimination"); // Given a Value, build an Expression to represent it GVNPRE::Expression GVNPRE::buildExpression(ValueTable& VN, Value* V) { if (Instruction* I = dyn_cast<Instruction>(V)) { Expression e; switch (I->getOpcode()) { case 7: e.opcode = 1; // ADD break; case 8: e.opcode = 2; // SUB break; case 9: e.opcode = 3; // MUL break; case 10: e.opcode = 4; // UDIV break; case 11: e.opcode = 5; // SDIV break; case 12: e.opcode = 6; // FDIV break; case 13: e.opcode = 7; // UREM break; case 14: e.opcode = 8; // SREM break; case 15: e.opcode = 9; // FREM break; default: e.opcode = 0; // OPAQUE e.lhs = 0; e.rhs = 0; e.value = V; return e; } e.value = 0; ValueTable::iterator lhs = lookup(VN, I->getOperand(0)); if (lhs == VN.end()) { Expression lhsExp = buildExpression(VN, I->getOperand(0)); VN.insert(std::make_pair(lhsExp, nextValueNumber)); e.lhs = nextValueNumber; nextValueNumber++; } else e.lhs = lhs->second; ValueTable::iterator rhs = lookup(VN, I->getOperand(1)); if (rhs == VN.end()) { Expression rhsExp = buildExpression(VN, I->getOperand(1)); VN.insert(std::make_pair(rhsExp, nextValueNumber)); e.rhs = nextValueNumber; nextValueNumber++; } else e.rhs = rhs->second; return e; } else { Expression e; e.opcode = 0; e.value = V; e.lhs = 0; e.rhs = 0; return e; } } GVNPRE::Expression GVNPRE::add(ValueTable& VN, std::set<Expression>& MS, Instruction* V) { Expression e = buildExpression(VN, V); if (VN.insert(std::make_pair(e, nextValueNumber)).second) nextValueNumber++; if (e.opcode != 0 || (e.opcode == 0 && isa<PHINode>(e.value))) MS.insert(e); return e; } GVNPRE::ValueTable::iterator GVNPRE::lookup(ValueTable& VN, Value* V) { Expression e = buildExpression(VN, V); return VN.find(e); } std::set<GVNPRE::Expression>::iterator GVNPRE::find_leader(GVNPRE::ValueTable VN, std::set<GVNPRE::Expression>& vals, uint32_t v) { for (std::set<Expression>::iterator I = vals.begin(), E = vals.end(); I != E; ++I) if (VN[*I] == v) return I; return vals.end(); } void GVNPRE::phi_translate(GVNPRE::ValueTable& VN, std::set<GVNPRE::Expression>& anticIn, BasicBlock* B, std::set<GVNPRE::Expression>& out) { BasicBlock* succ = B->getTerminator()->getSuccessor(0); for (std::set<Expression>::iterator I = anticIn.begin(), E = anticIn.end(); I != E; ++I) { if (I->opcode == 0) { Value *v = I->value; if (PHINode* p = dyn_cast<PHINode>(v)) if (p->getParent() == succ) { out.insert(buildExpression(VN, p->getIncomingValueForBlock(B))); continue; } } //out.insert(*I); } } // Remove all expressions whose operands are not themselves in the set void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<GVNPRE::Expression>& set) { unsigned size = set.size(); unsigned old = 0; while (size != old) { old = size; std::vector<Expression> worklist(set.begin(), set.end()); while (!worklist.empty()) { Expression e = worklist.back(); worklist.pop_back(); if (e.opcode == 0) // OPAQUE continue; bool lhsValid = false; for (std::set<Expression>::iterator I = set.begin(), E = set.end(); I != E; ++I) if (VN[*I] == e.lhs); lhsValid = true; bool rhsValid = false; for (std::set<Expression>::iterator I = set.begin(), E = set.end(); I != E; ++I) if (VN[*I] == e.rhs); rhsValid = true; if (!lhsValid || !rhsValid) set.erase(e); } size = set.size(); } } void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<GVNPRE::Expression>& s) { printf("{ "); for (std::set<Expression>::iterator I = s.begin(), E = s.end(); I != E; ++I) { printf("(%d, %s, value.%d, value.%d) ", I->opcode, I->value == 0 ? "0" : I->value->getName().c_str(), I->lhs, I->rhs); } printf("}\n\n"); } void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Expression>& MS, DominatorTree::Node* DI, std::set<Expression>& currExps, std::set<PHINode*>& currPhis, std::set<Expression>& currTemps, std::set<Expression>& currAvail, std::map<BasicBlock*, std::set<Expression> > availOut) { BasicBlock* BB = DI->getBlock(); // A block inherits AVAIL_OUT from its dominator if (DI->getIDom() != 0) currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(), availOut[DI->getIDom()->getBlock()].end()); for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) { // Handle PHI nodes... if (PHINode* p = dyn_cast<PHINode>(BI)) { add(VN, MS, p); currPhis.insert(p); // Handle binary ops... } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) { Expression leftValue = buildExpression(VN, BO->getOperand(0)); Expression rightValue = buildExpression(VN, BO->getOperand(1)); Expression e = add(VN, MS, BO); currExps.insert(leftValue); currExps.insert(rightValue); currExps.insert(e); currTemps.insert(e); // Handle unsupported ops } else { Expression e = add(VN, MS, BI); currTemps.insert(e); } currAvail.insert(buildExpression(VN, BI)); } } bool GVNPRE::runOnFunction(Function &F) { ValueTable VN; std::set<Expression> maximalSet; std::map<BasicBlock*, std::set<Expression> > generatedExpressions; std::map<BasicBlock*, std::set<PHINode*> > generatedPhis; std::map<BasicBlock*, std::set<Expression> > generatedTemporaries; std::map<BasicBlock*, std::set<Expression> > availableOut; std::map<BasicBlock*, std::set<Expression> > anticipatedIn; DominatorTree &DT = getAnalysis<DominatorTree>(); // First Phase of BuildSets - calculate AVAIL_OUT // Top-down walk of the dominator tree for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()), E = df_end(DT.getRootNode()); DI != E; ++DI) { // Get the sets to update for this block std::set<Expression>& currExps = generatedExpressions[DI->getBlock()]; std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()]; std::set<Expression>& currTemps = generatedTemporaries[DI->getBlock()]; std::set<Expression>& currAvail = availableOut[DI->getBlock()]; CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis, currTemps, currAvail, availableOut); } PostDominatorTree &PDT = getAnalysis<PostDominatorTree>(); // Second Phase of BuildSets - calculate ANTIC_IN bool changed = true; unsigned iterations = 0; while (changed) { changed = false; std::set<Expression> anticOut; // Top-down walk of the postdominator tree for (df_iterator<PostDominatorTree::Node*> PDI = df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode()); PDI != E; ++PDI) { BasicBlock* BB = PDI->getBlock(); std::set<Expression>& anticIn = anticipatedIn[BB]; std::set<Expression> old (anticIn.begin(), anticIn.end()); if (BB->getTerminator()->getNumSuccessors() == 1) { phi_translate(VN, anticIn, BB, anticOut); } else if (BB->getTerminator()->getNumSuccessors() > 1) { for (unsigned i = 0; i < BB->getTerminator()->getNumSuccessors(); ++i) { BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i); std::set<Expression> temp; if (i == 0) temp.insert(maximalSet.begin(), maximalSet.end()); else temp.insert(anticIn.begin(), anticIn.end()); anticIn.clear(); std::insert_iterator<std::set<Expression> > ai_ins(anticIn, anticIn.begin()); std::set_difference(anticipatedIn[currSucc].begin(), anticipatedIn[currSucc].end(), temp.begin(), temp.end(), ai_ins); } } std::set<Expression> S; std::insert_iterator<std::set<Expression> > s_ins(S, S.begin()); std::set_union(anticOut.begin(), anticOut.end(), generatedExpressions[BB].begin(), generatedExpressions[BB].end(), s_ins); anticIn.clear(); std::insert_iterator<std::set<Expression> > antic_ins(anticIn, anticIn.begin()); std::set_difference(S.begin(), S.end(), generatedTemporaries[BB].begin(), generatedTemporaries[BB].end(), antic_ins); clean(VN, anticIn); if (old != anticIn) changed = true; anticOut.clear(); } iterations++; } /* printf("Iterations: %d\n", iterations); for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { printf("Name: "); printf(I->getName().c_str()); printf("\nTMP_GEN: "); dump(VN, generatedTemporaries[I]); printf("\nEXP_GEN: "); dump(VN, generatedExpressions[I]); //printf("\nANTIC_OUT: "); //dump(VN, anticipatedOut[I]); printf("\nANTIC_IN: \n"); dump(VN, anticipatedIn[I]); printf("\n"); } */ return false; } <commit_msg>Add a place where I missed using the maximal set. Note that using the maximal set this way is _SLOW_. Somewhere down the line, I'll look at speeding it up.<commit_after>//===- GVNPRE.cpp - Eliminate redundant values and expressions ------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the Owen Anderson and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass performs a hybrid of global value numbering and partial redundancy // elimination, known as GVN-PRE. It performs partial redundancy elimination on // values, rather than lexical expressions, allowing a more comprehensive view // the optimization. It replaces redundant values with uses of earlier // occurences of the same value. While this is beneficial in that it eliminates // unneeded computation, it also increases register pressure by creating large // live ranges, and should be used with caution on platforms that a very // sensitive to register pressure. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "gvnpre" #include "llvm/Value.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Instructions.h" #include "llvm/Function.h" #include "llvm/Analysis/Dominators.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/ADT/DepthFirstIterator.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Compiler.h" #include <algorithm> #include <map> #include <set> #include <cstdio> using namespace llvm; namespace { class VISIBILITY_HIDDEN GVNPRE : public FunctionPass { bool runOnFunction(Function &F); public: static char ID; // Pass identification, replacement for typeid GVNPRE() : FunctionPass((intptr_t)&ID) { nextValueNumber = 0; } private: uint32_t nextValueNumber; struct Expression { char opcode; Value* value; uint32_t lhs; uint32_t rhs; bool operator<(const Expression& other) const { if (opcode < other.opcode) return true; else if (other.opcode < opcode) return false; if (opcode == 0) { if (value < other.value) return true; else return false; } else { if (lhs < other.lhs) return true; else if (other.lhs < lhs) return true; else if (rhs < other.rhs) return true; else return false; } } bool operator==(const Expression& other) const { if (opcode != other.opcode) return false; if (value != other.value) return false; if (lhs != other.lhs) return false; if (rhs != other.rhs) return false; return true; } }; typedef std::map<Expression, uint32_t> ValueTable; virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<DominatorTree>(); AU.addRequired<PostDominatorTree>(); } // Helper fuctions // FIXME: eliminate or document these better void dump(ValueTable& VN, std::set<Expression>& s); void clean(ValueTable VN, std::set<Expression>& set); Expression add(ValueTable& VN, std::set<Expression>& MS, Instruction* V); ValueTable::iterator lookup(ValueTable& VN, Value* V); Expression buildExpression(ValueTable& VN, Value* V); std::set<Expression>::iterator find_leader(ValueTable VN, std::set<Expression>& vals, uint32_t v); void phi_translate(ValueTable& VN, std::set<Expression>& anticIn, BasicBlock* B, std::set<Expression>& out); // For a given block, calculate the generated expressions, temporaries, // and the AVAIL_OUT set void CalculateAvailOut(ValueTable& VN, std::set<Expression>& MS, DominatorTree::Node* DI, std::set<Expression>& currExps, std::set<PHINode*>& currPhis, std::set<Expression>& currTemps, std::set<Expression>& currAvail, std::map<BasicBlock*, std::set<Expression> > availOut); }; char GVNPRE::ID = 0; } FunctionPass *llvm::createGVNPREPass() { return new GVNPRE(); } RegisterPass<GVNPRE> X("gvnpre", "Global Value Numbering/Partial Redundancy Elimination"); // Given a Value, build an Expression to represent it GVNPRE::Expression GVNPRE::buildExpression(ValueTable& VN, Value* V) { if (Instruction* I = dyn_cast<Instruction>(V)) { Expression e; switch (I->getOpcode()) { case 7: e.opcode = 1; // ADD break; case 8: e.opcode = 2; // SUB break; case 9: e.opcode = 3; // MUL break; case 10: e.opcode = 4; // UDIV break; case 11: e.opcode = 5; // SDIV break; case 12: e.opcode = 6; // FDIV break; case 13: e.opcode = 7; // UREM break; case 14: e.opcode = 8; // SREM break; case 15: e.opcode = 9; // FREM break; default: e.opcode = 0; // OPAQUE e.lhs = 0; e.rhs = 0; e.value = V; return e; } e.value = 0; ValueTable::iterator lhs = lookup(VN, I->getOperand(0)); if (lhs == VN.end()) { Expression lhsExp = buildExpression(VN, I->getOperand(0)); VN.insert(std::make_pair(lhsExp, nextValueNumber)); e.lhs = nextValueNumber; nextValueNumber++; } else e.lhs = lhs->second; ValueTable::iterator rhs = lookup(VN, I->getOperand(1)); if (rhs == VN.end()) { Expression rhsExp = buildExpression(VN, I->getOperand(1)); VN.insert(std::make_pair(rhsExp, nextValueNumber)); e.rhs = nextValueNumber; nextValueNumber++; } else e.rhs = rhs->second; return e; } else { Expression e; e.opcode = 0; e.value = V; e.lhs = 0; e.rhs = 0; return e; } } GVNPRE::Expression GVNPRE::add(ValueTable& VN, std::set<Expression>& MS, Instruction* V) { Expression e = buildExpression(VN, V); if (VN.insert(std::make_pair(e, nextValueNumber)).second) nextValueNumber++; if (e.opcode != 0 || (e.opcode == 0 && isa<PHINode>(e.value))) MS.insert(e); return e; } GVNPRE::ValueTable::iterator GVNPRE::lookup(ValueTable& VN, Value* V) { Expression e = buildExpression(VN, V); return VN.find(e); } std::set<GVNPRE::Expression>::iterator GVNPRE::find_leader(GVNPRE::ValueTable VN, std::set<GVNPRE::Expression>& vals, uint32_t v) { for (std::set<Expression>::iterator I = vals.begin(), E = vals.end(); I != E; ++I) if (VN[*I] == v) return I; return vals.end(); } void GVNPRE::phi_translate(GVNPRE::ValueTable& VN, std::set<GVNPRE::Expression>& anticIn, BasicBlock* B, std::set<GVNPRE::Expression>& out) { BasicBlock* succ = B->getTerminator()->getSuccessor(0); for (std::set<Expression>::iterator I = anticIn.begin(), E = anticIn.end(); I != E; ++I) { if (I->opcode == 0) { Value *v = I->value; if (PHINode* p = dyn_cast<PHINode>(v)) if (p->getParent() == succ) { out.insert(buildExpression(VN, p->getIncomingValueForBlock(B))); continue; } } //out.insert(*I); } } // Remove all expressions whose operands are not themselves in the set void GVNPRE::clean(GVNPRE::ValueTable VN, std::set<GVNPRE::Expression>& set) { unsigned size = set.size(); unsigned old = 0; while (size != old) { old = size; std::vector<Expression> worklist(set.begin(), set.end()); while (!worklist.empty()) { Expression e = worklist.back(); worklist.pop_back(); if (e.opcode == 0) // OPAQUE continue; bool lhsValid = false; for (std::set<Expression>::iterator I = set.begin(), E = set.end(); I != E; ++I) if (VN[*I] == e.lhs); lhsValid = true; bool rhsValid = false; for (std::set<Expression>::iterator I = set.begin(), E = set.end(); I != E; ++I) if (VN[*I] == e.rhs); rhsValid = true; if (!lhsValid || !rhsValid) set.erase(e); } size = set.size(); } } void GVNPRE::dump(GVNPRE::ValueTable& VN, std::set<GVNPRE::Expression>& s) { printf("{ "); for (std::set<Expression>::iterator I = s.begin(), E = s.end(); I != E; ++I) { printf("(%d, %s, value.%d, value.%d) ", I->opcode, I->value == 0 ? "0" : I->value->getName().c_str(), I->lhs, I->rhs); } printf("}\n\n"); } void GVNPRE::CalculateAvailOut(GVNPRE::ValueTable& VN, std::set<Expression>& MS, DominatorTree::Node* DI, std::set<Expression>& currExps, std::set<PHINode*>& currPhis, std::set<Expression>& currTemps, std::set<Expression>& currAvail, std::map<BasicBlock*, std::set<Expression> > availOut) { BasicBlock* BB = DI->getBlock(); // A block inherits AVAIL_OUT from its dominator if (DI->getIDom() != 0) currAvail.insert(availOut[DI->getIDom()->getBlock()].begin(), availOut[DI->getIDom()->getBlock()].end()); for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE; ++BI) { // Handle PHI nodes... if (PHINode* p = dyn_cast<PHINode>(BI)) { add(VN, MS, p); currPhis.insert(p); // Handle binary ops... } else if (BinaryOperator* BO = dyn_cast<BinaryOperator>(BI)) { Expression leftValue = buildExpression(VN, BO->getOperand(0)); Expression rightValue = buildExpression(VN, BO->getOperand(1)); Expression e = add(VN, MS, BO); currExps.insert(leftValue); currExps.insert(rightValue); currExps.insert(e); currTemps.insert(e); // Handle unsupported ops } else { Expression e = add(VN, MS, BI); currTemps.insert(e); } currAvail.insert(buildExpression(VN, BI)); } } bool GVNPRE::runOnFunction(Function &F) { ValueTable VN; std::set<Expression> maximalSet; std::map<BasicBlock*, std::set<Expression> > generatedExpressions; std::map<BasicBlock*, std::set<PHINode*> > generatedPhis; std::map<BasicBlock*, std::set<Expression> > generatedTemporaries; std::map<BasicBlock*, std::set<Expression> > availableOut; std::map<BasicBlock*, std::set<Expression> > anticipatedIn; DominatorTree &DT = getAnalysis<DominatorTree>(); // First Phase of BuildSets - calculate AVAIL_OUT // Top-down walk of the dominator tree for (df_iterator<DominatorTree::Node*> DI = df_begin(DT.getRootNode()), E = df_end(DT.getRootNode()); DI != E; ++DI) { // Get the sets to update for this block std::set<Expression>& currExps = generatedExpressions[DI->getBlock()]; std::set<PHINode*>& currPhis = generatedPhis[DI->getBlock()]; std::set<Expression>& currTemps = generatedTemporaries[DI->getBlock()]; std::set<Expression>& currAvail = availableOut[DI->getBlock()]; CalculateAvailOut(VN, maximalSet, *DI, currExps, currPhis, currTemps, currAvail, availableOut); } PostDominatorTree &PDT = getAnalysis<PostDominatorTree>(); // Second Phase of BuildSets - calculate ANTIC_IN bool changed = true; unsigned iterations = 0; while (changed) { changed = false; std::set<Expression> anticOut; // Top-down walk of the postdominator tree for (df_iterator<PostDominatorTree::Node*> PDI = df_begin(PDT.getRootNode()), E = df_end(DT.getRootNode()); PDI != E; ++PDI) { BasicBlock* BB = PDI->getBlock(); std::set<Expression>& anticIn = anticipatedIn[BB]; std::set<Expression> old (anticIn.begin(), anticIn.end()); if (BB->getTerminator()->getNumSuccessors() == 1) { phi_translate(VN, maximalSet, BB, anticOut); } else if (BB->getTerminator()->getNumSuccessors() > 1) { for (unsigned i = 0; i < BB->getTerminator()->getNumSuccessors(); ++i) { BasicBlock* currSucc = BB->getTerminator()->getSuccessor(i); std::set<Expression> temp; if (i == 0) temp.insert(maximalSet.begin(), maximalSet.end()); else temp.insert(anticIn.begin(), anticIn.end()); anticIn.clear(); std::insert_iterator<std::set<Expression> > ai_ins(anticIn, anticIn.begin()); std::set_difference(anticipatedIn[currSucc].begin(), anticipatedIn[currSucc].end(), temp.begin(), temp.end(), ai_ins); } } std::set<Expression> S; std::insert_iterator<std::set<Expression> > s_ins(S, S.begin()); std::set_union(anticOut.begin(), anticOut.end(), generatedExpressions[BB].begin(), generatedExpressions[BB].end(), s_ins); anticIn.clear(); std::insert_iterator<std::set<Expression> > antic_ins(anticIn, anticIn.begin()); std::set_difference(S.begin(), S.end(), generatedTemporaries[BB].begin(), generatedTemporaries[BB].end(), antic_ins); clean(VN, anticIn); if (old != anticIn) changed = true; anticOut.clear(); } iterations++; } printf("Iterations: %d\n", iterations); for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { printf("Name: "); printf(I->getName().c_str()); printf("\nTMP_GEN: "); dump(VN, generatedTemporaries[I]); printf("\nEXP_GEN: "); dump(VN, generatedExpressions[I]); //printf("\nANTIC_OUT: "); //dump(VN, anticipatedOut[I]); printf("\nANTIC_IN: \n"); dump(VN, anticipatedIn[I]); printf("\n"); } return false; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: transobj.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2004-06-04 11:43:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_TRANSOBJ_HXX #define SC_TRANSOBJ_HXX #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif #ifndef _EMBOBJ_HXX #include <so3/embobj.hxx> #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif class ScDocShell; class ScMarkData; namespace com { namespace sun { namespace star { namespace sheet { class XSheetCellRanges; } }}} class ScTransferObj : public TransferableHelper { private: ScDocument* pDoc; ScRange aBlock; SCROW nNonFiltered; // non-filtered rows TransferableDataHelper aOleData; TransferableObjectDescriptor aObjDesc; SvEmbeddedObjectRef aDocShellRef; SvEmbeddedObjectRef aDrawPersistRef; com::sun::star::uno::Reference<com::sun::star::sheet::XSheetCellRanges> xDragSourceRanges; SCCOL nDragHandleX; SCROW nDragHandleY; SCTAB nVisibleTab; USHORT nDragSourceFlags; BOOL bDragWasInternal; BOOL bUsedForLink; void InitDocShell(); static void StripRefs( ScDocument* pDoc, SCCOL nStartX, SCROW nStartY, SCCOL nEndX, SCROW nEndY, ScDocument* pDestDoc=0, SCCOL nSubX=0, SCROW nSubY=0 ); static void PaintToDev( OutputDevice* pDev, ScDocument* pDoc, double nPrintFactor, const ScRange& rBlock, BOOL bMetaFile ); static void GetAreaSize( ScDocument* pDoc, SCTAB nTab1, SCTAB nTab2, SCROW& nRow, SCCOL& nCol ); public: ScTransferObj( ScDocument* pClipDoc, const TransferableObjectDescriptor& rDesc ); virtual ~ScTransferObj(); virtual void AddSupportedFormats(); virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual void ObjectReleased(); virtual void DragFinished( sal_Int8 nDropAction ); ScDocument* GetDocument() { return pDoc; } // owned by ScTransferObj const ScRange& GetRange() const { return aBlock; } SCROW GetNonFilteredRows() const { return nNonFiltered; } SCCOL GetDragHandleX() const { return nDragHandleX; } SCROW GetDragHandleY() const { return nDragHandleY; } SCTAB GetVisibleTab() const { return nVisibleTab; } USHORT GetDragSourceFlags() const { return nDragSourceFlags; } ScDocShell* GetSourceDocShell(); ScDocument* GetSourceDocument(); ScMarkData GetSourceMarkData(); void SetDrawPersist( const SvEmbeddedObjectRef& rRef ); void SetDragHandlePos( SCCOL nX, SCROW nY ); void SetVisibleTab( SCTAB nNew ); void SetDragSource( ScDocShell* pSourceShell, const ScMarkData& rMark ); void SetDragSourceFlags( USHORT nFlags ); void SetDragWasInternal(); static ScTransferObj* GetOwnClipboard( Window* pUIWin ); static SvPersist* SetDrawClipDoc( BOOL bAnyOle ); // update ScGlobal::pDrawClipDocShellRef }; #endif <commit_msg>INTEGRATION: CWS mav09 (1.11.416); FILE MERGED 2004/07/09 02:42:07 mav 1.11.416.3: RESYNC: (1.11-1.12); FILE MERGED 2004/05/04 14:01:49 mba 1.11.416.2: #i27773#: remove so3 2004/04/29 08:57:07 mav 1.11.416.1: #i27773# one more step further<commit_after>/************************************************************************* * * $RCSfile: transobj.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2004-10-04 20:18:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_TRANSOBJ_HXX #define SC_TRANSOBJ_HXX #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif //REMOVE #ifndef _EMBOBJ_HXX //REMOVE #include <so3/embobj.hxx> //REMOVE #endif #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif #ifndef SC_ADDRESS_HXX #include "address.hxx" #endif class ScDocShell; class ScMarkData; class SfxObjectShell; namespace com { namespace sun { namespace star { namespace sheet { class XSheetCellRanges; } }}} #include <sfx2/objsh.hxx> class ScTransferObj : public TransferableHelper { private: ScDocument* pDoc; ScRange aBlock; SCROW nNonFiltered; // non-filtered rows TransferableDataHelper aOleData; TransferableObjectDescriptor aObjDesc; //REMOVE SvEmbeddedObjectRef aDocShellRef; //REMOVE SvEmbeddedObjectRef aDrawPersistRef; SfxObjectShellRef aDocShellRef; SfxObjectShellRef aDrawPersistRef; com::sun::star::uno::Reference<com::sun::star::sheet::XSheetCellRanges> xDragSourceRanges; SCCOL nDragHandleX; SCROW nDragHandleY; SCTAB nVisibleTab; USHORT nDragSourceFlags; BOOL bDragWasInternal; BOOL bUsedForLink; void InitDocShell(); static void StripRefs( ScDocument* pDoc, SCCOL nStartX, SCROW nStartY, SCCOL nEndX, SCROW nEndY, ScDocument* pDestDoc=0, SCCOL nSubX=0, SCROW nSubY=0 ); static void PaintToDev( OutputDevice* pDev, ScDocument* pDoc, double nPrintFactor, const ScRange& rBlock, BOOL bMetaFile ); static void GetAreaSize( ScDocument* pDoc, SCTAB nTab1, SCTAB nTab2, SCROW& nRow, SCCOL& nCol ); public: ScTransferObj( ScDocument* pClipDoc, const TransferableObjectDescriptor& rDesc ); virtual ~ScTransferObj(); virtual void AddSupportedFormats(); virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual void ObjectReleased(); virtual void DragFinished( sal_Int8 nDropAction ); ScDocument* GetDocument() { return pDoc; } // owned by ScTransferObj const ScRange& GetRange() const { return aBlock; } SCROW GetNonFilteredRows() const { return nNonFiltered; } SCCOL GetDragHandleX() const { return nDragHandleX; } SCROW GetDragHandleY() const { return nDragHandleY; } SCTAB GetVisibleTab() const { return nVisibleTab; } USHORT GetDragSourceFlags() const { return nDragSourceFlags; } ScDocShell* GetSourceDocShell(); ScDocument* GetSourceDocument(); ScMarkData GetSourceMarkData(); void SetDrawPersist( const SfxObjectShellRef& rRef ); void SetDragHandlePos( SCCOL nX, SCROW nY ); void SetVisibleTab( SCTAB nNew ); void SetDragSource( ScDocShell* pSourceShell, const ScMarkData& rMark ); void SetDragSourceFlags( USHORT nFlags ); void SetDragWasInternal(); static ScTransferObj* GetOwnClipboard( Window* pUIWin ); static SfxObjectShell* SetDrawClipDoc( BOOL bAnyOle ); // update ScGlobal::pDrawClipDocShellRef }; #endif <|endoftext|>
<commit_before>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2014 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LCB_BOOTSTRAP_DEFINE_STRUCT 1 #include "internal.h" #define LOGARGS(instance, lvl) instance->settings, "bootstrap", LCB_LOG_##lvl, __FILE__, __LINE__ using lcb::clconfig::EventType; using lcb::clconfig::ConfigInfo; using namespace lcb; /** * This function is where the configuration actually takes place. We ensure * in other functions that this is only ever called directly from an event * loop stack frame (or one of the small mini functions here) so that we * don't accidentally end up destroying resources underneath us. */ void Bootstrap::config_callback(EventType event, ConfigInfo *info) { using namespace lcb::clconfig; lcb_t instance = parent; if (event != CLCONFIG_EVENT_GOT_NEW_CONFIG) { if (event == CLCONFIG_EVENT_PROVIDERS_CYCLED) { if (!LCBT_VBCONFIG(instance)) { initial_error(LCB_ERROR, "No more bootstrap providers remain"); } } return; } instance->last_error = LCB_SUCCESS; /** Ensure we're not called directly twice again */ if (state < S_INITIAL_TRIGGERED) { state = S_INITIAL_TRIGGERED; } tm.cancel(); lcb_log(LOGARGS(instance, DEBUG), "Instance configured"); if (info->get_origin() != CLCONFIG_FILE) { /* Set the timestamp for the current config to control throttling, * but only if it's not an initial file-based config. See CCBC-482 */ last_refresh = gethrtime(); errcounter = 0; } if (info->get_origin() == CLCONFIG_CCCP) { /* Disable HTTP provider if we've received something via CCCP */ if (instance->cur_configinfo == NULL || instance->cur_configinfo->get_origin() != CLCONFIG_HTTP) { /* Never disable HTTP if it's still being used */ instance->confmon->set_active(CLCONFIG_HTTP, false); } } if (instance->type == LCB_TYPE_CLUSTER && info->get_origin() == CLCONFIG_CLADMIN) { /* Disable HTTP provider for management operations, and fallback to static */ if (instance->cur_configinfo == NULL || instance->cur_configinfo->get_origin() != CLCONFIG_HTTP) { instance->confmon->set_active(CLCONFIG_HTTP, false); } } if (instance->type != LCB_TYPE_CLUSTER) { lcb_update_vbconfig(instance, info); } if (state < S_BOOTSTRAPPED) { state = S_BOOTSTRAPPED; lcb_aspend_del(&instance->pendops, LCB_PENDTYPE_COUNTER, NULL); if (instance->type == LCB_TYPE_BUCKET) { if (LCBVB_DISTTYPE(LCBT_VBCONFIG(instance)) == LCBVB_DIST_KETAMA && instance->cur_configinfo->get_origin() != CLCONFIG_MCRAW) { lcb_log(LOGARGS(instance, INFO), "Reverting to HTTP Config for memcached buckets"); instance->settings->bc_http_stream_time = -1; instance->confmon->set_active(CLCONFIG_HTTP, true); instance->confmon->set_active(CLCONFIG_CCCP, false); } /* infer bucket type using distribution and capabilities set */ switch (LCBVB_DISTTYPE(LCBT_VBCONFIG(instance))) { case LCBVB_DIST_VBUCKET: if (LCBVB_CAPS(LCBT_VBCONFIG(instance)) & LCBVB_CAP_COUCHAPI) { instance->btype = LCB_BTYPE_COUCHBASE; } else { instance->btype = LCB_BTYPE_EPHEMERAL; } break; case LCBVB_DIST_KETAMA: instance->btype = LCB_BTYPE_MEMCACHED; break; } } instance->callbacks.bootstrap(instance, LCB_SUCCESS); // See if we can enable background polling. check_bgpoll(); } lcb_maybe_breakout(instance); } void Bootstrap::clconfig_lsn(EventType e, ConfigInfo *i) { if (state == S_INITIAL_PRE) { config_callback(e, i); } else if (e == clconfig::CLCONFIG_EVENT_GOT_NEW_CONFIG) { lcb_log(LOGARGS(parent, INFO), "Got new config. Will refresh asynchronously"); tm.signal(); } } void Bootstrap::check_bgpoll() { if (parent->cur_configinfo == NULL || parent->cur_configinfo->get_origin() != lcb::clconfig::CLCONFIG_CCCP || LCBT_SETTING(parent, config_poll_interval) == 0) { tmpoll.cancel(); } else { tmpoll.rearm(LCBT_SETTING(parent, config_poll_interval)); } } void Bootstrap::bgpoll() { lcb_log(LOGARGS(parent, TRACE), "Background-polling for new configuration"); bootstrap(BS_REFRESH_THROTTLE); check_bgpoll(); } /** * This it the initial bootstrap timeout handler. This timeout pins down the * instance. It is only scheduled during the initial bootstrap and is only * triggered if the initial bootstrap fails to configure in time. */ void Bootstrap::timer_dispatch() { if (state > S_INITIAL_PRE) { config_callback(clconfig::CLCONFIG_EVENT_GOT_NEW_CONFIG, parent->confmon->get_config()); } else { // Not yet bootstrapped! initial_error(LCB_ETIMEDOUT, "Failed to bootstrap in time"); } } void Bootstrap::initial_error(lcb_error_t err, const char *errinfo) { parent->last_error = parent->confmon->get_last_error(); if (parent->last_error == LCB_SUCCESS) { parent->last_error = err; } parent->callbacks.error(parent, parent->last_error, errinfo); lcb_log(LOGARGS(parent, ERR), "Failed to bootstrap client=%p. Error=%s, Message=%s", (void *)parent, lcb_strerror_short(parent->last_error), errinfo); tm.cancel(); parent->callbacks.bootstrap(parent, parent->last_error); lcb_aspend_del(&parent->pendops, LCB_PENDTYPE_COUNTER, NULL); lcb_maybe_breakout(parent); } Bootstrap::Bootstrap(lcb_t instance) : parent(instance), tm(parent->iotable, this), tmpoll(parent->iotable, this), last_refresh(0), errcounter(0), state(S_INITIAL_PRE) { parent->confmon->add_listener(this); } lcb_error_t Bootstrap::bootstrap(unsigned options) { hrtime_t now = gethrtime(); if (parent->confmon->is_refreshing()) { return LCB_SUCCESS; } if (options & BS_REFRESH_THROTTLE) { /* Refresh throttle requested. This is not true if options == ALWAYS */ hrtime_t next_ts; unsigned errthresh = LCBT_SETTING(parent, weird_things_threshold); if (options & BS_REFRESH_INCRERR) { errcounter++; } next_ts = last_refresh; next_ts += LCB_US2NS(LCBT_SETTING(parent, weird_things_delay)); if (now < next_ts && errcounter < errthresh) { lcb_log(LOGARGS(parent, INFO), "Not requesting a config refresh because of throttling parameters. Next refresh possible in %ums or %u errors. " "See LCB_CNTL_CONFDELAY_THRESH and LCB_CNTL_CONFERRTHRESH to modify the throttling settings", LCB_NS2US(next_ts-now)/1000, (unsigned)errthresh-errcounter); return LCB_SUCCESS; } } if (options == BS_REFRESH_INITIAL) { state = S_INITIAL_PRE; parent->confmon->prepare(); tm.rearm(LCBT_SETTING(parent, config_timeout)); lcb_aspend_add(&parent->pendops, LCB_PENDTYPE_COUNTER, NULL); } /* Reset the counters */ errcounter = 0; if (options != BS_REFRESH_INITIAL) { last_refresh = now; } parent->confmon->start(); return LCB_SUCCESS; } Bootstrap::~Bootstrap() { tm.release(); parent->confmon->remove_listener(this); } LIBCOUCHBASE_API lcb_error_t lcb_get_bootstrap_status(lcb_t instance) { if (instance->cur_configinfo) { return LCB_SUCCESS; } if (instance->last_error != LCB_SUCCESS) { return instance->last_error; } if (instance->type == LCB_TYPE_CLUSTER) { if (lcb::clconfig::http_get_conn(instance->confmon) != NULL || instance->confmon->get_config() != NULL) { return LCB_SUCCESS; } } return LCB_ERROR; } LIBCOUCHBASE_API void lcb_refresh_config(lcb_t instance) { instance->bootstrap(BS_REFRESH_ALWAYS); } <commit_msg>CCBC-829: Background configuration polling should not be throttled<commit_after>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2014 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LCB_BOOTSTRAP_DEFINE_STRUCT 1 #include "internal.h" #define LOGARGS(instance, lvl) instance->settings, "bootstrap", LCB_LOG_##lvl, __FILE__, __LINE__ using lcb::clconfig::EventType; using lcb::clconfig::ConfigInfo; using namespace lcb; /** * This function is where the configuration actually takes place. We ensure * in other functions that this is only ever called directly from an event * loop stack frame (or one of the small mini functions here) so that we * don't accidentally end up destroying resources underneath us. */ void Bootstrap::config_callback(EventType event, ConfigInfo *info) { using namespace lcb::clconfig; lcb_t instance = parent; if (event != CLCONFIG_EVENT_GOT_NEW_CONFIG) { if (event == CLCONFIG_EVENT_PROVIDERS_CYCLED) { if (!LCBT_VBCONFIG(instance)) { initial_error(LCB_ERROR, "No more bootstrap providers remain"); } } return; } instance->last_error = LCB_SUCCESS; /** Ensure we're not called directly twice again */ if (state < S_INITIAL_TRIGGERED) { state = S_INITIAL_TRIGGERED; } tm.cancel(); lcb_log(LOGARGS(instance, DEBUG), "Instance configured"); if (info->get_origin() != CLCONFIG_FILE) { /* Set the timestamp for the current config to control throttling, * but only if it's not an initial file-based config. See CCBC-482 */ last_refresh = gethrtime(); errcounter = 0; } if (info->get_origin() == CLCONFIG_CCCP) { /* Disable HTTP provider if we've received something via CCCP */ if (instance->cur_configinfo == NULL || instance->cur_configinfo->get_origin() != CLCONFIG_HTTP) { /* Never disable HTTP if it's still being used */ instance->confmon->set_active(CLCONFIG_HTTP, false); } } if (instance->type == LCB_TYPE_CLUSTER && info->get_origin() == CLCONFIG_CLADMIN) { /* Disable HTTP provider for management operations, and fallback to static */ if (instance->cur_configinfo == NULL || instance->cur_configinfo->get_origin() != CLCONFIG_HTTP) { instance->confmon->set_active(CLCONFIG_HTTP, false); } } if (instance->type != LCB_TYPE_CLUSTER) { lcb_update_vbconfig(instance, info); } if (state < S_BOOTSTRAPPED) { state = S_BOOTSTRAPPED; lcb_aspend_del(&instance->pendops, LCB_PENDTYPE_COUNTER, NULL); if (instance->type == LCB_TYPE_BUCKET) { if (LCBVB_DISTTYPE(LCBT_VBCONFIG(instance)) == LCBVB_DIST_KETAMA && instance->cur_configinfo->get_origin() != CLCONFIG_MCRAW) { lcb_log(LOGARGS(instance, INFO), "Reverting to HTTP Config for memcached buckets"); instance->settings->bc_http_stream_time = -1; instance->confmon->set_active(CLCONFIG_HTTP, true); instance->confmon->set_active(CLCONFIG_CCCP, false); } /* infer bucket type using distribution and capabilities set */ switch (LCBVB_DISTTYPE(LCBT_VBCONFIG(instance))) { case LCBVB_DIST_VBUCKET: if (LCBVB_CAPS(LCBT_VBCONFIG(instance)) & LCBVB_CAP_COUCHAPI) { instance->btype = LCB_BTYPE_COUCHBASE; } else { instance->btype = LCB_BTYPE_EPHEMERAL; } break; case LCBVB_DIST_KETAMA: instance->btype = LCB_BTYPE_MEMCACHED; break; } } instance->callbacks.bootstrap(instance, LCB_SUCCESS); // See if we can enable background polling. check_bgpoll(); } lcb_maybe_breakout(instance); } void Bootstrap::clconfig_lsn(EventType e, ConfigInfo *i) { if (state == S_INITIAL_PRE) { config_callback(e, i); } else if (e == clconfig::CLCONFIG_EVENT_GOT_NEW_CONFIG) { lcb_log(LOGARGS(parent, INFO), "Got new config. Will refresh asynchronously"); tm.signal(); } } void Bootstrap::check_bgpoll() { if (parent->cur_configinfo == NULL || parent->cur_configinfo->get_origin() != lcb::clconfig::CLCONFIG_CCCP || LCBT_SETTING(parent, config_poll_interval) == 0) { tmpoll.cancel(); } else { tmpoll.rearm(LCBT_SETTING(parent, config_poll_interval)); } } void Bootstrap::bgpoll() { lcb_log(LOGARGS(parent, TRACE), "Background-polling for new configuration"); bootstrap(BS_REFRESH_ALWAYS); check_bgpoll(); } /** * This it the initial bootstrap timeout handler. This timeout pins down the * instance. It is only scheduled during the initial bootstrap and is only * triggered if the initial bootstrap fails to configure in time. */ void Bootstrap::timer_dispatch() { if (state > S_INITIAL_PRE) { config_callback(clconfig::CLCONFIG_EVENT_GOT_NEW_CONFIG, parent->confmon->get_config()); } else { // Not yet bootstrapped! initial_error(LCB_ETIMEDOUT, "Failed to bootstrap in time"); } } void Bootstrap::initial_error(lcb_error_t err, const char *errinfo) { parent->last_error = parent->confmon->get_last_error(); if (parent->last_error == LCB_SUCCESS) { parent->last_error = err; } parent->callbacks.error(parent, parent->last_error, errinfo); lcb_log(LOGARGS(parent, ERR), "Failed to bootstrap client=%p. Error=%s, Message=%s", (void *)parent, lcb_strerror_short(parent->last_error), errinfo); tm.cancel(); parent->callbacks.bootstrap(parent, parent->last_error); lcb_aspend_del(&parent->pendops, LCB_PENDTYPE_COUNTER, NULL); lcb_maybe_breakout(parent); } Bootstrap::Bootstrap(lcb_t instance) : parent(instance), tm(parent->iotable, this), tmpoll(parent->iotable, this), last_refresh(0), errcounter(0), state(S_INITIAL_PRE) { parent->confmon->add_listener(this); } lcb_error_t Bootstrap::bootstrap(unsigned options) { hrtime_t now = gethrtime(); if (parent->confmon->is_refreshing()) { return LCB_SUCCESS; } if (options & BS_REFRESH_THROTTLE) { /* Refresh throttle requested. This is not true if options == ALWAYS */ hrtime_t next_ts; unsigned errthresh = LCBT_SETTING(parent, weird_things_threshold); if (options & BS_REFRESH_INCRERR) { errcounter++; } next_ts = last_refresh; next_ts += LCB_US2NS(LCBT_SETTING(parent, weird_things_delay)); if (now < next_ts && errcounter < errthresh) { lcb_log(LOGARGS(parent, INFO), "Not requesting a config refresh because of throttling parameters. Next refresh possible in %ums or %u errors. " "See LCB_CNTL_CONFDELAY_THRESH and LCB_CNTL_CONFERRTHRESH to modify the throttling settings", LCB_NS2US(next_ts-now)/1000, (unsigned)errthresh-errcounter); return LCB_SUCCESS; } } if (options == BS_REFRESH_INITIAL) { state = S_INITIAL_PRE; parent->confmon->prepare(); tm.rearm(LCBT_SETTING(parent, config_timeout)); lcb_aspend_add(&parent->pendops, LCB_PENDTYPE_COUNTER, NULL); } /* Reset the counters */ errcounter = 0; if (options != BS_REFRESH_INITIAL) { last_refresh = now; } parent->confmon->start(); return LCB_SUCCESS; } Bootstrap::~Bootstrap() { tm.release(); parent->confmon->remove_listener(this); } LIBCOUCHBASE_API lcb_error_t lcb_get_bootstrap_status(lcb_t instance) { if (instance->cur_configinfo) { return LCB_SUCCESS; } if (instance->last_error != LCB_SUCCESS) { return instance->last_error; } if (instance->type == LCB_TYPE_CLUSTER) { if (lcb::clconfig::http_get_conn(instance->confmon) != NULL || instance->confmon->get_config() != NULL) { return LCB_SUCCESS; } } return LCB_ERROR; } LIBCOUCHBASE_API void lcb_refresh_config(lcb_t instance) { instance->bootstrap(BS_REFRESH_ALWAYS); } <|endoftext|>
<commit_before>//===-- ConnectionMachPort.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #if defined(__APPLE__) #include "lldb/Core/ConnectionMachPort.h" // C Includes #include <mach/mach.h> #include <servers/bootstrap.h> // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/Communication.h" #include "lldb/Core/Log.h" using namespace lldb; using namespace lldb_private; struct MessageType { mach_msg_header_t head; ConnectionMachPort::PayloadType payload; }; ConnectionMachPort::ConnectionMachPort () : Connection(), m_task(mach_task_self()), m_port(MACH_PORT_TYPE_NONE) { } ConnectionMachPort::~ConnectionMachPort () { Disconnect (NULL); } bool ConnectionMachPort::IsConnected () const { return m_port != MACH_PORT_TYPE_NONE; } ConnectionStatus ConnectionMachPort::Connect (const char *s, Error *error_ptr) { if (IsConnected()) { if (error_ptr) error_ptr->SetErrorString ("already connected"); return eConnectionStatusError; } if (s == NULL || s[0] == '\0') { if (error_ptr) error_ptr->SetErrorString ("empty connect URL"); return eConnectionStatusError; } ConnectionStatus status = eConnectionStatusError; if (strncmp (s, "bootstrap-checkin://", strlen("bootstrap-checkin://"))) { s += strlen("bootstrap-checkin://"); if (*s) { status = BootstrapCheckIn (s, error_ptr); } else { if (error_ptr) error_ptr->SetErrorString ("bootstrap port name is empty"); } } else if (strncmp (s, "bootstrap-lookup://", strlen("bootstrap-lookup://"))) { s += strlen("bootstrap-lookup://"); if (*s) { status = BootstrapLookup (s, error_ptr); } else { if (error_ptr) error_ptr->SetErrorString ("bootstrap port name is empty"); } } else { if (error_ptr) error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s); } if (status == eConnectionStatusSuccess) { if (error_ptr) error_ptr->Clear(); m_uri.assign(s); } else { Disconnect(NULL); } return status; } ConnectionStatus ConnectionMachPort::BootstrapCheckIn (const char *port, Error *error_ptr) { mach_port_t bootstrap_port = MACH_PORT_TYPE_NONE; /* Getting bootstrap server port */ kern_return_t kret = task_get_bootstrap_port(mach_task_self(), &bootstrap_port); if (kret == KERN_SUCCESS) { name_t port_name; int len = snprintf(port_name, sizeof(port_name), "%s", port); if (static_cast<size_t>(len) < sizeof(port_name)) { kret = ::bootstrap_check_in (bootstrap_port, port_name, &m_port); } else { Disconnect(NULL); if (error_ptr) error_ptr->SetErrorString ("bootstrap is too long"); return eConnectionStatusError; } } if (kret != KERN_SUCCESS) { Disconnect(NULL); if (error_ptr) error_ptr->SetError (kret, eErrorTypeMachKernel); return eConnectionStatusError; } return eConnectionStatusSuccess; } lldb::ConnectionStatus ConnectionMachPort::BootstrapLookup (const char *port, Error *error_ptr) { name_t port_name; if (port && port[0]) { if (static_cast<size_t>(::snprintf (port_name, sizeof (port_name), "%s", port)) >= sizeof (port_name)) { if (error_ptr) error_ptr->SetErrorString ("port netname is too long"); return eConnectionStatusError; } } else { if (error_ptr) error_ptr->SetErrorString ("empty port netname"); return eConnectionStatusError; } mach_port_t bootstrap_port = MACH_PORT_TYPE_NONE; /* Getting bootstrap server port */ kern_return_t kret = task_get_bootstrap_port(mach_task_self(), &bootstrap_port); if (kret == KERN_SUCCESS) { kret = ::bootstrap_look_up (bootstrap_port, port_name, &m_port); } if (kret != KERN_SUCCESS) { if (error_ptr) error_ptr->SetError (kret, eErrorTypeMachKernel); return eConnectionStatusError; } return eConnectionStatusSuccess; } ConnectionStatus ConnectionMachPort::Disconnect (Error *error_ptr) { kern_return_t kret; // TODO: verify if we need to netname_check_out for // either or both if (m_port != MACH_PORT_TYPE_NONE) { kret = ::mach_port_deallocate (m_task, m_port); if (error_ptr) error_ptr->SetError (kret, eErrorTypeMachKernel); m_port = MACH_PORT_TYPE_NONE; } m_uri.clear(); return eConnectionStatusSuccess; } size_t ConnectionMachPort::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr) { PayloadType payload; kern_return_t kret = Receive (payload); if (kret == KERN_SUCCESS) { memcpy (dst, payload.data, payload.data_length); status = eConnectionStatusSuccess; return payload.data_length; } if (error_ptr) error_ptr->SetError (kret, eErrorTypeMachKernel); status = eConnectionStatusError; return 0; } size_t ConnectionMachPort::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) { PayloadType payload; payload.command = 0; payload.data_length = src_len; const size_t max_payload_size = sizeof(payload.data); if (src_len > max_payload_size) payload.data_length = max_payload_size; memcpy (payload.data, src, payload.data_length); if (Send (payload) == KERN_SUCCESS) { status = eConnectionStatusSuccess; return payload.data_length; } status = eConnectionStatusError; return 0; } std::string ConnectionMachPort::GetURI() { return m_uri; } ConnectionStatus ConnectionMachPort::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) { return eConnectionStatusLostConnection; } kern_return_t ConnectionMachPort::Send (const PayloadType &payload) { struct MessageType message; /* (i) Form the message : */ /* (i.a) Fill the header fields : */ message.head.msgh_bits = MACH_MSGH_BITS_REMOTE (MACH_MSG_TYPE_MAKE_SEND) | MACH_MSGH_BITS_OTHER (MACH_MSGH_BITS_COMPLEX); message.head.msgh_size = sizeof(MessageType); message.head.msgh_local_port = MACH_PORT_NULL; message.head.msgh_remote_port = m_port; /* (i.b) Explain the message type ( an integer ) */ // message.type.msgt_name = MACH_MSG_TYPE_INTEGER_32; // message.type.msgt_size = 32; // message.type.msgt_number = 1; // message.type.msgt_inline = TRUE; // message.type.msgt_longform = FALSE; // message.type.msgt_deallocate = FALSE; /* message.type.msgt_unused = 0; */ /* not needed, I think */ /* (i.c) Fill the message with the given integer : */ message.payload = payload; /* (ii) Send the message : */ kern_return_t kret = ::mach_msg (&message.head, MACH_SEND_MSG, message.head.msgh_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); return kret; } kern_return_t ConnectionMachPort::Receive (PayloadType &payload) { MessageType message; message.head.msgh_size = sizeof(MessageType); kern_return_t kret = ::mach_msg (&message.head, MACH_RCV_MSG, 0, sizeof(MessageType), m_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kret == KERN_SUCCESS) payload = message.payload; return kret; } #endif // #if defined(__APPLE__) <commit_msg>I make no claims that Mach ports work, but at least we should check the right thing<commit_after>//===-- ConnectionMachPort.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #if defined(__APPLE__) #include "lldb/Core/ConnectionMachPort.h" // C Includes #include <mach/mach.h> #include <servers/bootstrap.h> // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Core/Communication.h" #include "lldb/Core/Log.h" using namespace lldb; using namespace lldb_private; struct MessageType { mach_msg_header_t head; ConnectionMachPort::PayloadType payload; }; ConnectionMachPort::ConnectionMachPort () : Connection(), m_task(mach_task_self()), m_port(MACH_PORT_TYPE_NONE) { } ConnectionMachPort::~ConnectionMachPort () { Disconnect (NULL); } bool ConnectionMachPort::IsConnected () const { return m_port != MACH_PORT_TYPE_NONE; } ConnectionStatus ConnectionMachPort::Connect (const char *s, Error *error_ptr) { if (IsConnected()) { if (error_ptr) error_ptr->SetErrorString ("already connected"); return eConnectionStatusError; } if (s == NULL || s[0] == '\0') { if (error_ptr) error_ptr->SetErrorString ("empty connect URL"); return eConnectionStatusError; } ConnectionStatus status = eConnectionStatusError; if (0 == strncmp (s, "bootstrap-checkin://", strlen("bootstrap-checkin://"))) { s += strlen("bootstrap-checkin://"); if (*s) { status = BootstrapCheckIn (s, error_ptr); } else { if (error_ptr) error_ptr->SetErrorString ("bootstrap port name is empty"); } } else if (0 == strncmp (s, "bootstrap-lookup://", strlen("bootstrap-lookup://"))) { s += strlen("bootstrap-lookup://"); if (*s) { status = BootstrapLookup (s, error_ptr); } else { if (error_ptr) error_ptr->SetErrorString ("bootstrap port name is empty"); } } else { if (error_ptr) error_ptr->SetErrorStringWithFormat ("unsupported connection URL: '%s'", s); } if (status == eConnectionStatusSuccess) { if (error_ptr) error_ptr->Clear(); m_uri.assign(s); } else { Disconnect(NULL); } return status; } ConnectionStatus ConnectionMachPort::BootstrapCheckIn (const char *port, Error *error_ptr) { mach_port_t bootstrap_port = MACH_PORT_TYPE_NONE; /* Getting bootstrap server port */ kern_return_t kret = task_get_bootstrap_port(mach_task_self(), &bootstrap_port); if (kret == KERN_SUCCESS) { name_t port_name; int len = snprintf(port_name, sizeof(port_name), "%s", port); if (static_cast<size_t>(len) < sizeof(port_name)) { kret = ::bootstrap_check_in (bootstrap_port, port_name, &m_port); } else { Disconnect(NULL); if (error_ptr) error_ptr->SetErrorString ("bootstrap is too long"); return eConnectionStatusError; } } if (kret != KERN_SUCCESS) { Disconnect(NULL); if (error_ptr) error_ptr->SetError (kret, eErrorTypeMachKernel); return eConnectionStatusError; } return eConnectionStatusSuccess; } lldb::ConnectionStatus ConnectionMachPort::BootstrapLookup (const char *port, Error *error_ptr) { name_t port_name; if (port && port[0]) { if (static_cast<size_t>(::snprintf (port_name, sizeof (port_name), "%s", port)) >= sizeof (port_name)) { if (error_ptr) error_ptr->SetErrorString ("port netname is too long"); return eConnectionStatusError; } } else { if (error_ptr) error_ptr->SetErrorString ("empty port netname"); return eConnectionStatusError; } mach_port_t bootstrap_port = MACH_PORT_TYPE_NONE; /* Getting bootstrap server port */ kern_return_t kret = task_get_bootstrap_port(mach_task_self(), &bootstrap_port); if (kret == KERN_SUCCESS) { kret = ::bootstrap_look_up (bootstrap_port, port_name, &m_port); } if (kret != KERN_SUCCESS) { if (error_ptr) error_ptr->SetError (kret, eErrorTypeMachKernel); return eConnectionStatusError; } return eConnectionStatusSuccess; } ConnectionStatus ConnectionMachPort::Disconnect (Error *error_ptr) { kern_return_t kret; // TODO: verify if we need to netname_check_out for // either or both if (m_port != MACH_PORT_TYPE_NONE) { kret = ::mach_port_deallocate (m_task, m_port); if (error_ptr) error_ptr->SetError (kret, eErrorTypeMachKernel); m_port = MACH_PORT_TYPE_NONE; } m_uri.clear(); return eConnectionStatusSuccess; } size_t ConnectionMachPort::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr) { PayloadType payload; kern_return_t kret = Receive (payload); if (kret == KERN_SUCCESS) { memcpy (dst, payload.data, payload.data_length); status = eConnectionStatusSuccess; return payload.data_length; } if (error_ptr) error_ptr->SetError (kret, eErrorTypeMachKernel); status = eConnectionStatusError; return 0; } size_t ConnectionMachPort::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) { PayloadType payload; payload.command = 0; payload.data_length = src_len; const size_t max_payload_size = sizeof(payload.data); if (src_len > max_payload_size) payload.data_length = max_payload_size; memcpy (payload.data, src, payload.data_length); if (Send (payload) == KERN_SUCCESS) { status = eConnectionStatusSuccess; return payload.data_length; } status = eConnectionStatusError; return 0; } std::string ConnectionMachPort::GetURI() { return m_uri; } ConnectionStatus ConnectionMachPort::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) { return eConnectionStatusLostConnection; } kern_return_t ConnectionMachPort::Send (const PayloadType &payload) { struct MessageType message; /* (i) Form the message : */ /* (i.a) Fill the header fields : */ message.head.msgh_bits = MACH_MSGH_BITS_REMOTE (MACH_MSG_TYPE_MAKE_SEND) | MACH_MSGH_BITS_OTHER (MACH_MSGH_BITS_COMPLEX); message.head.msgh_size = sizeof(MessageType); message.head.msgh_local_port = MACH_PORT_NULL; message.head.msgh_remote_port = m_port; /* (i.b) Explain the message type ( an integer ) */ // message.type.msgt_name = MACH_MSG_TYPE_INTEGER_32; // message.type.msgt_size = 32; // message.type.msgt_number = 1; // message.type.msgt_inline = TRUE; // message.type.msgt_longform = FALSE; // message.type.msgt_deallocate = FALSE; /* message.type.msgt_unused = 0; */ /* not needed, I think */ /* (i.c) Fill the message with the given integer : */ message.payload = payload; /* (ii) Send the message : */ kern_return_t kret = ::mach_msg (&message.head, MACH_SEND_MSG, message.head.msgh_size, 0, MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); return kret; } kern_return_t ConnectionMachPort::Receive (PayloadType &payload) { MessageType message; message.head.msgh_size = sizeof(MessageType); kern_return_t kret = ::mach_msg (&message.head, MACH_RCV_MSG, 0, sizeof(MessageType), m_port, MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if (kret == KERN_SUCCESS) payload = message.payload; return kret; } #endif // #if defined(__APPLE__) <|endoftext|>
<commit_before>#include "protocol.h" #include "storage.h" #include <algorithm> #include <cstdlib> #include <vector> #include <deque> #include <iostream> #include <list> #include <map> #include <set> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/asio.hpp> #include <boost/filesystem.hpp> using boost::asio::ip::tcp; using namespace std; const riorita::int32 MIN_VALID_REQUEST_SIZE = 19; const riorita::int32 MAX_VALID_REQUEST_SIZE = 1073741824; class Session; typedef boost::shared_ptr<Session> SessionPtr; set<SessionPtr> sessions; riorita::Storage* storage; riorita::Bytes processRequest(const riorita::Request& request) { bool success = true; bool verdict = false; string data; if (request.type == riorita::PING) verdict = true; string key(request.key.data, request.key.data + request.key.size); if (request.type == riorita::HAS) verdict = storage->has(key); if (request.type == riorita::GET) verdict = storage->get(key, data); #undef DELETE if (request.type == riorita::DELETE) { storage->erase(key); verdict = true; } if (request.type == riorita::PUT) { string value(request.value.data, request.value.data + request.value.size); storage->put(key, value); verdict = true; } return newResponse(request, success, verdict, static_cast<riorita::int32>(data.length()), reinterpret_cast<const riorita::byte*>(data.c_str())); } class Session: public boost::enable_shared_from_this<Session> { public: virtual ~Session() { cout << "Connection closed: " << int(this) << endl; response.reset(); cout << 2 << endl; requestBytes.reset(); cout << 3 << endl; if (null != request) { cout << 4 << endl; delete[] request; } cout << 5 << endl; } Session(boost::asio::io_service& io_service) : _socket(io_service), request(null) { } void onError() { cout << "Ready to close" << endl; sessions.erase(shared_from_this()); } tcp::socket& socket() { return _socket; } void start() { cout << "New connection" << endl; sessions.insert(shared_from_this()); boost::system::error_code error; handleStart(error); } void handleStart(const boost::system::error_code& error) { if (!error) { boost::asio::async_read( _socket, boost::asio::buffer(&requestBytes.size, sizeof(requestBytes.size)), boost::bind(&Session::handleRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); } else { cout << "error handleStart" << endl; onError(); } } void handleRead(const boost::system::error_code& error, std::size_t bytes_transferred) { if (!error && bytes_transferred == sizeof(requestBytes.size) && requestBytes.size >= MIN_VALID_REQUEST_SIZE && requestBytes.size <= MAX_VALID_REQUEST_SIZE) { requestBytes.size -= sizeof(riorita::int32); requestBytes.data = new riorita::byte[requestBytes.size]; boost::asio::async_read( _socket, boost::asio::buffer(requestBytes.data, requestBytes.size), boost::bind(&Session::handleRequest, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); } else { cout << "error handleRead" << endl; onError(); } } void handleRequest(const boost::system::error_code& error, std::size_t bytes_transferred) { if (!error && riorita::int32(bytes_transferred) == requestBytes.size) { riorita::int32 parsedByteCount; request = parseRequest(requestBytes, 0, parsedByteCount); if (request != null && parsedByteCount == requestBytes.size) { response = processRequest(*request); boost::asio::async_write( _socket, boost::asio::buffer(response.data, response.size), boost::bind(&Session::handleEnd, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); } else { cout << "Can't parse request" << endl; onError(); } if (null != request) { delete request; request = null; } } else { cout << "error handleRequest" << endl; onError(); } } void handleEnd(const boost::system::error_code& error, std::size_t bytes_transferred) { std::size_t responseSize = response.size; requestBytes.reset(); response.reset(); if (!error && bytes_transferred == responseSize) { handleStart(error); } else { cout << "error handleEnd" << endl; onError(); } } private: tcp::socket _socket; riorita::Bytes requestBytes; riorita::Request* request; riorita::Bytes response; }; //---------------------------------------------------------------------- class RioritaServer { public: RioritaServer(boost::asio::io_service& io_service, const tcp::endpoint& endpoint) : io_service_(io_service), acceptor_(io_service, endpoint) { startAccept(); } void startAccept() { SessionPtr newSession(new Session(io_service_)); acceptor_.async_accept(newSession->socket(), boost::bind(&RioritaServer::handleAccept, this, newSession, boost::asio::placeholders::error)); } void handleAccept(SessionPtr Session, const boost::system::error_code& error) { if (!error) { Session->start(); } startAccept(); } private: boost::asio::io_service& io_service_; tcp::acceptor acceptor_; }; typedef boost::shared_ptr<RioritaServer> RioritaServerPtr; typedef std::list<RioritaServerPtr> RioritaServerList; //---------------------------------------------------------------------- void init() { riorita::StorageOptions opts; opts.directory = "data"; storage = riorita::newStorage(riorita::MEMORY, opts); if (null == storage) { std::cerr << "Can't initialize storage\n"; exit(1); } } int main(int argc, char* argv[]) { init(); try { if (argc < 2) { std::cerr << "Usage: riorita_server <port> [<port> ...]\n"; return 1; } boost::asio::io_service io_service; RioritaServerList servers; for (int i = 1; i < argc; ++i) { tcp::endpoint endpoint(tcp::v4(), short(atoi(argv[i]))); RioritaServerPtr server(new RioritaServer(io_service, endpoint)); servers.push_back(server); } io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; return 1; } return 0; } <commit_msg>- remove debug output<commit_after>#include "protocol.h" #include "storage.h" #include <algorithm> #include <cstdlib> #include <vector> #include <deque> #include <iostream> #include <list> #include <map> #include <set> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <boost/asio.hpp> #include <boost/filesystem.hpp> using boost::asio::ip::tcp; using namespace std; const riorita::int32 MIN_VALID_REQUEST_SIZE = 19; const riorita::int32 MAX_VALID_REQUEST_SIZE = 1073741824; class Session; typedef boost::shared_ptr<Session> SessionPtr; set<SessionPtr> sessions; riorita::Storage* storage; riorita::Bytes processRequest(const riorita::Request& request) { bool success = true; bool verdict = false; string data; if (request.type == riorita::PING) verdict = true; string key(request.key.data, request.key.data + request.key.size); if (request.type == riorita::HAS) verdict = storage->has(key); if (request.type == riorita::GET) verdict = storage->get(key, data); #undef DELETE if (request.type == riorita::DELETE) { storage->erase(key); verdict = true; } if (request.type == riorita::PUT) { string value(request.value.data, request.value.data + request.value.size); storage->put(key, value); verdict = true; } return newResponse(request, success, verdict, static_cast<riorita::int32>(data.length()), reinterpret_cast<const riorita::byte*>(data.c_str())); } class Session: public boost::enable_shared_from_this<Session> { public: virtual ~Session() { cout << "Connection closed" << endl; response.reset(); requestBytes.reset(); if (null != request) delete[] request; } Session(boost::asio::io_service& io_service) : _socket(io_service), request(null) { } void onError() { cout << "Ready to close" << endl; sessions.erase(shared_from_this()); } tcp::socket& socket() { return _socket; } void start() { cout << "New connection" << endl; sessions.insert(shared_from_this()); boost::system::error_code error; handleStart(error); } void handleStart(const boost::system::error_code& error) { if (!error) { boost::asio::async_read( _socket, boost::asio::buffer(&requestBytes.size, sizeof(requestBytes.size)), boost::bind(&Session::handleRead, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); } else { cout << "error handleStart" << endl; onError(); } } void handleRead(const boost::system::error_code& error, std::size_t bytes_transferred) { if (!error && bytes_transferred == sizeof(requestBytes.size) && requestBytes.size >= MIN_VALID_REQUEST_SIZE && requestBytes.size <= MAX_VALID_REQUEST_SIZE) { requestBytes.size -= sizeof(riorita::int32); requestBytes.data = new riorita::byte[requestBytes.size]; boost::asio::async_read( _socket, boost::asio::buffer(requestBytes.data, requestBytes.size), boost::bind(&Session::handleRequest, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); } else { cout << "error handleRead" << endl; onError(); } } void handleRequest(const boost::system::error_code& error, std::size_t bytes_transferred) { if (!error && riorita::int32(bytes_transferred) == requestBytes.size) { riorita::int32 parsedByteCount; request = parseRequest(requestBytes, 0, parsedByteCount); if (request != null && parsedByteCount == requestBytes.size) { response = processRequest(*request); boost::asio::async_write( _socket, boost::asio::buffer(response.data, response.size), boost::bind(&Session::handleEnd, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred) ); } else { cout << "Can't parse request" << endl; onError(); } if (null != request) { delete request; request = null; } } else { cout << "error handleRequest" << endl; onError(); } } void handleEnd(const boost::system::error_code& error, std::size_t bytes_transferred) { std::size_t responseSize = response.size; requestBytes.reset(); response.reset(); if (!error && bytes_transferred == responseSize) { handleStart(error); } else { cout << "error handleEnd" << endl; onError(); } } private: tcp::socket _socket; riorita::Bytes requestBytes; riorita::Request* request; riorita::Bytes response; }; //---------------------------------------------------------------------- class RioritaServer { public: RioritaServer(boost::asio::io_service& io_service, const tcp::endpoint& endpoint) : io_service_(io_service), acceptor_(io_service, endpoint) { startAccept(); } void startAccept() { SessionPtr newSession(new Session(io_service_)); acceptor_.async_accept(newSession->socket(), boost::bind(&RioritaServer::handleAccept, this, newSession, boost::asio::placeholders::error)); } void handleAccept(SessionPtr Session, const boost::system::error_code& error) { if (!error) { Session->start(); } startAccept(); } private: boost::asio::io_service& io_service_; tcp::acceptor acceptor_; }; typedef boost::shared_ptr<RioritaServer> RioritaServerPtr; typedef std::list<RioritaServerPtr> RioritaServerList; //---------------------------------------------------------------------- void init() { riorita::StorageOptions opts; opts.directory = "data"; storage = riorita::newStorage(riorita::MEMORY, opts); if (null == storage) { std::cerr << "Can't initialize storage\n"; exit(1); } } int main(int argc, char* argv[]) { init(); try { if (argc < 2) { std::cerr << "Usage: riorita_server <port> [<port> ...]\n"; return 1; } boost::asio::io_service io_service; RioritaServerList servers; for (int i = 1; i < argc; ++i) { tcp::endpoint endpoint(tcp::v4(), short(atoi(argv[i]))); RioritaServerPtr server(new RioritaServer(io_service, endpoint)); servers.push_back(server); } io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; return 1; } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: galwrap.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:45:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include <vcl/graph.hxx> #include <svx/gallery.hxx> #include <sfx2/app.hxx> #include <sfx2/explorer.hxx> // ----------------------------------------------------------------------- Graphic GalleryGetGraphic() { GalleryExplorer* pGal = SVX_GALLERY(); DBG_ASSERT( pGal, "Wo ist die Gallery?" ); return pGal->GetGraphic(); } USHORT GallerySGA_FORMAT_GRAPHIC() { return SGA_FORMAT_GRAPHIC; } BOOL GalleryIsLinkage() { GalleryExplorer* pGal = SVX_GALLERY(); DBG_ASSERT( pGal, "Wo ist die Gallery?" ); return pGal->IsLinkage(); } String GalleryGetFullPath() { GalleryExplorer* pGal = SVX_GALLERY(); DBG_ASSERT( pGal, "Wo ist die Gallery?" ); // return pGal->GetPath().GetFull(); return pGal->GetURL().GetMainURL(); } String GalleryGetFilterName() { GalleryExplorer* pGal = SVX_GALLERY(); DBG_ASSERT( pGal, "Wo ist die Gallery?" ); return pGal->GetFilterName(); } <commit_msg>#65293# sfx2/explorer.hxx removed - it's obsolete<commit_after>/************************************************************************* * * $RCSfile: galwrap.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2001-05-16 09:34:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop // INCLUDE --------------------------------------------------------------- #include <vcl/graph.hxx> #include <svx/gallery.hxx> #include <sfx2/app.hxx> // ----------------------------------------------------------------------- Graphic GalleryGetGraphic() { GalleryExplorer* pGal = SVX_GALLERY(); DBG_ASSERT( pGal, "Wo ist die Gallery?" ); return pGal->GetGraphic(); } USHORT GallerySGA_FORMAT_GRAPHIC() { return SGA_FORMAT_GRAPHIC; } BOOL GalleryIsLinkage() { GalleryExplorer* pGal = SVX_GALLERY(); DBG_ASSERT( pGal, "Wo ist die Gallery?" ); return pGal->IsLinkage(); } String GalleryGetFullPath() { GalleryExplorer* pGal = SVX_GALLERY(); DBG_ASSERT( pGal, "Wo ist die Gallery?" ); // return pGal->GetPath().GetFull(); return pGal->GetURL().GetMainURL(); } String GalleryGetFilterName() { GalleryExplorer* pGal = SVX_GALLERY(); DBG_ASSERT( pGal, "Wo ist die Gallery?" ); return pGal->GetFilterName(); } <|endoftext|>
<commit_before>#include "../../include/frame/Catalog.h" #include "../../include/frame/Point.h" #include <fstream> #include <iostream> #include <set> #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> using namespace shapelens; using namespace std; Catalog::Catalog() : map<unsigned long, CatObject>() { present.set(); } Catalog::Catalog(string catfile) : map<unsigned long, CatObject>() { read(catfile); } void Catalog::read(string catfile) { // reset bitset that indicates which data are given in catalog // in other words: which of the format fields are set present.reset(); formatChecked = true; // open cat file ifstream catalog (catfile.c_str()); if (catalog.fail()) { std::cerr << "Catalog: catalog file does not exist!" << endl; terminate(); } catalog.clear(); // read in cat file // 1) parse the format definition lines // 2) fill object information into SExCatObjects -> map<unsigned long, CatObject>; string line; std::vector<std::string> column; while(getline(catalog, line)) { typedef boost::tokenizer<boost::char_separator<char> > Tok; // split entries at empty chars boost::char_separator<char> sep(" "); Tok tok(line, sep); // first of all we copy the token into string vector // though this is not too sophisticated it does not hurt and is more // convenient column.clear(); for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) column.push_back(*tok_iter); // comment line: contains format definition at columns 2,3 if (column[0].compare("#") == 0) setFormatField(column[2],boost::lexical_cast<unsigned short>(column[1].c_str())); // at this point we should have a complete format definition: check it // from here on we expect the list of object to come along. else { if (!formatChecked) checkFormat(); // then set up a true SExCatObject CatObject so; unsigned long id = boost::lexical_cast<unsigned long>(column[format.ID].c_str()); // the sextractor corrdinates start with (1,1), ours with (0,0) so.XMIN = boost::lexical_cast<int>(column[format.XMIN].c_str())-1; so.XMAX = boost::lexical_cast<int>(column[format.XMAX].c_str())-1; so.YMIN = boost::lexical_cast<int>(column[format.YMIN].c_str())-1; so.YMAX = boost::lexical_cast<int>(column[format.YMAX].c_str())-1; // as Catalog pixels start with (1,1) and ours with (0,0), // we need to subtract 1 so.XCENTROID = boost::lexical_cast<data_t>(column[format.XCENTROID].c_str())-1; so.YCENTROID = boost::lexical_cast<data_t>(column[format.YCENTROID].c_str())-1; so.FLUX = boost::lexical_cast<data_t>(column[format.FLUX].c_str()); so.FLAGS = (unsigned char) boost::lexical_cast<unsigned int>(column[format.FLAGS].c_str()); if (present.test(9)) so.CLASSIFIER = boost::lexical_cast<data_t>(column[format.CLASSIFIER].c_str()); else so.CLASSIFIER = (data_t) 0; if (present.test(10)) so.PARENT = boost::lexical_cast<unsigned long>(column[format.PARENT].c_str()); else so.PARENT = (unsigned long)0; // then store it in map Catalog::insert(make_pair(id,so)); } } catalog.close(); } void Catalog::save(string catfile) const { // write header and the data section in SExtractor format ofstream catalog (catfile.c_str()); catalog << "# 1 ID" << endl; catalog << "# 2 XMIN_IMAGE" << endl; catalog << "# 3 XMAX_IMAGE" << endl; catalog << "# 4 YMIN_IMAGE" << endl; catalog << "# 5 YMAX_IMAGE" << endl; catalog << "# 6 XCENTROID_IMAGE" << endl; catalog << "# 7 YCENTROID_IMAGE" << endl; catalog << "# 8 FLUX" << endl; catalog << "# 9 FLAGS" << endl; if (present.test(9)) catalog << "# 10 CLASSIFIER" << endl; if (present.test(10)) { if (present.test(9)) catalog << "# 11 PARENT" << endl; else catalog << "# 10 PARENT" << endl; } // now all objects in Catalog Catalog::const_iterator iter; for (iter = Catalog::begin(); iter != Catalog::end(); iter++) { catalog << iter->first << " "; catalog << iter->second.XMIN + 1 << " "; catalog << iter->second.XMAX + 1 << " "; catalog << iter->second.YMIN + 1 << " "; catalog << iter->second.YMAX + 1 << " "; catalog << iter->second.XCENTROID + 1 << " "; catalog << iter->second.YCENTROID + 1 << " "; catalog << iter->second.FLUX << " "; catalog << (unsigned int) iter->second.FLAGS << " "; if (present.test(9)) catalog << iter->second.CLASSIFIER << " "; if (present.test(10)) catalog << iter->second.PARENT << " "; catalog << endl; } } void Catalog::setFormatField(std::string type, unsigned short colnr) { if (type == "ID" || type == "NUMBER" || type == "NR") { format.ID = colnr - 1; present[0] = 1; } else if (type.find("XMIN") == 0) { format.XMIN = colnr - 1; present[1] = 1; } else if (type.find("XMAX") == 0) { format.XMAX = colnr - 1; present[2] = 1; } else if (type.find("YMIN") == 0) { format.YMIN = colnr - 1; present[3] = 1; } else if (type.find("YMAX") == 0) { format.YMAX = colnr - 1; present[4] = 1; } else if (type == "X" || type.find("X_") == 0 || type.find("XWIN") == 0 || type.find("XPEAK") == 0 || type.find("XCENTROID") == 0) { format.XCENTROID = colnr - 1; present[5] = 1; } else if (type == "Y" || type.find("Y_") == 0 || type.find("YWIN") == 0 || type.find("YPEAK") == 0 || type.find("YCENTROID") == 0) { format.YCENTROID = colnr - 1; present[6] = 1; } else if (type.find("FLUX") == 0) { format.FLUX = colnr - 1; present[7] = 1; } else if (type == "FLAGS") { format.FLAGS = colnr - 1; present[8] = 1; } else if (type == "CLASS_STAR" || type == "CLASSIFIER") { format.CLASSIFIER = colnr - 1; present[9] = 1; } else if (type == "PARENT" || type == "VECTOR_ASSOC") { format.PARENT = colnr - 1; present[10] = 1; } } bool Catalog::checkFormat() { // test if all but 9th bit are set // this means that CLASSIFIER is optional bitset<11> mask(0); mask[9] = mask[10] = 1; if ((present | mask).count() < 11) { cerr << "Catalog: mandatory catalog parameters are missing!" << endl; terminate(); } else formatChecked = 1; } int Catalog::round(data_t x) { if (x-floor(x)>=0.5) return (int) ceil(x); else return (int) floor(x); } void Catalog::apply(const CoordinateTransformation<data_t>& C) { Point<data_t> P; for (Catalog::iterator iter = Catalog::begin(); iter != Catalog::end(); iter++) { CatObject& ci = iter->second; // transform centroid P(0) = ci.XCENTROID; P(1) = ci.YCENTROID; C.transform(P); ci.XCENTROID = P(0); ci.YCENTROID = P(1); // transform XMIN ... P(0) = ci.XMIN; P(1) = ci.YMIN; C.transform(P); ci.XMIN = round(P(0)); ci.YMIN = round(P(1)); // transform XMAX ... P(0) = ci.XMAX; P(1) = ci.YMAX; C.transform(P); ci.XMAX = round(P(0)); ci.YMAX = round(P(1)); } } Catalog Catalog::operator+ (const Catalog& c) { Catalog newCat = *this; for (Catalog::const_iterator iter = c.begin(); iter != c.end(); iter++) newCat[iter->first] = iter->second; } void Catalog::operator+= (const Catalog& c) { for (Catalog::const_iterator iter = c.begin(); iter != c.end(); iter++) Catalog::operator[](iter->first) = iter->second; } Catalog Catalog::operator- (const Catalog& c) { Catalog newCat = *this; for (Catalog::const_iterator iter = c.begin(); iter != c.end(); iter++) { Catalog::iterator key = newCat.find(iter->first); if (key != newCat.end()) newCat.erase(key); } } void Catalog::operator-= (const Catalog& c) { for (Catalog::const_iterator iter = c.begin(); iter != c.end(); iter++) { Catalog::iterator key = Catalog::find(iter->first); if (key != Catalog::end()) Catalog::erase(key); } } <commit_msg>bugfix in WCS treatment of Catalog<commit_after>#include "../../include/frame/Catalog.h" #include "../../include/frame/Shapes.h" #include <fstream> #include <iostream> #include <set> #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> using namespace shapelens; using namespace std; Catalog::Catalog() : map<unsigned long, CatObject>() { present.set(); } Catalog::Catalog(string catfile) : map<unsigned long, CatObject>() { read(catfile); } void Catalog::read(string catfile) { // reset bitset that indicates which data are given in catalog // in other words: which of the format fields are set present.reset(); formatChecked = true; // open cat file ifstream catalog (catfile.c_str()); if (catalog.fail()) { std::cerr << "Catalog: catalog file does not exist!" << endl; terminate(); } catalog.clear(); // read in cat file // 1) parse the format definition lines // 2) fill object information into SExCatObjects -> map<unsigned long, CatObject>; string line; std::vector<std::string> column; while(getline(catalog, line)) { typedef boost::tokenizer<boost::char_separator<char> > Tok; // split entries at empty chars boost::char_separator<char> sep(" "); Tok tok(line, sep); // first of all we copy the token into string vector // though this is not too sophisticated it does not hurt and is more // convenient column.clear(); for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) column.push_back(*tok_iter); // comment line: contains format definition at columns 2,3 if (column[0].compare("#") == 0) setFormatField(column[2],boost::lexical_cast<unsigned short>(column[1].c_str())); // at this point we should have a complete format definition: check it // from here on we expect the list of object to come along. else { if (!formatChecked) checkFormat(); // then set up a true SExCatObject CatObject so; unsigned long id = boost::lexical_cast<unsigned long>(column[format.ID].c_str()); // the sextractor corrdinates start with (1,1), ours with (0,0) so.XMIN = boost::lexical_cast<int>(column[format.XMIN].c_str())-1; so.XMAX = boost::lexical_cast<int>(column[format.XMAX].c_str())-1; so.YMIN = boost::lexical_cast<int>(column[format.YMIN].c_str())-1; so.YMAX = boost::lexical_cast<int>(column[format.YMAX].c_str())-1; // as Catalog pixels start with (1,1) and ours with (0,0), // we need to subtract 1 so.XCENTROID = boost::lexical_cast<data_t>(column[format.XCENTROID].c_str())-1; so.YCENTROID = boost::lexical_cast<data_t>(column[format.YCENTROID].c_str())-1; so.FLUX = boost::lexical_cast<data_t>(column[format.FLUX].c_str()); so.FLAGS = (unsigned char) boost::lexical_cast<unsigned int>(column[format.FLAGS].c_str()); if (present.test(9)) so.CLASSIFIER = boost::lexical_cast<data_t>(column[format.CLASSIFIER].c_str()); else so.CLASSIFIER = (data_t) 0; if (present.test(10)) so.PARENT = boost::lexical_cast<unsigned long>(column[format.PARENT].c_str()); else so.PARENT = (unsigned long)0; // then store it in map Catalog::insert(make_pair(id,so)); } } catalog.close(); } void Catalog::save(string catfile) const { // write header and the data section in SExtractor format ofstream catalog (catfile.c_str()); catalog << "# 1 ID" << endl; catalog << "# 2 XMIN_IMAGE" << endl; catalog << "# 3 XMAX_IMAGE" << endl; catalog << "# 4 YMIN_IMAGE" << endl; catalog << "# 5 YMAX_IMAGE" << endl; catalog << "# 6 XCENTROID_IMAGE" << endl; catalog << "# 7 YCENTROID_IMAGE" << endl; catalog << "# 8 FLUX" << endl; catalog << "# 9 FLAGS" << endl; if (present.test(9)) catalog << "# 10 CLASSIFIER" << endl; if (present.test(10)) { if (present.test(9)) catalog << "# 11 PARENT" << endl; else catalog << "# 10 PARENT" << endl; } // now all objects in Catalog Catalog::const_iterator iter; for (iter = Catalog::begin(); iter != Catalog::end(); iter++) { catalog << iter->first << " "; catalog << iter->second.XMIN + 1 << " "; catalog << iter->second.XMAX + 1 << " "; catalog << iter->second.YMIN + 1 << " "; catalog << iter->second.YMAX + 1 << " "; catalog << iter->second.XCENTROID + 1 << " "; catalog << iter->second.YCENTROID + 1 << " "; catalog << iter->second.FLUX << " "; catalog << (unsigned int) iter->second.FLAGS << " "; if (present.test(9)) catalog << iter->second.CLASSIFIER << " "; if (present.test(10)) catalog << iter->second.PARENT << " "; catalog << endl; } } void Catalog::setFormatField(std::string type, unsigned short colnr) { if (type == "ID" || type == "NUMBER" || type == "NR") { format.ID = colnr - 1; present[0] = 1; } else if (type.find("XMIN") == 0) { format.XMIN = colnr - 1; present[1] = 1; } else if (type.find("XMAX") == 0) { format.XMAX = colnr - 1; present[2] = 1; } else if (type.find("YMIN") == 0) { format.YMIN = colnr - 1; present[3] = 1; } else if (type.find("YMAX") == 0) { format.YMAX = colnr - 1; present[4] = 1; } else if (type == "X" || type.find("X_") == 0 || type.find("XWIN") == 0 || type.find("XPEAK") == 0 || type.find("XCENTROID") == 0) { format.XCENTROID = colnr - 1; present[5] = 1; } else if (type == "Y" || type.find("Y_") == 0 || type.find("YWIN") == 0 || type.find("YPEAK") == 0 || type.find("YCENTROID") == 0) { format.YCENTROID = colnr - 1; present[6] = 1; } else if (type.find("FLUX") == 0) { format.FLUX = colnr - 1; present[7] = 1; } else if (type == "FLAGS") { format.FLAGS = colnr - 1; present[8] = 1; } else if (type == "CLASS_STAR" || type == "CLASSIFIER") { format.CLASSIFIER = colnr - 1; present[9] = 1; } else if (type == "PARENT" || type == "VECTOR_ASSOC") { format.PARENT = colnr - 1; present[10] = 1; } } bool Catalog::checkFormat() { // test if all but 9th bit are set // this means that CLASSIFIER is optional bitset<11> mask(0); mask[9] = mask[10] = 1; if ((present | mask).count() < 11) { cerr << "Catalog: mandatory catalog parameters are missing!" << endl; terminate(); } else formatChecked = 1; } int Catalog::round(data_t x) { if (x-floor(x)>=0.5) return (int) ceil(x); else return (int) floor(x); } void Catalog::apply(const CoordinateTransformation<data_t>& C) { Point<data_t> P; Rectangle<data_t> bb; for (Catalog::iterator iter = Catalog::begin(); iter != Catalog::end(); iter++) { CatObject& ci = iter->second; // transform centroid P(0) = ci.XCENTROID; P(1) = ci.YCENTROID; C.transform(P); ci.XCENTROID = P(0); ci.YCENTROID = P(1); // transform bounding box of (XMIN/YMIN) .. (XMAX/YMAX) bb.ll(0) = ci.XMIN; bb.ll(1) = ci.YMIN; bb.tr(0) = ci.XMAX; bb.tr(1) = ci.YMAX; bb.apply(C); ci.XMIN = (int) round(bb.ll(0)); ci.YMIN = (int) round(bb.ll(1)); ci.XMAX = (int) round(bb.tr(0)); ci.YMAX = (int) round(bb.tr(1)); } } Catalog Catalog::operator+ (const Catalog& c) { Catalog newCat = *this; for (Catalog::const_iterator iter = c.begin(); iter != c.end(); iter++) newCat[iter->first] = iter->second; } void Catalog::operator+= (const Catalog& c) { for (Catalog::const_iterator iter = c.begin(); iter != c.end(); iter++) Catalog::operator[](iter->first) = iter->second; } Catalog Catalog::operator- (const Catalog& c) { Catalog newCat = *this; for (Catalog::const_iterator iter = c.begin(); iter != c.end(); iter++) { Catalog::iterator key = newCat.find(iter->first); if (key != newCat.end()) newCat.erase(key); } } void Catalog::operator-= (const Catalog& c) { for (Catalog::const_iterator iter = c.begin(); iter != c.end(); iter++) { Catalog::iterator key = Catalog::find(iter->first); if (key != Catalog::end()) Catalog::erase(key); } } <|endoftext|>
<commit_before>#include <frame/Catalog.h> #include <fstream> #include <iostream> #include <boost/tokenizer.hpp> using namespace std; Catalog::Catalog() : vector<CatObject>() { } Catalog::Catalog(string catfile) : vector<CatObject>() { read(catfile); } void Catalog::read(string catfile) { // reset bitset that indicates which data are given in catalog // in other words: which of the format fields are set present.reset(); formatChecked = 0; // first inser empty object 0, since object numbers start with 1 vector<CatObject>::clear(); CatObject s0 = {0,0,0,0,0,0,0,0,0,0}; vector<CatObject>::push_back(s0); // open cat file ifstream catalog (catfile.c_str()); if (catalog.fail()) { std::cerr << "Catalog: catalog file does not exist!" << endl; terminate(); } catalog.clear(); // read in cat file // 1) parse the format definition lines // 2) fill object information into SExCatObjects -> vector<CatObject>; string line; std::vector<std::string> column; while(getline(catalog, line)) { typedef boost::tokenizer<boost::char_separator<char> > Tok; // split entries at empty chars boost::char_separator<char> sep(" "); Tok tok(line, sep); // first of all we copy the token into string vector // though this is not too sophisticated it does not hurt and is more // convenient column.clear(); for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) column.push_back(*tok_iter); // comment line: contains format definition at columns 2,3 if (column[0].compare("#") == 0) setFormatField(column[2],atoi(column[1].c_str())); // at this point we should have a complete format definition: check it // from here on we expect the list of object to come along. else { if (!formatChecked) checkFormat(); // then set up a true SExCatObject CatObject so; so.NUMBER = (unsigned long) atoi(column[format.NUMBER].c_str()); // the sextractor corrdinates start with (1,1), ours with (0,0) so.XMIN = atoi(column[format.XMIN].c_str())-1; so.XMAX = atoi(column[format.XMAX].c_str())-1; so.YMIN = atoi(column[format.YMIN].c_str())-1; so.YMAX = atoi(column[format.YMAX].c_str())-1; so.XCENTROID = atof(column[format.XCENTROID].c_str())-1; so.YCENTROID = atof(column[format.YCENTROID].c_str())-1; so.FLUX = atof(column[format.FLUX].c_str()); so.FLAGS = (unsigned char) atoi(column[format.FLAGS].c_str()); if (present.test(9)) so.CLASSIFIER = (data_t) atof(column[format.CLASSIFIER].c_str()); else so.CLASSIFIER = (data_t) 0; // then push it on vector<CatObject> vector<CatObject>::push_back(so); } } catalog.close(); } void Catalog::save(string catfile) const { // write header and the data section in SExtractor format ofstream catalog (catfile.c_str()); catalog << "# 1 NUMBER" << endl; catalog << "# 2 XMIN_IMAGE" << endl; catalog << "# 3 XMAX_IMAGE" << endl; catalog << "# 4 YMIN_IMAGE" << endl; catalog << "# 5 YMAX_IMAGE" << endl; catalog << "# 6 XCENTROID_IMAGE" << endl; catalog << "# 7 YCENTROID_IMAGE" << endl; catalog << "# 8 FLUX" << endl; catalog << "# 9 FLAGS" << endl; if (present.test(9)) catalog << "# 10 CLASSIFIER" << endl; // now all objects in Catalog for (unsigned int i=1; i<vector<CatObject>::size(); i++) { catalog << vector<CatObject>::operator[](i).NUMBER << " "; catalog << vector<CatObject>::operator[](i).XMIN + 1 << " "; catalog << vector<CatObject>::operator[](i).XMAX + 1 << " "; catalog << vector<CatObject>::operator[](i).YMIN + 1 << " "; catalog << vector<CatObject>::operator[](i).YMAX + 1 << " "; catalog << vector<CatObject>::operator[](i).XCENTROID + 1 << " "; catalog << vector<CatObject>::operator[](i).YCENTROID + 1 << " "; catalog << vector<CatObject>::operator[](i).FLUX << " "; catalog << (unsigned int) vector<CatObject>::operator[](i).FLAGS << " "; if (present.test(9)) catalog << vector<CatObject>::operator[](i).CLASSIFIER << " "; catalog << endl; } } void Catalog::setFormatField(std::string type, unsigned short colnr) { if (type == "NUMBER" || type == "NR") { format.NUMBER = colnr - 1; present[0] = 1; } else if (type.find("XMIN") != string::npos) { format.XMIN = colnr - 1; present[1] = 1; } else if (type.find("XMAX") != string::npos) { format.XMAX = colnr - 1; present[2] = 1; } else if (type.find("YMIN") != string::npos) { format.YMIN = colnr - 1; present[3] = 1; } else if (type.find("YMAX") != string::npos) { format.YMAX = colnr - 1; present[4] = 1; } else if (type == "X" || type.find("X_") != string::npos || type.find("XWIN") != string::npos || type.find("XPEAK") != string::npos) { format.XCENTROID = colnr - 1; present[5] = 1; } else if (type == "Y" || type.find("Y_") != string::npos || type.find("YWIN") != string::npos || type.find("YPEAK") != string::npos) { format.YCENTROID = colnr - 1; present[6] = 1; } else if (type.find("FLUX") != string::npos) { format.FLUX = colnr - 1; present[7] = 1; } else if (type == "FLAGS") { format.FLAGS = colnr - 1; present[8] = 1; } else if (type == "CLASS_STAR" || type == "CLASSIFIER") { format.CLASSIFIER = colnr - 1; present[9] = 1; } } bool Catalog::checkFormat() { // test if all but 9th bit are set // this means that CLASSIFIER is optional bitset<10> mask(0); mask[9] = 1; if ((present | mask).count() < 10) { cerr << "Catalog: mandatory catalog parameters are missing!" << endl; terminate(); } } <commit_msg>bugfix in Catalog<commit_after>#include <frame/Catalog.h> #include <fstream> #include <iostream> #include <boost/tokenizer.hpp> using namespace std; Catalog::Catalog() : vector<CatObject>() { } Catalog::Catalog(string catfile) : vector<CatObject>() { read(catfile); } void Catalog::read(string catfile) { // reset bitset that indicates which data are given in catalog // in other words: which of the format fields are set present.reset(); formatChecked = 0; // first inser empty object 0, since object numbers start with 1 vector<CatObject>::clear(); CatObject s0 = {0,0,0,0,0,0,0,0,0,0}; vector<CatObject>::push_back(s0); // open cat file ifstream catalog (catfile.c_str()); if (catalog.fail()) { std::cerr << "Catalog: catalog file does not exist!" << endl; terminate(); } catalog.clear(); // read in cat file // 1) parse the format definition lines // 2) fill object information into SExCatObjects -> vector<CatObject>; string line; std::vector<std::string> column; while(getline(catalog, line)) { typedef boost::tokenizer<boost::char_separator<char> > Tok; // split entries at empty chars boost::char_separator<char> sep(" "); Tok tok(line, sep); // first of all we copy the token into string vector // though this is not too sophisticated it does not hurt and is more // convenient column.clear(); for(Tok::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) column.push_back(*tok_iter); // comment line: contains format definition at columns 2,3 if (column[0].compare("#") == 0) setFormatField(column[2],atoi(column[1].c_str())); // at this point we should have a complete format definition: check it // from here on we expect the list of object to come along. else { if (!formatChecked) checkFormat(); // then set up a true SExCatObject CatObject so; so.NUMBER = (unsigned long) atoi(column[format.NUMBER].c_str()); // the sextractor corrdinates start with (1,1), ours with (0,0) so.XMIN = atoi(column[format.XMIN].c_str())-1; so.XMAX = atoi(column[format.XMAX].c_str())-1; so.YMIN = atoi(column[format.YMIN].c_str())-1; so.YMAX = atoi(column[format.YMAX].c_str())-1; so.XCENTROID = atof(column[format.XCENTROID].c_str())-1; so.YCENTROID = atof(column[format.YCENTROID].c_str())-1; so.FLUX = atof(column[format.FLUX].c_str()); so.FLAGS = (unsigned char) atoi(column[format.FLAGS].c_str()); if (present.test(9)) so.CLASSIFIER = (data_t) atof(column[format.CLASSIFIER].c_str()); else so.CLASSIFIER = (data_t) 0; // then push it on vector<CatObject> vector<CatObject>::push_back(so); } } catalog.close(); } void Catalog::save(string catfile) const { // write header and the data section in SExtractor format ofstream catalog (catfile.c_str()); catalog << "# 1 NUMBER" << endl; catalog << "# 2 XMIN_IMAGE" << endl; catalog << "# 3 XMAX_IMAGE" << endl; catalog << "# 4 YMIN_IMAGE" << endl; catalog << "# 5 YMAX_IMAGE" << endl; catalog << "# 6 XCENTROID_IMAGE" << endl; catalog << "# 7 YCENTROID_IMAGE" << endl; catalog << "# 8 FLUX" << endl; catalog << "# 9 FLAGS" << endl; if (present.test(9)) catalog << "# 10 CLASSIFIER" << endl; // now all objects in Catalog for (unsigned int i=1; i<vector<CatObject>::size(); i++) { catalog << vector<CatObject>::operator[](i).NUMBER << " "; catalog << vector<CatObject>::operator[](i).XMIN + 1 << " "; catalog << vector<CatObject>::operator[](i).XMAX + 1 << " "; catalog << vector<CatObject>::operator[](i).YMIN + 1 << " "; catalog << vector<CatObject>::operator[](i).YMAX + 1 << " "; catalog << vector<CatObject>::operator[](i).XCENTROID + 1 << " "; catalog << vector<CatObject>::operator[](i).YCENTROID + 1 << " "; catalog << vector<CatObject>::operator[](i).FLUX << " "; catalog << (unsigned int) vector<CatObject>::operator[](i).FLAGS << " "; if (present.test(9)) catalog << vector<CatObject>::operator[](i).CLASSIFIER << " "; catalog << endl; } } void Catalog::setFormatField(std::string type, unsigned short colnr) { if (type == "NUMBER" || type == "NR") { format.NUMBER = colnr - 1; present[0] = 1; } else if (type.find("XMIN") == 0) { format.XMIN = colnr - 1; present[1] = 1; } else if (type.find("XMAX") == 0) { format.XMAX = colnr - 1; present[2] = 1; } else if (type.find("YMIN") == 0) { format.YMIN = colnr - 1; present[3] = 1; } else if (type.find("YMAX") == 0) { format.YMAX = colnr - 1; present[4] = 1; } else if (type == "X" || type.find("X_") == 0 || type.find("XWIN") == 0 || type.find("XPEAK") == 0) { format.XCENTROID = colnr - 1; present[5] = 1; } else if (type == "Y" || type.find("Y_") == 0 || type.find("YWIN") == 0 || type.find("YPEAK") == 0) { format.YCENTROID = colnr - 1; present[6] = 1; } else if (type.find("FLUX") == 0) { format.FLUX = colnr - 1; present[7] = 1; } else if (type == "FLAGS") { format.FLAGS = colnr - 1; present[8] = 1; } else if (type == "CLASS_STAR" || type == "CLASSIFIER") { format.CLASSIFIER = colnr - 1; present[9] = 1; } } bool Catalog::checkFormat() { // test if all but 9th bit are set // this means that CLASSIFIER is optional bitset<10> mask(0); mask[9] = 1; if ((present | mask).count() < 10) { cerr << "Catalog: mandatory catalog parameters are missing!" << endl; terminate(); } else formatChecked = 1; } <|endoftext|>
<commit_before> #include <common/Context.h> #include <cassert> #include <map> #include <glbinding/gl/gl.h> #include <glbinding/ContextInfo.h> #include <glbinding/ProcAddress.h> #include <glbinding/Binding.h> #include <glbinding/Version.h> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> // specifies APIENTRY, should be after Error.h include, // which requires APIENTRY in windows.. #include <globjects/globjects.h> #include <globjects/base/baselogging.h> #include <common/ContextFormat.h> using namespace gl; using namespace globjects; glbinding::Version Context::retrieveVersion() { assert(0 != glbinding::getCurrentContext()); GLint minorVersion = -1; GLint majorVersion = -1; glGetIntegerv(GLenum::GL_MAJOR_VERSION, &majorVersion); // major version glGetIntegerv(GLenum::GL_MINOR_VERSION, &minorVersion); // minor version if (minorVersion < 0 && majorVersion < 0) // probably a context < 3.0 with no support for GL_MAJOR/MINOR_VERSION { const GLubyte * vstr = glGetString(GLenum::GL_VERSION); if (!vstr) return glbinding::Version(); assert(vstr[1] == '.'); assert(vstr[0] >= '0' && vstr[0] <= '9'); majorVersion = vstr[0] - '0'; assert(vstr[2] >= '0' && vstr[2] <= '9'); minorVersion = vstr[2] - '0'; } return glbinding::Version(majorVersion, minorVersion); } glbinding::Version Context::maxSupportedVersion() { glbinding::Version version; /* GLFW3 does not set default hint values on window creation so at least the default values must be set before glfwCreateWindow can be called. cf. http://www.glfw.org/docs/latest/group__window.html#ga4fd9e504bb937e79588a0ffdca9f620b */ glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, false); #ifdef MAC_OS /* * Using OS X the following hints must be set for proper context initialization * (cf. http://stackoverflow.com/questions/19969937/getting-a-glsl-330-context-on-osx-10-9-mavericks) */ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); #endif // create window for version check GLFWwindow * window = glfwCreateWindow(1, 1, "VersionCheck", nullptr, nullptr); if (window) { glfwMakeContextCurrent(window); glbinding::Binding::initialize(false); version = retrieveVersion(); glfwMakeContextCurrent(nullptr); glfwDestroyWindow(window); } return version; } GLFWwindow * Context::create( const ContextFormat & format , bool verify , int width , int height , GLFWmonitor * monitor) { glbinding::Version version = format.version(); if (verify) // check if version is valid and supported version = ContextFormat::validateVersion(format.version(), maxSupportedVersion()); /** GLFW3 does not set default hint values on window creation so at least the default values must be set before glfwCreateWindow can be called. cf. http://www.glfw.org/docs/latest/group__window.html#ga4fd9e504bb937e79588a0ffdca9f620b */ glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, true); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, version.m_major); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, version.m_minor); #ifdef MAC_OS glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #else if (version >= glbinding::Version(3, 0)) { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, format.forwardCompatible()); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, format.debugContext()); } if (version >= glbinding::Version(3, 2)) { glfwWindowHint(GLFW_OPENGL_PROFILE, format.profile() == ContextFormat::Profile::Core ? GLFW_OPENGL_CORE_PROFILE : (format.profile() == ContextFormat::Profile::Compatibility ? GLFW_OPENGL_COMPAT_PROFILE : GLFW_OPENGL_ANY_PROFILE)); } #endif glfwWindowHint(GLFW_DEPTH_BITS, format.depthBufferSize()); glfwWindowHint(GLFW_STENCIL_BITS, format.stencilBufferSize()); glfwWindowHint(GLFW_RED_BITS, format.redBufferSize()); glfwWindowHint(GLFW_GREEN_BITS, format.greenBufferSize()); glfwWindowHint(GLFW_BLUE_BITS, format.blueBufferSize()); glfwWindowHint(GLFW_ALPHA_BITS, format.alphaBufferSize()); glfwWindowHint(GLFW_STEREO, format.stereo()); glfwWindowHint(GLFW_SAMPLES, format.samples()); GLFWwindow * window = glfwCreateWindow(width, height, "", monitor, nullptr); if (window) { glfwMakeContextCurrent(window); glbinding::Binding::initialize(false); glfwMakeContextCurrent(nullptr); } return window; } const std::string & Context::swapIntervalString(const SwapInterval interval) { static const std::map<SwapInterval, std::string> swapiIdentifier = { { SwapInterval::NoVerticalSyncronization, "NoVerticalSyncronization" } , { SwapInterval::VerticalSyncronization, "VerticalSyncronization" } , { SwapInterval::AdaptiveVerticalSyncronization, "AdaptiveVerticalSyncronization" } }; return swapiIdentifier.at(interval); } Context::Context(GLFWwindow * window) : m_swapInterval(SwapInterval::NoVerticalSyncronization) , m_format(nullptr) , m_window(window) , m_handle(0) { assert(window); if (!window) return; GLFWwindow * current = glfwGetCurrentContext(); if (current != m_window) glfwMakeContextCurrent(m_window); m_handle = tryFetchHandle(); if (current != m_window) glfwMakeContextCurrent(current); } Context::~Context() { delete m_format; } std::string Context::version() { assert(0 != glbinding::getCurrentContext()); return glbinding::ContextInfo::version().toString(); } std::string Context::vendor() { assert(0 != glbinding::getCurrentContext()); return glbinding::ContextInfo::vendor(); } std::string Context::renderer() { assert(0 != glbinding::getCurrentContext()); return glbinding::ContextInfo::renderer(); } bool Context::isValid() const { return 0 < handle(); } glbinding::ContextHandle Context::tryFetchHandle() { const glbinding::ContextHandle handle = glbinding::getCurrentContext(); if (0 == handle) critical("Acquiring OpenGL context handle failed."); return handle; } Context::SwapInterval Context::swapInterval() const { return m_swapInterval; } void Context::setSwapInterval(const SwapInterval interval) { //if (interval == m_swapInterval) // initialized value might not match or explicit reset might be required // return true; GLFWwindow * current = glfwGetCurrentContext(); if (current != m_window) glfwMakeContextCurrent(m_window); glfwSwapInterval(static_cast<int>(interval)); if (current != m_window) glfwMakeContextCurrent(current); m_swapInterval = interval; } glbinding::ContextHandle Context::handle() const { return m_handle; } const ContextFormat & Context::format() const { assert(isValid()); if (m_format) return *m_format; // create and retrive format if not done already m_format = new ContextFormat(); GLFWwindow * current = glfwGetCurrentContext(); if (current != m_window) glfwMakeContextCurrent(m_window); m_format->setVersion(retrieveVersion()); if (m_format->version() >= glbinding::Version(3, 2)) m_format->setProfile(isCoreProfile() ? ContextFormat::Profile::Core : ContextFormat::Profile::Compatibility); else m_format->setProfile(ContextFormat::Profile::None); if (current != m_window) glfwMakeContextCurrent(current); //GLint i; //GLboolean b; //i = -1; glGetIntegerv(GLenum::GL_DEPTH_BITS, &i); //m_format->setDepthBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_STENCIL_BITS, &i); //m_format->setStencilBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_RED_BITS, &i); //m_format->setRedBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_GREEN_BITS, &i); //m_format->setGreenBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_BLUE_BITS, &i); //m_format->setBlueBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_ALPHA_BITS, &i); //m_format->setAlphaBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_SAMPLES, &i); //m_format->setSamples(i); //b = GL_FALSE; glGetBooleanv(GLenum::GL_STEREO, &b); //m_format->setStereo(b == GL_TRUE); return *m_format; } void Context::makeCurrent() const { if (m_window) glfwMakeContextCurrent(m_window); } void Context::doneCurrent() const { if (m_window && m_window == glfwGetCurrentContext()) glfwMakeContextCurrent(nullptr); } <commit_msg>revert vsync for windows, since glfw does not work<commit_after> #include <common/Context.h> #include <cassert> #include <map> #include <glbinding/gl/gl.h> #include <glbinding/ContextInfo.h> #include <glbinding/ProcAddress.h> #include <glbinding/Binding.h> #include <glbinding/Version.h> #define GLFW_INCLUDE_NONE #include <GLFW/glfw3.h> // specifies APIENTRY, should be after Error.h include, // which requires APIENTRY in windows.. #include <globjects/globjects.h> #include <globjects/base/baselogging.h> #include <common/ContextFormat.h> using namespace gl; using namespace globjects; glbinding::Version Context::retrieveVersion() { assert(0 != glbinding::getCurrentContext()); GLint minorVersion = -1; GLint majorVersion = -1; glGetIntegerv(GLenum::GL_MAJOR_VERSION, &majorVersion); // major version glGetIntegerv(GLenum::GL_MINOR_VERSION, &minorVersion); // minor version if (minorVersion < 0 && majorVersion < 0) // probably a context < 3.0 with no support for GL_MAJOR/MINOR_VERSION { const GLubyte * vstr = glGetString(GLenum::GL_VERSION); if (!vstr) return glbinding::Version(); assert(vstr[1] == '.'); assert(vstr[0] >= '0' && vstr[0] <= '9'); majorVersion = vstr[0] - '0'; assert(vstr[2] >= '0' && vstr[2] <= '9'); minorVersion = vstr[2] - '0'; } return glbinding::Version(majorVersion, minorVersion); } glbinding::Version Context::maxSupportedVersion() { glbinding::Version version; /* GLFW3 does not set default hint values on window creation so at least the default values must be set before glfwCreateWindow can be called. cf. http://www.glfw.org/docs/latest/group__window.html#ga4fd9e504bb937e79588a0ffdca9f620b */ glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, false); #ifdef MAC_OS /* * Using OS X the following hints must be set for proper context initialization * (cf. http://stackoverflow.com/questions/19969937/getting-a-glsl-330-context-on-osx-10-9-mavericks) */ glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); #endif // create window for version check GLFWwindow * window = glfwCreateWindow(1, 1, "VersionCheck", nullptr, nullptr); if (window) { glfwMakeContextCurrent(window); glbinding::Binding::initialize(false); version = retrieveVersion(); glfwMakeContextCurrent(nullptr); glfwDestroyWindow(window); } return version; } GLFWwindow * Context::create( const ContextFormat & format , bool verify , int width , int height , GLFWmonitor * monitor) { glbinding::Version version = format.version(); if (verify) // check if version is valid and supported version = ContextFormat::validateVersion(format.version(), maxSupportedVersion()); /** GLFW3 does not set default hint values on window creation so at least the default values must be set before glfwCreateWindow can be called. cf. http://www.glfw.org/docs/latest/group__window.html#ga4fd9e504bb937e79588a0ffdca9f620b */ glfwDefaultWindowHints(); glfwWindowHint(GLFW_VISIBLE, true); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, version.m_major); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, version.m_minor); #ifdef MAC_OS glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #else if (version >= glbinding::Version(3, 0)) { glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, format.forwardCompatible()); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, format.debugContext()); } if (version >= glbinding::Version(3, 2)) { glfwWindowHint(GLFW_OPENGL_PROFILE, format.profile() == ContextFormat::Profile::Core ? GLFW_OPENGL_CORE_PROFILE : (format.profile() == ContextFormat::Profile::Compatibility ? GLFW_OPENGL_COMPAT_PROFILE : GLFW_OPENGL_ANY_PROFILE)); } #endif glfwWindowHint(GLFW_DEPTH_BITS, format.depthBufferSize()); glfwWindowHint(GLFW_STENCIL_BITS, format.stencilBufferSize()); glfwWindowHint(GLFW_RED_BITS, format.redBufferSize()); glfwWindowHint(GLFW_GREEN_BITS, format.greenBufferSize()); glfwWindowHint(GLFW_BLUE_BITS, format.blueBufferSize()); glfwWindowHint(GLFW_ALPHA_BITS, format.alphaBufferSize()); glfwWindowHint(GLFW_STEREO, format.stereo()); glfwWindowHint(GLFW_SAMPLES, format.samples()); GLFWwindow * window = glfwCreateWindow(width, height, "", monitor, nullptr); if (window) { glfwMakeContextCurrent(window); glbinding::Binding::initialize(false); glfwMakeContextCurrent(nullptr); } return window; } const std::string & Context::swapIntervalString(const SwapInterval interval) { static const std::map<SwapInterval, std::string> swapiIdentifier = { { SwapInterval::NoVerticalSyncronization, "NoVerticalSyncronization" } , { SwapInterval::VerticalSyncronization, "VerticalSyncronization" } , { SwapInterval::AdaptiveVerticalSyncronization, "AdaptiveVerticalSyncronization" } }; return swapiIdentifier.at(interval); } Context::Context(GLFWwindow * window) : m_swapInterval(SwapInterval::NoVerticalSyncronization) , m_format(nullptr) , m_window(window) , m_handle(0) { assert(window); if (!window) return; GLFWwindow * current = glfwGetCurrentContext(); if (current != m_window) glfwMakeContextCurrent(m_window); m_handle = tryFetchHandle(); if (current != m_window) glfwMakeContextCurrent(current); } Context::~Context() { delete m_format; } std::string Context::version() { assert(0 != glbinding::getCurrentContext()); return glbinding::ContextInfo::version().toString(); } std::string Context::vendor() { assert(0 != glbinding::getCurrentContext()); return glbinding::ContextInfo::vendor(); } std::string Context::renderer() { assert(0 != glbinding::getCurrentContext()); return glbinding::ContextInfo::renderer(); } bool Context::isValid() const { return 0 < handle(); } glbinding::ContextHandle Context::tryFetchHandle() { const glbinding::ContextHandle handle = glbinding::getCurrentContext(); if (0 == handle) critical("Acquiring OpenGL context handle failed."); return handle; } Context::SwapInterval Context::swapInterval() const { return m_swapInterval; } void Context::setSwapInterval(const SwapInterval interval) { //if (interval == m_swapInterval) // initialized value might not match or explicit reset might be required // return true; GLFWwindow * current = glfwGetCurrentContext(); if (current != m_window) glfwMakeContextCurrent(m_window); #ifdef WIN32 using SWAPINTERVALEXTPROC = bool(*)(int); static SWAPINTERVALEXTPROC wglSwapIntervalEXT(nullptr); bool result(false); if (!wglSwapIntervalEXT) wglSwapIntervalEXT = reinterpret_cast<SWAPINTERVALEXTPROC>(glbinding::getProcAddress("wglSwapIntervalEXT")); if (wglSwapIntervalEXT) result = wglSwapIntervalEXT(static_cast<int>(interval)); if(!result) warning("Setting swap interval to % failed.", swapIntervalString(interval)); #else glfwSwapInterval(static_cast<int>(interval)); #endif if (current != m_window) glfwMakeContextCurrent(current); m_swapInterval = interval; } glbinding::ContextHandle Context::handle() const { return m_handle; } const ContextFormat & Context::format() const { assert(isValid()); if (m_format) return *m_format; // create and retrive format if not done already m_format = new ContextFormat(); GLFWwindow * current = glfwGetCurrentContext(); if (current != m_window) glfwMakeContextCurrent(m_window); m_format->setVersion(retrieveVersion()); if (m_format->version() >= glbinding::Version(3, 2)) m_format->setProfile(isCoreProfile() ? ContextFormat::Profile::Core : ContextFormat::Profile::Compatibility); else m_format->setProfile(ContextFormat::Profile::None); if (current != m_window) glfwMakeContextCurrent(current); //GLint i; //GLboolean b; //i = -1; glGetIntegerv(GLenum::GL_DEPTH_BITS, &i); //m_format->setDepthBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_STENCIL_BITS, &i); //m_format->setStencilBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_RED_BITS, &i); //m_format->setRedBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_GREEN_BITS, &i); //m_format->setGreenBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_BLUE_BITS, &i); //m_format->setBlueBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_ALPHA_BITS, &i); //m_format->setAlphaBufferSize(i); //i = -1; glGetIntegerv(GLenum::GL_SAMPLES, &i); //m_format->setSamples(i); //b = GL_FALSE; glGetBooleanv(GLenum::GL_STEREO, &b); //m_format->setStereo(b == GL_TRUE); return *m_format; } void Context::makeCurrent() const { if (m_window) glfwMakeContextCurrent(m_window); } void Context::doneCurrent() const { if (m_window && m_window == glfwGetCurrentContext()) glfwMakeContextCurrent(nullptr); } <|endoftext|>
<commit_before><commit_msg>vcl: Add list of contexts sharing the same display list<commit_after><|endoftext|>
<commit_before> #include <iostream> #include <QGuiApplication> #include <QQmlFileSelector> #include <QStringList> #include <QTranslator> #include <QDebug> #include <qmltoolbox/qmltoolbox-version.h> #include <qmltoolbox/QmlApplicationEngine.h> #include <qmltoolbox/MessageHandler.h> int main(int argc, char *argv[]) { // qInstallMessageHandler(qmltoolbox::globalMessageHandler); qmltoolbox::MessageHandler::instance().installStdHandlers(); #ifndef QMLTOOLBOX_QT57 QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); app.setOrganizationName(QMLTOOLBOX_AUTHOR_ORGANIZATION); app.setOrganizationDomain("cginternals.com"); app.setApplicationName(QString(QMLTOOLBOX_PROJECT_NAME) + "_uiconcept"); // Create QtQuick engine qmltoolbox::QmlApplicationEngine engine; // Setup Localization QTranslator translator; translator.load(QLocale::system(), "uiconcept", ".", engine.qmlToolboxModulePath() + "/examples/uiconcept/i18n"); app.installTranslator(&translator); #ifdef QMLTOOLBOX_QT54 auto fileSelector = QQmlFileSelector::get(&engine); fileSelector->setExtraSelectors(QStringList{ QMLTOOLBOX_QT54 }); #endif // Load and show QML engine.load(QUrl::fromLocalFile(engine.qmlToolboxModulePath() + "/examples/uiconcept/window.qml")); qDebug() << "qDebug() message \n with line break"; std::cout << "std::cout w/o line break"; std::cout << std::endl << "hallo"; std::cout << "std::cerr w/o line break"; // Run application int res = app.exec(); // Stop application return res; } <commit_msg>Remove debugging code<commit_after> #include <QGuiApplication> #include <QQmlFileSelector> #include <QStringList> #include <QTranslator> #include <qmltoolbox/qmltoolbox-version.h> #include <qmltoolbox/QmlApplicationEngine.h> #include <qmltoolbox/MessageHandler.h> int main(int argc, char *argv[]) { qInstallMessageHandler(qmltoolbox::globalMessageHandler); qmltoolbox::MessageHandler::instance().installStdHandlers(); #ifndef QMLTOOLBOX_QT57 QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QGuiApplication app(argc, argv); app.setOrganizationName(QMLTOOLBOX_AUTHOR_ORGANIZATION); app.setOrganizationDomain("cginternals.com"); app.setApplicationName(QString(QMLTOOLBOX_PROJECT_NAME) + "_uiconcept"); // Create QtQuick engine qmltoolbox::QmlApplicationEngine engine; // Setup Localization QTranslator translator; translator.load(QLocale::system(), "uiconcept", ".", engine.qmlToolboxModulePath() + "/examples/uiconcept/i18n"); app.installTranslator(&translator); #ifdef QMLTOOLBOX_QT54 auto fileSelector = QQmlFileSelector::get(&engine); fileSelector->setExtraSelectors(QStringList{ QMLTOOLBOX_QT54 }); #endif // Load and show QML engine.load(QUrl::fromLocalFile(engine.qmlToolboxModulePath() + "/examples/uiconcept/window.qml")); // Run application int res = app.exec(); // Stop application return res; } <|endoftext|>
<commit_before><commit_msg>-Werror=unused-function<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkExceptionObject.h" #include "otbUnaryFunctorNeighborhoodImageFilter.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" namespace Functor { template <class TIter, class TOutput> class UnaryFunctorNeighborhoodImageFilterFunctorNewTest { public: UnaryFunctorNeighborhoodImageFilterFunctorNewTest() {}; ~UnaryFunctorNeighborhoodImageFilterFunctorNewTest() {}; inline TOutput operator() (const TIter & it) { return(static_cast<TOutput>(it.GetCenterPixel())); } }; } int otbUnaryFunctorNeighborhoodImageFilter(int argc, char * argv[]) { const char * inputFileName = argv[1]; const char * outputFileName = argv[2]; typedef double InputPixelType; const int Dimension = 2; typedef otb::Image<InputPixelType,Dimension> ImageType; typedef ImageType::PixelType PixelType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; typedef itk::ConstNeighborhoodIterator<ImageType> IterType;; typedef Functor::UnaryFunctorNeighborhoodImageFilterFunctorNewTest<IterType, PixelType> FunctorType; typedef otb::UnaryFunctorNeighborhoodImageFilter<ImageType, ImageType, FunctorType> UnaryFunctorNeighborhoodImageFilterType; // Instantiating object UnaryFunctorNeighborhoodImageFilterType::Pointer object = UnaryFunctorNeighborhoodImageFilterType::New(); ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName(inputFileName); writer->SetFileName(outputFileName); object->SetInput(reader->GetOutput()); object->SetRadius(atoi(argv[3])); writer->SetInput(object->GetOutput()); writer->Update(); return EXIT_SUCCESS; } <commit_msg>STYLE: Renaming double declared FunctorNew.<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkExceptionObject.h" #include "otbUnaryFunctorNeighborhoodImageFilter.h" #include "otbImage.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" namespace Functor { template <class TIter, class TOutput> class UnaryFunctorNeighborhoodImageFilterTest { public: UnaryFunctorNeighborhoodImageFilterTest() {}; ~UnaryFunctorNeighborhoodImageFilterTest() {}; inline TOutput operator() (const TIter & it) { return(static_cast<TOutput>(it.GetCenterPixel())); } }; } int otbUnaryFunctorNeighborhoodImageFilter(int argc, char * argv[]) { const char * inputFileName = argv[1]; const char * outputFileName = argv[2]; typedef double InputPixelType; const int Dimension = 2; typedef otb::Image<InputPixelType,Dimension> ImageType; typedef ImageType::PixelType PixelType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::ImageFileWriter<ImageType> WriterType; typedef itk::ConstNeighborhoodIterator<ImageType> IterType;; typedef Functor::UnaryFunctorNeighborhoodImageFilterTest<IterType, PixelType> FunctorType; typedef otb::UnaryFunctorNeighborhoodImageFilter<ImageType, ImageType, FunctorType> UnaryFunctorNeighborhoodImageFilterType; // Instantiating object UnaryFunctorNeighborhoodImageFilterType::Pointer object = UnaryFunctorNeighborhoodImageFilterType::New(); ReaderType::Pointer reader = ReaderType::New(); WriterType::Pointer writer = WriterType::New(); reader->SetFileName(inputFileName); writer->SetFileName(outputFileName); object->SetInput(reader->GetOutput()); object->SetRadius(atoi(argv[3])); writer->SetInput(object->GetOutput()); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> extern "C" { #include <ei.h> #include <erl_interface.h> extern const char *erl_thisnodename(void); extern short erl_thiscreation(void); #define SELF(fd) erl_mk_pid(erl_thisnodename(), fd, 0, erl_thiscreation()) } using namespace node; using namespace v8; class ErlNode: ObjectWrap { private: int m_count; int sockfd; ETERM* self; public: static Persistent<FunctionTemplate> s_ct; static void Init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); s_ct = Persistent<FunctionTemplate>::New(t); s_ct->InstanceTemplate()->SetInternalFieldCount(1); s_ct->SetClassName(String::NewSymbol("ErlNode")); NODE_SET_PROTOTYPE_METHOD(s_ct, "send_by_name", SendByName); NODE_SET_PROTOTYPE_METHOD(s_ct, "receive", Receive); NODE_SET_PROTOTYPE_METHOD(s_ct, "count", Count); NODE_SET_PROTOTYPE_METHOD(s_ct, "args", Args); NODE_SET_PROTOTYPE_METHOD(s_ct, "info", Info); target->Set(String::NewSymbol("ErlNode"), s_ct->GetFunction()); } ErlNode() : m_count(0){} ~ErlNode(){} static Handle<Value> New(const Arguments& args) { HandleScope scope; ErlNode* hw = new ErlNode(); String::AsciiValue nodename(args[0]); String::AsciiValue cookie(args[1]); erl_init(NULL, 0); //char *cookie = "secret"; //char *nodename = "e1@localhost"; if(erl_connect_init(1, *cookie, 1) == -1) { erl_err_quit("ERROR: erl_connect_init failed"); } int sockfd = -1; if((sockfd = erl_connect(*nodename)) == -1) { erl_err_quit("ERROR: erl_connect failed"); } hw->sockfd = sockfd; hw->self = SELF(sockfd); hw->Wrap(args.This()); return args.This(); } static Handle<Value> Receive(const Arguments& args) { HandleScope scope; ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); int sockfd = hw->sockfd; // Receive msg int BUFSIZE = 128; unsigned char buf[BUFSIZE]; ErlMessage emsg; ETERM *msg; int status = -1; status = erl_receive_msg(sockfd, buf, BUFSIZE, &emsg); if(status == -1) { return scope.Close(Undefined()); } while (status == ERL_TICK) { status = erl_receive_msg(sockfd, buf, BUFSIZE, &emsg); } msg = emsg.msg; if(ERL_IS_LIST(msg)) { char* pp; pp = erl_iolist_to_string(msg); Local<String> result = String::New(pp); return scope.Close(result); } else { char* pp; pp = erl_iolist_to_string(msg); Local<String> result = String::New(pp); return scope.Close(result); } } static Handle<Value> SendByName(const Arguments& args) { HandleScope scope; ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); hw->m_count++; int sockfd = hw->sockfd; ETERM *self = hw->self; String::AsciiValue pname(args[0]); String::AsciiValue eformat(args[1]); //String::AsciiValue _self(args[2]); String::AsciiValue command(args[3]); ETERM *ep; ep = erl_format(*eformat, self, *command); erl_reg_send(sockfd, *pname, ep); erl_free_term(ep); Local<Integer> result = Integer::New(1); return scope.Close(result); } static Handle<Value> Count(const Arguments& args) { HandleScope scope; ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); Local<Integer> result = Integer::New(hw->m_count); return scope.Close(result); } static Handle<Value> Info(const Arguments& args) { HandleScope scope; ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); Local<Object> info = Object::New(); Local<String> node_name = String::New(ERL_PID_NODE(hw->self)); info->Set(String::NewSymbol("node_name"), node_name); //Local<String> result = String::New(ERL_PID_NODE(hw->self)); //Local<String> result = String::New(erl_thisnodename()); return scope.Close(info); } static Handle<Value> Args(const Arguments& args) { HandleScope scope; //ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); Local<String> result = args[0]->ToString(); return scope.Close(result); } }; Persistent<FunctionTemplate> ErlNode::s_ct; static void init (Handle<Object> target) { ErlNode::Init(target); } NODE_MODULE(erlnode, init);<commit_msg>Updated.<commit_after>#include <v8.h> #include <node.h> extern "C" { #include <ei.h> #include <erl_interface.h> extern const char *erl_thisnodename(void); extern short erl_thiscreation(void); #define SELF(fd) erl_mk_pid(erl_thisnodename(), fd, 0, erl_thiscreation()) } using namespace node; using namespace v8; class ErlNode: ObjectWrap { private: int m_count; int sockfd; ETERM* self; public: ErlNode() : m_count(0){} ~ErlNode(){} static Persistent<FunctionTemplate> s_erlnode; static void Init(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); s_erlnode = Persistent<FunctionTemplate>::New(t); s_erlnode->InstanceTemplate()->SetInternalFieldCount(1); s_erlnode->SetClassName(String::NewSymbol("ErlNode")); NODE_SET_PROTOTYPE_METHOD(s_erlnode, "send_by_name", SendByName); NODE_SET_PROTOTYPE_METHOD(s_erlnode, "receive", Receive); NODE_SET_PROTOTYPE_METHOD(s_erlnode, "count", Count); NODE_SET_PROTOTYPE_METHOD(s_erlnode, "args", Args); NODE_SET_PROTOTYPE_METHOD(s_erlnode, "info", Info); target->Set(String::NewSymbol("ErlNode"), s_erlnode->GetFunction()); } static Handle<Value> New(const Arguments& args) { HandleScope scope; ErlNode* hw = new ErlNode(); String::AsciiValue nodename(args[0]); String::AsciiValue cookie(args[1]); erl_init(NULL, 0); //char *cookie = "secret"; //char *nodename = "e1@localhost"; if(erl_connect_init(1, *cookie, 1) == -1) { erl_err_quit("ERROR: erl_connect_init failed"); } int sockfd = -1; if((sockfd = erl_connect(*nodename)) == -1) { erl_err_quit("ERROR: erl_connect failed"); } hw->sockfd = sockfd; hw->self = SELF(sockfd); hw->Wrap(args.This()); return args.This(); } static Handle<Value> Receive(const Arguments& args) { HandleScope scope; ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); int sockfd = hw->sockfd; // Receive msg int BUFSIZE = 128; unsigned char buf[BUFSIZE]; ErlMessage emsg; ETERM *msg; int status = -1; status = erl_receive_msg(sockfd, buf, BUFSIZE, &emsg); if(status == -1) { return scope.Close(Undefined()); } while (status == ERL_TICK) { status = erl_receive_msg(sockfd, buf, BUFSIZE, &emsg); } msg = emsg.msg; if(ERL_IS_LIST(msg)) { char* pp; pp = erl_iolist_to_string(msg); Local<String> result = String::New(pp); return scope.Close(result); } else { char* pp; pp = erl_iolist_to_string(msg); Local<String> result = String::New(pp); return scope.Close(result); } } static Handle<Value> SendByName(const Arguments& args) { HandleScope scope; ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); hw->m_count++; int sockfd = hw->sockfd; ETERM *self = hw->self; String::AsciiValue pname(args[0]); String::AsciiValue eformat(args[1]); //String::AsciiValue _self(args[2]); String::AsciiValue command(args[3]); ETERM *ep; ep = erl_format(*eformat, self, *command); erl_reg_send(sockfd, *pname, ep); erl_free_term(ep); Local<Integer> result = Integer::New(1); return scope.Close(result); } static Handle<Value> Count(const Arguments& args) { HandleScope scope; ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); Local<Integer> result = Integer::New(hw->m_count); return scope.Close(result); } static Handle<Value> Info(const Arguments& args) { HandleScope scope; ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); Local<Object> info = Object::New(); Local<String> node_name = String::New(ERL_PID_NODE(hw->self)); info->Set(String::NewSymbol("node_name"), node_name); //Local<String> result = String::New(ERL_PID_NODE(hw->self)); //Local<String> result = String::New(erl_thisnodename()); return scope.Close(info); } static Handle<Value> Args(const Arguments& args) { HandleScope scope; //ErlNode* hw = ObjectWrap::Unwrap<ErlNode>(args.This()); Local<String> result = args[0]->ToString(); return scope.Close(result); } }; Persistent<FunctionTemplate> ErlNode::s_erlnode; static void init (Handle<Object> target) { ErlNode::Init(target); } NODE_MODULE(erlnode, init);<|endoftext|>
<commit_before>/*************************************************************************/ /* split_container.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "split_container.h" #include "margin_container.h" #include "label.h" struct _MinSizeCache { int min_size; bool will_stretch; int final_size; }; Control *SplitContainer::_getch(int p_idx) const { int idx=0; for(int i=0;i<get_child_count();i++) { Control *c=get_child(i)->cast_to<Control>(); if (!c || !c->is_visible()) continue; if (c->is_set_as_toplevel()) continue; if (idx==p_idx) return c; idx++; } return NULL; } void SplitContainer::_resort() { /** First pass, determine minimum size AND amount of stretchable elements */ int axis = vertical?1:0; bool has_first=_getch(0); bool has_second=_getch(1); if (!has_first && !has_second) { return; } else if (! (has_first && has_second)) { if (has_first) fit_child_in_rect(_getch(0),Rect2(Point2(),get_size())); else fit_child_in_rect(_getch(1),Rect2(Point2(),get_size())); return; } Control *first=_getch(0); Control *second=_getch(1); bool ratiomode=false; bool expand_first_mode=false; if (vertical) { ratiomode=first->get_v_size_flags()&SIZE_EXPAND && second->get_v_size_flags()&SIZE_EXPAND; expand_first_mode=first->get_v_size_flags()&SIZE_EXPAND && !(second->get_v_size_flags()&SIZE_EXPAND); } else { ratiomode=first->get_h_size_flags()&SIZE_EXPAND && second->get_h_size_flags()&SIZE_EXPAND; expand_first_mode=first->get_h_size_flags()&SIZE_EXPAND && !(second->get_h_size_flags()&SIZE_EXPAND); } int sep=get_constant("separation"); Ref<Texture> g = get_icon("grabber"); if (collapsed || !dragger_visible) { sep=0; } else { sep=MAX(sep,vertical?g->get_height():g->get_width()); } int total = vertical?get_size().height:get_size().width; total-=sep; int minimum=0; Size2 ms_first = first->get_combined_minimum_size(); Size2 ms_second = second->get_combined_minimum_size(); if (vertical) { minimum=ms_first.height+ms_second.height; } else { minimum=ms_first.width+ms_second.width; } int available=total-minimum; if (available<0) available=0; middle_sep=0; if (collapsed) { if (ratiomode) { middle_sep=ms_first[axis]+available/2; } else if (expand_first_mode) { middle_sep=get_size()[axis]-ms_second[axis]-sep; } else { middle_sep=ms_first[axis]; } } else if (ratiomode) { if (expand_ofs<-(available/2)) expand_ofs=-(available/2); else if (expand_ofs>(available/2)) expand_ofs=(available/2); middle_sep=ms_first[axis]+available/2+expand_ofs; } else if (expand_first_mode) { if (expand_ofs>0) expand_ofs=0; if (expand_ofs < -available) expand_ofs=-available; middle_sep=get_size()[axis]-ms_second[axis]-sep+expand_ofs; } else { if (expand_ofs<0) expand_ofs=0; if (expand_ofs > available) expand_ofs=available; middle_sep=ms_first[axis]+expand_ofs; } if (vertical) { fit_child_in_rect(first,Rect2(Point2(0,0),Size2(get_size().width,middle_sep))); int sofs=middle_sep+sep; fit_child_in_rect(second,Rect2(Point2(0,sofs),Size2(get_size().width,get_size().height-sofs))); } else { fit_child_in_rect(first,Rect2(Point2(0,0),Size2(middle_sep,get_size().height))); int sofs=middle_sep+sep; fit_child_in_rect(second,Rect2(Point2(sofs,0),Size2(get_size().width-sofs,get_size().height))); } update(); _change_notify("split/offset"); } Size2 SplitContainer::get_minimum_size() const { /* Calculate MINIMUM SIZE */ Size2i minimum; int sep=get_constant("separation"); Ref<Texture> g = get_icon("grabber"); sep=dragger_visible?MAX(sep,vertical?g->get_height():g->get_width()):0; for(int i=0;i<2;i++) { if (!_getch(i)) break; if (i==1) { if (vertical) minimum.height+=sep; else minimum.width+=sep; } Size2 ms = _getch(i)->get_combined_minimum_size(); if (vertical) { minimum.height+=ms.height; minimum.width=MAX(minimum.width,ms.width); } else { minimum.width+=ms.width; minimum.height=MAX(minimum.height,ms.height); } } return minimum; } void SplitContainer::_notification(int p_what) { switch(p_what) { case NOTIFICATION_SORT_CHILDREN: { _resort(); } break; case NOTIFICATION_MOUSE_ENTER: { mouse_inside=true; update(); } break; case NOTIFICATION_MOUSE_EXIT: { mouse_inside=false; update(); } break; case NOTIFICATION_DRAW: { if (!_getch(0) || !_getch(1)) return; if (collapsed || (!mouse_inside && get_constant("autohide"))) return; int sep=dragger_visible?get_constant("separation"):0; Ref<Texture> tex = get_icon("grabber"); Size2 size=get_size(); if (vertical) { //draw_style_box( get_stylebox("bg"), Rect2(0,middle_sep,get_size().width,sep)); if (dragger_visible) draw_texture(tex,Point2i((size.x-tex->get_width())/2,middle_sep+(sep-tex->get_height())/2)); } else { //draw_style_box( get_stylebox("bg"), Rect2(middle_sep,0,sep,get_size().height)); if (dragger_visible) draw_texture(tex,Point2i(middle_sep+(sep-tex->get_width())/2,(size.y-tex->get_height())/2)); } } break; } } void SplitContainer::_input_event(const InputEvent& p_event) { if (collapsed || !_getch(0) || !_getch(1) || !dragger_visible) return; if (p_event.type==InputEvent::MOUSE_BUTTON) { const InputEventMouseButton &mb=p_event.mouse_button; if (mb.button_index==BUTTON_LEFT) { if (mb.pressed) { int sep=get_constant("separation"); if (vertical) { if (mb.y > middle_sep && mb.y < middle_sep+sep) { dragging=true; drag_from=mb.y; drag_ofs=expand_ofs; } } else { if (mb.x > middle_sep && mb.x < middle_sep+sep) { dragging=true; drag_from=mb.x; drag_ofs=expand_ofs; } } } else { dragging=false; } } } if (p_event.type==InputEvent::MOUSE_MOTION) { const InputEventMouseMotion &mm=p_event.mouse_motion; if (dragging) { expand_ofs=drag_ofs+((vertical?mm.y:mm.x)-drag_from); queue_sort(); emit_signal("dragged",get_split_offset()); } } } Control::CursorShape SplitContainer::get_cursor_shape(const Point2& p_pos) { if (collapsed) return Control::get_cursor_shape(p_pos); if (dragging) return (vertical?CURSOR_VSIZE:CURSOR_HSIZE); int sep=get_constant("separation"); if (vertical) { if (p_pos.y > middle_sep && p_pos.y < middle_sep+sep) { return CURSOR_VSIZE; } } else { if (p_pos.x > middle_sep && p_pos.x < middle_sep+sep) { return CURSOR_HSIZE; } } return Control::get_cursor_shape(p_pos); } void SplitContainer::set_split_offset(int p_offset) { if (expand_ofs==p_offset) return; expand_ofs=p_offset; queue_sort(); } int SplitContainer::get_split_offset() const { return expand_ofs; } void SplitContainer::set_collapsed(bool p_collapsed) { if (collapsed==p_collapsed) return; collapsed=p_collapsed; queue_sort(); } void SplitContainer::set_dragger_visible(bool p_true) { dragger_visible=p_true; queue_sort(); update(); } bool SplitContainer::is_dragger_visible() const{ return dragger_visible; } bool SplitContainer::is_collapsed() const { return collapsed; } void SplitContainer::_bind_methods() { ObjectTypeDB::bind_method(_MD("_input_event"),&SplitContainer::_input_event); ObjectTypeDB::bind_method(_MD("set_split_offset","offset"),&SplitContainer::set_split_offset); ObjectTypeDB::bind_method(_MD("get_split_offset"),&SplitContainer::get_split_offset); ObjectTypeDB::bind_method(_MD("set_collapsed","collapsed"),&SplitContainer::set_collapsed); ObjectTypeDB::bind_method(_MD("is_collapsed"),&SplitContainer::is_collapsed); ObjectTypeDB::bind_method(_MD("set_dragger_visible","visible"),&SplitContainer::set_dragger_visible); ObjectTypeDB::bind_method(_MD("is_dragger_visible"),&SplitContainer::is_dragger_visible); ADD_SIGNAL( MethodInfo("dragged",PropertyInfo(Variant::INT,"offset"))); ADD_PROPERTY( PropertyInfo(Variant::INT,"split/offset"),_SCS("set_split_offset"),_SCS("get_split_offset")); ADD_PROPERTY( PropertyInfo(Variant::INT,"split/collapsed"),_SCS("set_collapsed"),_SCS("is_collapsed")); ADD_PROPERTY( PropertyInfo(Variant::INT,"split/dragger_visible"),_SCS("set_dragger_visible"),_SCS("is_dragger_visible")); } SplitContainer::SplitContainer(bool p_vertical) { mouse_inside=false; expand_ofs=0; middle_sep=0; vertical=p_vertical; dragging=false; collapsed=false; dragger_visible=true; } <commit_msg>Fix SplitContainer bool properties<commit_after>/*************************************************************************/ /* split_container.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "split_container.h" #include "margin_container.h" #include "label.h" struct _MinSizeCache { int min_size; bool will_stretch; int final_size; }; Control *SplitContainer::_getch(int p_idx) const { int idx=0; for(int i=0;i<get_child_count();i++) { Control *c=get_child(i)->cast_to<Control>(); if (!c || !c->is_visible()) continue; if (c->is_set_as_toplevel()) continue; if (idx==p_idx) return c; idx++; } return NULL; } void SplitContainer::_resort() { /** First pass, determine minimum size AND amount of stretchable elements */ int axis = vertical?1:0; bool has_first=_getch(0); bool has_second=_getch(1); if (!has_first && !has_second) { return; } else if (! (has_first && has_second)) { if (has_first) fit_child_in_rect(_getch(0),Rect2(Point2(),get_size())); else fit_child_in_rect(_getch(1),Rect2(Point2(),get_size())); return; } Control *first=_getch(0); Control *second=_getch(1); bool ratiomode=false; bool expand_first_mode=false; if (vertical) { ratiomode=first->get_v_size_flags()&SIZE_EXPAND && second->get_v_size_flags()&SIZE_EXPAND; expand_first_mode=first->get_v_size_flags()&SIZE_EXPAND && !(second->get_v_size_flags()&SIZE_EXPAND); } else { ratiomode=first->get_h_size_flags()&SIZE_EXPAND && second->get_h_size_flags()&SIZE_EXPAND; expand_first_mode=first->get_h_size_flags()&SIZE_EXPAND && !(second->get_h_size_flags()&SIZE_EXPAND); } int sep=get_constant("separation"); Ref<Texture> g = get_icon("grabber"); if (collapsed || !dragger_visible) { sep=0; } else { sep=MAX(sep,vertical?g->get_height():g->get_width()); } int total = vertical?get_size().height:get_size().width; total-=sep; int minimum=0; Size2 ms_first = first->get_combined_minimum_size(); Size2 ms_second = second->get_combined_minimum_size(); if (vertical) { minimum=ms_first.height+ms_second.height; } else { minimum=ms_first.width+ms_second.width; } int available=total-minimum; if (available<0) available=0; middle_sep=0; if (collapsed) { if (ratiomode) { middle_sep=ms_first[axis]+available/2; } else if (expand_first_mode) { middle_sep=get_size()[axis]-ms_second[axis]-sep; } else { middle_sep=ms_first[axis]; } } else if (ratiomode) { if (expand_ofs<-(available/2)) expand_ofs=-(available/2); else if (expand_ofs>(available/2)) expand_ofs=(available/2); middle_sep=ms_first[axis]+available/2+expand_ofs; } else if (expand_first_mode) { if (expand_ofs>0) expand_ofs=0; if (expand_ofs < -available) expand_ofs=-available; middle_sep=get_size()[axis]-ms_second[axis]-sep+expand_ofs; } else { if (expand_ofs<0) expand_ofs=0; if (expand_ofs > available) expand_ofs=available; middle_sep=ms_first[axis]+expand_ofs; } if (vertical) { fit_child_in_rect(first,Rect2(Point2(0,0),Size2(get_size().width,middle_sep))); int sofs=middle_sep+sep; fit_child_in_rect(second,Rect2(Point2(0,sofs),Size2(get_size().width,get_size().height-sofs))); } else { fit_child_in_rect(first,Rect2(Point2(0,0),Size2(middle_sep,get_size().height))); int sofs=middle_sep+sep; fit_child_in_rect(second,Rect2(Point2(sofs,0),Size2(get_size().width-sofs,get_size().height))); } update(); _change_notify("split/offset"); } Size2 SplitContainer::get_minimum_size() const { /* Calculate MINIMUM SIZE */ Size2i minimum; int sep=get_constant("separation"); Ref<Texture> g = get_icon("grabber"); sep=dragger_visible?MAX(sep,vertical?g->get_height():g->get_width()):0; for(int i=0;i<2;i++) { if (!_getch(i)) break; if (i==1) { if (vertical) minimum.height+=sep; else minimum.width+=sep; } Size2 ms = _getch(i)->get_combined_minimum_size(); if (vertical) { minimum.height+=ms.height; minimum.width=MAX(minimum.width,ms.width); } else { minimum.width+=ms.width; minimum.height=MAX(minimum.height,ms.height); } } return minimum; } void SplitContainer::_notification(int p_what) { switch(p_what) { case NOTIFICATION_SORT_CHILDREN: { _resort(); } break; case NOTIFICATION_MOUSE_ENTER: { mouse_inside=true; update(); } break; case NOTIFICATION_MOUSE_EXIT: { mouse_inside=false; update(); } break; case NOTIFICATION_DRAW: { if (!_getch(0) || !_getch(1)) return; if (collapsed || (!mouse_inside && get_constant("autohide"))) return; int sep=dragger_visible?get_constant("separation"):0; Ref<Texture> tex = get_icon("grabber"); Size2 size=get_size(); if (vertical) { //draw_style_box( get_stylebox("bg"), Rect2(0,middle_sep,get_size().width,sep)); if (dragger_visible) draw_texture(tex,Point2i((size.x-tex->get_width())/2,middle_sep+(sep-tex->get_height())/2)); } else { //draw_style_box( get_stylebox("bg"), Rect2(middle_sep,0,sep,get_size().height)); if (dragger_visible) draw_texture(tex,Point2i(middle_sep+(sep-tex->get_width())/2,(size.y-tex->get_height())/2)); } } break; } } void SplitContainer::_input_event(const InputEvent& p_event) { if (collapsed || !_getch(0) || !_getch(1) || !dragger_visible) return; if (p_event.type==InputEvent::MOUSE_BUTTON) { const InputEventMouseButton &mb=p_event.mouse_button; if (mb.button_index==BUTTON_LEFT) { if (mb.pressed) { int sep=get_constant("separation"); if (vertical) { if (mb.y > middle_sep && mb.y < middle_sep+sep) { dragging=true; drag_from=mb.y; drag_ofs=expand_ofs; } } else { if (mb.x > middle_sep && mb.x < middle_sep+sep) { dragging=true; drag_from=mb.x; drag_ofs=expand_ofs; } } } else { dragging=false; } } } if (p_event.type==InputEvent::MOUSE_MOTION) { const InputEventMouseMotion &mm=p_event.mouse_motion; if (dragging) { expand_ofs=drag_ofs+((vertical?mm.y:mm.x)-drag_from); queue_sort(); emit_signal("dragged",get_split_offset()); } } } Control::CursorShape SplitContainer::get_cursor_shape(const Point2& p_pos) { if (collapsed) return Control::get_cursor_shape(p_pos); if (dragging) return (vertical?CURSOR_VSIZE:CURSOR_HSIZE); int sep=get_constant("separation"); if (vertical) { if (p_pos.y > middle_sep && p_pos.y < middle_sep+sep) { return CURSOR_VSIZE; } } else { if (p_pos.x > middle_sep && p_pos.x < middle_sep+sep) { return CURSOR_HSIZE; } } return Control::get_cursor_shape(p_pos); } void SplitContainer::set_split_offset(int p_offset) { if (expand_ofs==p_offset) return; expand_ofs=p_offset; queue_sort(); } int SplitContainer::get_split_offset() const { return expand_ofs; } void SplitContainer::set_collapsed(bool p_collapsed) { if (collapsed==p_collapsed) return; collapsed=p_collapsed; queue_sort(); } void SplitContainer::set_dragger_visible(bool p_true) { dragger_visible=p_true; queue_sort(); update(); } bool SplitContainer::is_dragger_visible() const{ return dragger_visible; } bool SplitContainer::is_collapsed() const { return collapsed; } void SplitContainer::_bind_methods() { ObjectTypeDB::bind_method(_MD("_input_event"),&SplitContainer::_input_event); ObjectTypeDB::bind_method(_MD("set_split_offset","offset"),&SplitContainer::set_split_offset); ObjectTypeDB::bind_method(_MD("get_split_offset"),&SplitContainer::get_split_offset); ObjectTypeDB::bind_method(_MD("set_collapsed","collapsed"),&SplitContainer::set_collapsed); ObjectTypeDB::bind_method(_MD("is_collapsed"),&SplitContainer::is_collapsed); ObjectTypeDB::bind_method(_MD("set_dragger_visible","visible"),&SplitContainer::set_dragger_visible); ObjectTypeDB::bind_method(_MD("is_dragger_visible"),&SplitContainer::is_dragger_visible); ADD_SIGNAL( MethodInfo("dragged",PropertyInfo(Variant::INT,"offset"))); ADD_PROPERTY( PropertyInfo(Variant::INT,"split/offset"),_SCS("set_split_offset"),_SCS("get_split_offset")); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"split/collapsed"),_SCS("set_collapsed"),_SCS("is_collapsed")); ADD_PROPERTY( PropertyInfo(Variant::BOOL,"split/dragger_visible"),_SCS("set_dragger_visible"),_SCS("is_dragger_visible")); } SplitContainer::SplitContainer(bool p_vertical) { mouse_inside=false; expand_ofs=0; middle_sep=0; vertical=p_vertical; dragging=false; collapsed=false; dragger_visible=true; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #include "../StroikaPreComp.h" #include <cstdarg> #include <cstdlib> #include <iomanip> #include <limits> #include <sstream> #include "../Characters/StringBuilder.h" #include "../Characters/String_Constant.h" #include "../Containers/Common.h" #include "../Debug/Assertions.h" #include "../Debug/Trace.h" #include "../Math/Common.h" #include "../Memory/SmallStackBuffer.h" #include "CodePage.h" #include "FloatConversion.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Memory; /* ******************************************************************************** ************************** Float2StringOptions ********************************* ******************************************************************************** */ Float2StringOptions::Float2StringOptions (UseCurrentLocale) : fUseLocale_ (locale{}) { } String Float2StringOptions::ToString () const { StringBuilder sb; sb += L"{"; if (fPrecision_) { sb += L"Precision:" + Characters::ToString ((int)*fPrecision_) + L","; } if (fFmtFlags_) { sb += L"Fmt-Flags:" + Characters::ToString ((int)*fFmtFlags_) + L","; } if (fUseLocale_) { sb += L"Use-Locale" + String::FromNarrowSDKString (fUseLocale_->name ()) + L","; } if (fTrimTrailingZeros_) { sb += L"Trim-Trailing-Zeros: " + Characters::ToString (*fTrimTrailingZeros_) + L","; } if (fFloatFormat_) { sb += L"Scientific-Notation: " + Characters::ToString ((int)*fFloatFormat_) + L","; } sb += L"}"; return sb.str (); } /* ******************************************************************************** ********************************* Float2String ********************************* ******************************************************************************** */ namespace { inline void TrimTrailingZeros_ (String* strResult) { RequireNotNull (strResult); // strip trailing zeros - except for the last first one after the decimal point. // And don't do if ends with exponential notation e+40 shouldnt get shortned to e+4! bool hasE = strResult->Find ('e', CompareOptions::eCaseInsensitive).has_value (); //Assert (hasE == (strResult->find ('e') != String::npos or strResult->find ('E') != String::npos)); if (not hasE) { size_t pastDot = strResult->find ('.'); if (pastDot != String::npos) { pastDot++; size_t pPastLastZero = strResult->length (); for (; (pPastLastZero - 1) > pastDot; --pPastLastZero) { if ((*strResult)[pPastLastZero - 1] != '0') { break; } } *strResult = strResult->SubString (0, pPastLastZero); } } } inline char* mkFmtWithPrecisionArg_ (char* formatBufferStart, [[maybe_unused]] char* formatBufferEnd, char _Spec) { char* fmtPtr = formatBufferStart; *fmtPtr++ = '%'; // include precision arg *fmtPtr++ = '.'; *fmtPtr++ = '*'; if (_Spec != '\0') { *fmtPtr++ = _Spec; // e.g. 'L' qualifier } *fmtPtr++ = 'g'; // format specifier *fmtPtr = '\0'; Require (fmtPtr < formatBufferEnd); return formatBufferStart; } template <typename FLOAT_TYPE> inline String Float2String_OptimizedForCLocaleAndNoStreamFlags_ (FLOAT_TYPE f, int precision, bool trimTrailingZeros) { Require (not isnan (f)); Require (not isinf (f)); size_t sz = precision + 100; // I think precision is enough SmallStackBuffer<char> buf (SmallStackBuffer<char>::eUninitialized, sz); char format[100]; int resultStrLen = ::snprintf (buf, buf.size (), mkFmtWithPrecisionArg_ (std::begin (format), std::end (format), is_same_v<FLOAT_TYPE, long double> ? 'L' : '\0'), (int)precision, f); Verify (resultStrLen > 0 and resultStrLen < static_cast<int> (sz)); String tmp = String::FromASCII (buf.begin (), buf.begin () + resultStrLen); if (trimTrailingZeros) { TrimTrailingZeros_ (&tmp); } return tmp; } template <typename FLOAT_TYPE> inline String Float2String_GenericCase_ (FLOAT_TYPE f, const Float2StringOptions& options) { Require (not isnan (f)); Require (not isinf (f)); // expensive to construct, and slightly cheaper to just use thread_local version of // the same stringstream each time (only one per thread can be in use) static thread_local stringstream s; static const ios_base::fmtflags kDefaultIOSFmtFlags_ = s.flags (); // Just copy out of the first constructed stringstream s.str (string ()); s.clear (); static const locale kCLocale_ = locale::classic (); s.imbue (options.GetUseLocale ().value_or (kCLocale_)); // must set explictly (even if defaulted) because of the thread_local thing s.flags (options.GetIOSFmtFlags ().value_or (kDefaultIOSFmtFlags_)); // todo must set default precision because of the thread_local thing unsigned int usePrecision = options.GetPrecision ().value_or (kDefaultPrecision.fPrecision); s.precision (usePrecision); { optional<ios_base::fmtflags> useFloatField; switch (options.GetFloatFormat ().value_or (Float2StringOptions::FloatFormatType::eDEFAULT)) { case Float2StringOptions::FloatFormatType::eScientific: useFloatField = ios_base::scientific; break; case Float2StringOptions::FloatFormatType::eDefaultFloat: break; case Float2StringOptions::FloatFormatType::eFixedPoint: useFloatField = ios_base::fixed; break; case Float2StringOptions::FloatFormatType::eAutomatic: { bool useScientificNotation = abs (f) >= pow (10, usePrecision / 2) or (f != 0 and abs (f) < pow (10, -static_cast<int> (usePrecision) / 2)); // scientific preserves more precision - but non-scientific looks better if (useScientificNotation) { useFloatField = ios_base::scientific; } } break; default: RequireNotReached (); break; } if (useFloatField) { s.setf (*useFloatField, ios_base::floatfield); } else { s.unsetf (ios_base::floatfield); // see std::defaultfloat - not same as ios_base::fixed } } s << f; String tmp = options.GetUseLocale () ? String::FromNarrowString (s.str (), *options.GetUseLocale ()) : String::FromASCII (s.str ()); if (options.GetTrimTrailingZeros ().value_or (Float2StringOptions::kDefaultTrimTrailingZeros)) { TrimTrailingZeros_ (&tmp); } return tmp; } template <typename FLOAT_TYPE> inline String Float2String_ (FLOAT_TYPE f, const Float2StringOptions& options) { switch (fpclassify (f)) { case FP_INFINITE: { Assert (isinf (f)); Assert (!isnan (f)); static const String_Constant kNEG_INF_STR_{L"-INF"}; static const String_Constant kINF_STR_{L"INF"}; return f > 0 ? kINF_STR_ : kNEG_INF_STR_; } case FP_NAN: { Assert (isnan (f)); Assert (!isinf (f)); static const String_Constant kNAN_STR_{L"NAN"}; return kNAN_STR_; } } Assert (!isnan (f)); Assert (!isinf (f)); if (not options.GetUseLocale ().has_value () and not options.GetIOSFmtFlags ().has_value () and not options.GetFloatFormat ().has_value ()) { auto result = Float2String_OptimizedForCLocaleAndNoStreamFlags_ (f, options.GetPrecision ().value_or (kDefaultPrecision.fPrecision), options.GetTrimTrailingZeros ().value_or (Float2StringOptions::kDefaultTrimTrailingZeros)); Ensure (result == Float2String_GenericCase_<FLOAT_TYPE> (f, options)); return result; } return Float2String_GenericCase_<FLOAT_TYPE> (f, options); } } String Characters::Float2String (float f, const Float2StringOptions& options) { return Float2String_<long double> (f, options); } String Characters::Float2String (double f, const Float2StringOptions& options) { return Float2String_<long double> (f, options); } String Characters::Float2String (long double f, const Float2StringOptions& options) { return Float2String_<long double> (f, options); } /* ******************************************************************************** ********************************* String2Float ********************************* ******************************************************************************** */ namespace { template <typename RETURN_TYPE, typename FUNCTION> inline RETURN_TYPE String2Float_ (const String& s, FUNCTION F) { wchar_t* e = nullptr; const wchar_t* cst = s.c_str (); RETURN_TYPE d = F (cst, &e); // if trailing crap - return nan if (*e != '\0') { return Math::nan<RETURN_TYPE> (); } if (d == 0) { if (cst == e) { return Math::nan<RETURN_TYPE> (); } } return d; } } namespace Stroika::Foundation::Characters { template <> float String2Float (const String& s) { return String2Float_<float> (s, wcstof); } template <> double String2Float (const String& s) { return String2Float_<double> (s, wcstod); } template <> long double String2Float (const String& s) { return String2Float_<long double> (s, wcstold); } } <commit_msg>cosmetic<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved */ #include "../StroikaPreComp.h" #include <cstdarg> #include <cstdlib> #include <iomanip> #include <limits> #include <sstream> #include "../Characters/StringBuilder.h" #include "../Characters/String_Constant.h" #include "../Containers/Common.h" #include "../Debug/Assertions.h" #include "../Debug/Trace.h" #include "../Math/Common.h" #include "../Memory/SmallStackBuffer.h" #include "CodePage.h" #include "FloatConversion.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Characters; using namespace Stroika::Foundation::Memory; /* ******************************************************************************** ************************** Float2StringOptions ********************************* ******************************************************************************** */ Float2StringOptions::Float2StringOptions (UseCurrentLocale) : fUseLocale_ (locale{}) { } String Float2StringOptions::ToString () const { StringBuilder sb; sb += L"{"; if (fPrecision_) { sb += L"Precision:" + Characters::ToString ((int)*fPrecision_) + L","; } if (fFmtFlags_) { sb += L"Fmt-Flags:" + Characters::ToString ((int)*fFmtFlags_) + L","; } if (fUseLocale_) { sb += L"Use-Locale" + String::FromNarrowSDKString (fUseLocale_->name ()) + L","; } if (fTrimTrailingZeros_) { sb += L"Trim-Trailing-Zeros: " + Characters::ToString (*fTrimTrailingZeros_) + L","; } if (fFloatFormat_) { sb += L"Scientific-Notation: " + Characters::ToString ((int)*fFloatFormat_) + L","; } sb += L"}"; return sb.str (); } /* ******************************************************************************** ********************************* Float2String ********************************* ******************************************************************************** */ namespace { inline void TrimTrailingZeros_ (String* strResult) { RequireNotNull (strResult); // strip trailing zeros - except for the last first one after the decimal point. // And don't do if ends with exponential notation e+40 shouldnt get shortned to e+4! bool hasE = strResult->Find ('e', CompareOptions::eCaseInsensitive).has_value (); //Assert (hasE == (strResult->find ('e') != String::npos or strResult->find ('E') != String::npos)); if (not hasE) { size_t pastDot = strResult->find ('.'); if (pastDot != String::npos) { pastDot++; size_t pPastLastZero = strResult->length (); for (; (pPastLastZero - 1) > pastDot; --pPastLastZero) { if ((*strResult)[pPastLastZero - 1] != '0') { break; } } *strResult = strResult->SubString (0, pPastLastZero); } } } inline char* mkFmtWithPrecisionArg_ (char* formatBufferStart, [[maybe_unused]] char* formatBufferEnd, char _Spec) { char* fmtPtr = formatBufferStart; *fmtPtr++ = '%'; // include precision arg *fmtPtr++ = '.'; *fmtPtr++ = '*'; if (_Spec != '\0') { *fmtPtr++ = _Spec; // e.g. 'L' qualifier } *fmtPtr++ = 'g'; // format specifier *fmtPtr = '\0'; Require (fmtPtr < formatBufferEnd); return formatBufferStart; } template <typename FLOAT_TYPE> inline String Float2String_OptimizedForCLocaleAndNoStreamFlags_ (FLOAT_TYPE f, int precision, bool trimTrailingZeros) { Require (not isnan (f)); Require (not isinf (f)); size_t sz = precision + 100; // I think precision is enough SmallStackBuffer<char> buf (SmallStackBuffer<char>::eUninitialized, sz); char format[100]; int resultStrLen = ::snprintf (buf, buf.size (), mkFmtWithPrecisionArg_ (std::begin (format), std::end (format), is_same_v<FLOAT_TYPE, long double> ? 'L' : '\0'), (int)precision, f); Verify (resultStrLen > 0 and resultStrLen < static_cast<int> (sz)); String tmp = String::FromASCII (buf.begin (), buf.begin () + resultStrLen); if (trimTrailingZeros) { TrimTrailingZeros_ (&tmp); } return tmp; } template <typename FLOAT_TYPE> inline String Float2String_GenericCase_ (FLOAT_TYPE f, const Float2StringOptions& options) { Require (not isnan (f)); Require (not isinf (f)); // expensive to construct, and slightly cheaper to just use thread_local version of // the same stringstream each time (only one per thread can be in use) static thread_local stringstream s; static const ios_base::fmtflags kDefaultIOSFmtFlags_ = s.flags (); // Just copy out of the first constructed stringstream s.str (string ()); s.clear (); static const locale kCLocale_ = locale::classic (); s.imbue (options.GetUseLocale ().value_or (kCLocale_)); // must set explictly (even if defaulted) because of the thread_local thing s.flags (options.GetIOSFmtFlags ().value_or (kDefaultIOSFmtFlags_)); // todo must set default precision because of the thread_local thing unsigned int usePrecision = options.GetPrecision ().value_or (kDefaultPrecision.fPrecision); s.precision (usePrecision); { optional<ios_base::fmtflags> useFloatField; switch (options.GetFloatFormat ().value_or (Float2StringOptions::FloatFormatType::eDEFAULT)) { case Float2StringOptions::FloatFormatType::eScientific: useFloatField = ios_base::scientific; break; case Float2StringOptions::FloatFormatType::eDefaultFloat: break; case Float2StringOptions::FloatFormatType::eFixedPoint: useFloatField = ios_base::fixed; break; case Float2StringOptions::FloatFormatType::eAutomatic: { bool useScientificNotation = abs (f) >= pow (10, usePrecision / 2) or (f != 0 and abs (f) < pow (10, -static_cast<int> (usePrecision) / 2)); // scientific preserves more precision - but non-scientific looks better if (useScientificNotation) { useFloatField = ios_base::scientific; } } break; default: RequireNotReached (); break; } if (useFloatField) { s.setf (*useFloatField, ios_base::floatfield); } else { s.unsetf (ios_base::floatfield); // see std::defaultfloat - not same as ios_base::fixed } } s << f; String tmp = options.GetUseLocale () ? String::FromNarrowString (s.str (), *options.GetUseLocale ()) : String::FromASCII (s.str ()); if (options.GetTrimTrailingZeros ().value_or (Float2StringOptions::kDefaultTrimTrailingZeros)) { TrimTrailingZeros_ (&tmp); } return tmp; } template <typename FLOAT_TYPE> inline String Float2String_ (FLOAT_TYPE f, const Float2StringOptions& options) { switch (fpclassify (f)) { case FP_INFINITE: { Assert (isinf (f)); Assert (!isnan (f)); static const String_Constant kNEG_INF_STR_{L"-INF"}; static const String_Constant kINF_STR_{L"INF"}; return f > 0 ? kINF_STR_ : kNEG_INF_STR_; } case FP_NAN: { Assert (isnan (f)); Assert (!isinf (f)); static const String_Constant kNAN_STR_{L"NAN"}; return kNAN_STR_; } } Assert (!isnan (f)); Assert (!isinf (f)); if (not options.GetUseLocale ().has_value () and not options.GetIOSFmtFlags ().has_value () and not options.GetFloatFormat ().has_value ()) { auto result = Float2String_OptimizedForCLocaleAndNoStreamFlags_ (f, options.GetPrecision ().value_or (kDefaultPrecision.fPrecision), options.GetTrimTrailingZeros ().value_or (Float2StringOptions::kDefaultTrimTrailingZeros)); Ensure (result == Float2String_GenericCase_<FLOAT_TYPE> (f, options)); return result; } return Float2String_GenericCase_<FLOAT_TYPE> (f, options); } } String Characters::Float2String (float f, const Float2StringOptions& options) { return Float2String_<long double> (f, options); } String Characters::Float2String (double f, const Float2StringOptions& options) { return Float2String_<long double> (f, options); } String Characters::Float2String (long double f, const Float2StringOptions& options) { return Float2String_<long double> (f, options); } /* ******************************************************************************** ********************************* String2Float ********************************* ******************************************************************************** */ namespace { template <typename RETURN_TYPE, typename FUNCTION> inline RETURN_TYPE String2Float_ (const String& s, FUNCTION F) { wchar_t* e = nullptr; const wchar_t* cst = s.c_str (); RETURN_TYPE d = F (cst, &e); // if trailing crap - return nan if (*e != '\0') { return Math::nan<RETURN_TYPE> (); } if (d == 0) { if (cst == e) { return Math::nan<RETURN_TYPE> (); } } return d; } } namespace Stroika::Foundation::Characters { template <> float String2Float (const String& s) { return String2Float_<float> (s, wcstof); } template <> double String2Float (const String& s) { return String2Float_<double> (s, wcstod); } template <> long double String2Float (const String& s) { return String2Float_<long double> (s, wcstold); } } <|endoftext|>
<commit_before>#include <omni/take2/context.hpp> #include <omni/take2/block.hpp> #include <omni/take2/type.hpp> #include <omni/take2/function.hpp> #include <omni/take2/context_part.hpp> #include <omni/take2/return_statement.hpp> #include <omni/take2/literal_expression.hpp> #include <omni/take2/builtin_literal.hpp> #include <omni/take2/function_call_expression.hpp> #include <omni/take2/expression_statement.hpp> #include <omni/tests/test_file_manager.hpp> #include <lld/Driver/Driver.h> #include <lld/Driver/WinLinkInputGraph.h> #include <lld/ReaderWriter/PECOFFLinkingContext.h> #include <boost/filesystem.hpp> #include <omni/tests/test_utils.hpp> #include <set> #include <memory> #include <iostream> #define BOOST_TEST_MODULE OmniTake2 #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(contextTests) BOOST_AUTO_TEST_CASE(ctor) { using namespace omni::take2; context c; } /** Creates 20 ids for each domain and checks whether they are unique. **/ BOOST_AUTO_TEST_CASE(createId) { using namespace omni::take2; context c; std::set <id> ids; for (domain d = domain::first; d < domain::last; d = static_cast <domain> (static_cast <int> (d) + 1)) { for (int i = 0; i < 20; ++ i) { id id = c.createId (d); BOOST_CHECK (ids.find (id) == ids.end ()); ids.insert (id); BOOST_CHECK (ids.find (id) != ids.end ()); } } } /** Tests that a function can be created using createFunction and later be found via findFunctionByName and findPartById. **/ BOOST_AUTO_TEST_CASE (createAndFindFunction) { using namespace omni::take2; context c; std::shared_ptr <block> emptyBody (new block ()); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), emptyBody); BOOST_CHECK (func->getName () == functionName); BOOST_CHECK (c.findFunctionByName (func->getName ()) != nullptr); BOOST_CHECK (c.findFunctionByName (func->getName ())->getName () == functionName); BOOST_CHECK (c.findFunctionByName (functionName) != nullptr); BOOST_CHECK (c.findFunctionByName (functionName)->getName () == functionName); BOOST_CHECK (c.findPartById (func->getId ()) != std::shared_ptr <context_part> ()); BOOST_CHECK (std::dynamic_pointer_cast <function> (c.findPartById (func->getId ()))->getName () == functionName); } /** Tests that a manually created function can be added using addFunction and later be found via findFunctionByName and findPartById. **/ BOOST_AUTO_TEST_CASE (addAndFindFunction) { using namespace omni::take2; context c; std::shared_ptr <block> emptyBody (new block ()); const std::string functionName = "test"; std::shared_ptr <function> func (new function (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), emptyBody)); BOOST_CHECK (func->getContext () == nullptr); c.addFunction (func); BOOST_CHECK (func->getName () == functionName); BOOST_CHECK (func->getContext () == & c); BOOST_CHECK (c.findFunctionByName (func->getName ()) != nullptr); BOOST_CHECK (c.findFunctionByName (func->getName ())->getName () == functionName); BOOST_CHECK (c.findFunctionByName (functionName) != nullptr); BOOST_CHECK (c.findFunctionByName (functionName)->getName () == functionName); BOOST_CHECK (c.findPartById (func->getId ()) != std::shared_ptr <context_part> ()); BOOST_CHECK (std::dynamic_pointer_cast <function> (c.findPartById (func->getId ()))->getName () == functionName); } /** Tests that a previously added function that is verified to exist in a context can be removed using removeFunction. **/ BOOST_AUTO_TEST_CASE (removeFunction) { using namespace omni::take2; context c; std::shared_ptr <block> emptyBody (new block ()); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), emptyBody); BOOST_CHECK (c.findFunctionByName (func->getName ()) != nullptr); BOOST_CHECK (c.findFunctionByName (func->getName ())->getName () == functionName); BOOST_CHECK (c.removeFunction (func)); BOOST_CHECK (func->getContext () == nullptr); BOOST_CHECK (c.findFunctionByName (func->getName ()) == nullptr); BOOST_CHECK (c.findFunctionByName (functionName) == nullptr); } /** Writes an assembly (.ll) file and checks, whether it exists. TODO: Check, whether llvm can interpret the resulting ll file. **/ BOOST_AUTO_TEST_CASE (emitAssemblyFile) { using namespace omni::take2; context c; std::shared_ptr <block> body (new block ()); std::shared_ptr <literal> literal42 (new builtin_literal <signed int> (c, 42)); std::shared_ptr <expression> literal42exp (new literal_expression (literal42)); std::shared_ptr <statement> return42 (new return_statement (literal42exp)); body->appendStatement (return42); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), body); omni::tests::test_file_manager testFileManager; std::string assemblyFileName = testFileManager.getTestFileName ("emitAssemblyFile.ll").string (); c.emitAssemblyFile (assemblyFileName); BOOST_CHECK (boost::filesystem::exists(assemblyFileName)); } /** Writes an object file (.o on Linux/Unix, .obj on Windows) and checks, whether it exists. **/ BOOST_AUTO_TEST_CASE (emitObjectFile) { using namespace omni::take2; context c; std::shared_ptr <block> body (new block ()); std::shared_ptr <literal> literal42 (new builtin_literal <signed int> (c, 42)); std::shared_ptr <expression> literal42exp (new literal_expression (literal42)); std::shared_ptr <statement> return42 (new return_statement (literal42exp)); body->appendStatement (return42); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), body); omni::tests::test_file_manager testFileManager; boost::filesystem::path objectFilePath = testFileManager.getTestFileName ("emitObjectFile.obj"); std::string objectFileName = objectFilePath.string (); c.emitObjectFile (objectFileName); BOOST_CHECK (boost::filesystem::exists (objectFileName)); } /** Writes an shared object file (.so on Linux/Unix, .dll on Windows) and checks, whether it exists, tries to load it and then tries to call the function exported from it. **/ BOOST_AUTO_TEST_CASE (emitSharedLibraryFile) { using namespace omni::take2; context c; std::shared_ptr <block> body (new block ()); std::shared_ptr <literal> literal42 (new builtin_literal <signed int> (c, 42)); std::shared_ptr <expression> literal42exp (new literal_expression (literal42)); std::shared_ptr <statement> return42 (new return_statement (literal42exp)); body->appendStatement (return42); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), body); omni::tests::test_file_manager testFileManager; int functionCallResult = omni::tests::runFunction <int> (func, testFileManager, "emitSharedLibraryFile"); BOOST_CHECK_EQUAL (functionCallResult, 42); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Removed includes from lld headers from the tests - the tests should only use omni, standard and boost includes<commit_after>#include <omni/take2/context.hpp> #include <omni/take2/block.hpp> #include <omni/take2/type.hpp> #include <omni/take2/function.hpp> #include <omni/take2/context_part.hpp> #include <omni/take2/return_statement.hpp> #include <omni/take2/literal_expression.hpp> #include <omni/take2/builtin_literal.hpp> #include <omni/take2/function_call_expression.hpp> #include <omni/take2/expression_statement.hpp> #include <omni/tests/test_file_manager.hpp> #include <omni/tests/test_utils.hpp> #include <set> #include <memory> #include <iostream> #define BOOST_TEST_MODULE OmniTake2 #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(contextTests) BOOST_AUTO_TEST_CASE(ctor) { using namespace omni::take2; context c; } /** Creates 20 ids for each domain and checks whether they are unique. **/ BOOST_AUTO_TEST_CASE(createId) { using namespace omni::take2; context c; std::set <id> ids; for (domain d = domain::first; d < domain::last; d = static_cast <domain> (static_cast <int> (d) + 1)) { for (int i = 0; i < 20; ++ i) { id id = c.createId (d); BOOST_CHECK (ids.find (id) == ids.end ()); ids.insert (id); BOOST_CHECK (ids.find (id) != ids.end ()); } } } /** Tests that a function can be created using createFunction and later be found via findFunctionByName and findPartById. **/ BOOST_AUTO_TEST_CASE (createAndFindFunction) { using namespace omni::take2; context c; std::shared_ptr <block> emptyBody (new block ()); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), emptyBody); BOOST_CHECK (func->getName () == functionName); BOOST_CHECK (c.findFunctionByName (func->getName ()) != nullptr); BOOST_CHECK (c.findFunctionByName (func->getName ())->getName () == functionName); BOOST_CHECK (c.findFunctionByName (functionName) != nullptr); BOOST_CHECK (c.findFunctionByName (functionName)->getName () == functionName); BOOST_CHECK (c.findPartById (func->getId ()) != std::shared_ptr <context_part> ()); BOOST_CHECK (std::dynamic_pointer_cast <function> (c.findPartById (func->getId ()))->getName () == functionName); } /** Tests that a manually created function can be added using addFunction and later be found via findFunctionByName and findPartById. **/ BOOST_AUTO_TEST_CASE (addAndFindFunction) { using namespace omni::take2; context c; std::shared_ptr <block> emptyBody (new block ()); const std::string functionName = "test"; std::shared_ptr <function> func (new function (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), emptyBody)); BOOST_CHECK (func->getContext () == nullptr); c.addFunction (func); BOOST_CHECK (func->getName () == functionName); BOOST_CHECK (func->getContext () == & c); BOOST_CHECK (c.findFunctionByName (func->getName ()) != nullptr); BOOST_CHECK (c.findFunctionByName (func->getName ())->getName () == functionName); BOOST_CHECK (c.findFunctionByName (functionName) != nullptr); BOOST_CHECK (c.findFunctionByName (functionName)->getName () == functionName); BOOST_CHECK (c.findPartById (func->getId ()) != std::shared_ptr <context_part> ()); BOOST_CHECK (std::dynamic_pointer_cast <function> (c.findPartById (func->getId ()))->getName () == functionName); } /** Tests that a previously added function that is verified to exist in a context can be removed using removeFunction. **/ BOOST_AUTO_TEST_CASE (removeFunction) { using namespace omni::take2; context c; std::shared_ptr <block> emptyBody (new block ()); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), emptyBody); BOOST_CHECK (c.findFunctionByName (func->getName ()) != nullptr); BOOST_CHECK (c.findFunctionByName (func->getName ())->getName () == functionName); BOOST_CHECK (c.removeFunction (func)); BOOST_CHECK (func->getContext () == nullptr); BOOST_CHECK (c.findFunctionByName (func->getName ()) == nullptr); BOOST_CHECK (c.findFunctionByName (functionName) == nullptr); } /** Writes an assembly (.ll) file and checks, whether it exists. TODO: Check, whether llvm can interpret the resulting ll file. **/ BOOST_AUTO_TEST_CASE (emitAssemblyFile) { using namespace omni::take2; context c; std::shared_ptr <block> body (new block ()); std::shared_ptr <literal> literal42 (new builtin_literal <signed int> (c, 42)); std::shared_ptr <expression> literal42exp (new literal_expression (literal42)); std::shared_ptr <statement> return42 (new return_statement (literal42exp)); body->appendStatement (return42); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), body); omni::tests::test_file_manager testFileManager; std::string assemblyFileName = testFileManager.getTestFileName ("emitAssemblyFile.ll").string (); c.emitAssemblyFile (assemblyFileName); BOOST_CHECK (boost::filesystem::exists(assemblyFileName)); } /** Writes an object file (.o on Linux/Unix, .obj on Windows) and checks, whether it exists. **/ BOOST_AUTO_TEST_CASE (emitObjectFile) { using namespace omni::take2; context c; std::shared_ptr <block> body (new block ()); std::shared_ptr <literal> literal42 (new builtin_literal <signed int> (c, 42)); std::shared_ptr <expression> literal42exp (new literal_expression (literal42)); std::shared_ptr <statement> return42 (new return_statement (literal42exp)); body->appendStatement (return42); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), body); omni::tests::test_file_manager testFileManager; boost::filesystem::path objectFilePath = testFileManager.getTestFileName ("emitObjectFile.obj"); std::string objectFileName = objectFilePath.string (); c.emitObjectFile (objectFileName); BOOST_CHECK (boost::filesystem::exists (objectFileName)); } /** Writes an shared object file (.so on Linux/Unix, .dll on Windows) and checks, whether it exists, tries to load it and then tries to call the function exported from it. **/ BOOST_AUTO_TEST_CASE (emitSharedLibraryFile) { using namespace omni::take2; context c; std::shared_ptr <block> body (new block ()); std::shared_ptr <literal> literal42 (new builtin_literal <signed int> (c, 42)); std::shared_ptr <expression> literal42exp (new literal_expression (literal42)); std::shared_ptr <statement> return42 (new return_statement (literal42exp)); body->appendStatement (return42); const std::string functionName = "test"; std::shared_ptr <function> func = c.createFunction (functionName, static_cast <std::shared_ptr <type>> (new type (c, type_class::t_signedInt)), body); omni::tests::test_file_manager testFileManager; int functionCallResult = omni::tests::runFunction <int> (func, testFileManager, "emitSharedLibraryFile"); BOOST_CHECK_EQUAL (functionCallResult, 42); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkImage.h" #include "itkCastImageFilter.h" #include "itkRandomImageSource.h" template < class T > std::string GetTypeName() { return "unknown type"; } template < > std::string GetTypeName< char >() { return "char"; } template < > std::string GetTypeName< unsigned char >() { return "unsigned char"; } template < > std::string GetTypeName< short >() { return "short"; } template < > std::string GetTypeName< unsigned short >() { return "unsigned short"; } template < > std::string GetTypeName< int >() { return "int"; } template < > std::string GetTypeName< unsigned int >() { return "unsigned int"; } template < > std::string GetTypeName< long >() { return "long"; } template < > std::string GetTypeName< unsigned long >() { return "unsigned long"; } template < > std::string GetTypeName< long long >() { return "long long"; } template < > std::string GetTypeName< unsigned long long >() { return "unsigned long long"; } template < > std::string GetTypeName< float >() { return "float"; } template < > std::string GetTypeName< double >() { return "double"; } template < class TInputPixelType, class TOutputPixelType > bool TestCastFromTo() { typedef itk::Image< TInputPixelType, 3 > InputImageType; typedef itk::Image< TOutputPixelType, 3 > OutputImageType; typedef itk::CastImageFilter< InputImageType, OutputImageType > FilterType; typedef itk::RandomImageSource< InputImageType > SourceType; typename SourceType::Pointer source = SourceType::New(); typename InputImageType::SizeValueType randomSize[3] = {18, 17, 23}; source->SetSize( randomSize ); typename FilterType::Pointer filter = FilterType::New(); filter->SetInput( source->GetOutput() ); filter->UpdateLargestPossibleRegion(); typedef itk::ImageRegionConstIterator< InputImageType > InputIteratorType; typedef itk::ImageRegionConstIterator< OutputImageType > OutputIteratorType; InputIteratorType it( source->GetOutput(), source->GetOutput()->GetLargestPossibleRegion() ); OutputIteratorType ot( filter->GetOutput(), filter->GetOutput()->GetLargestPossibleRegion() ); bool success = true; std::cout << "Casting from " << GetTypeName< TInputPixelType >() << " to " << GetTypeName< TOutputPixelType >() << " ... "; it.GoToBegin(); ot.GoToBegin(); while ( !it.IsAtEnd() ) { TInputPixelType inValue = it.Value(); TOutputPixelType outValue = ot.Value(); if ( outValue != static_cast< TOutputPixelType >( inValue ) ) { success = false; break; } ++it; ++ot; } if ( success ) { std::cout << "[PASSED]" << std::endl; } else { std::cout << "[FAILED]" << std::endl; } return true; } template < class TInputPixelType > bool TestCastTo() { bool success = TestCastFromTo< TInputPixelType, char >() && TestCastFromTo< TInputPixelType, unsigned char >() && TestCastFromTo< TInputPixelType, short >() && TestCastFromTo< TInputPixelType, unsigned short >() && TestCastFromTo< TInputPixelType, int >() && TestCastFromTo< TInputPixelType, unsigned int >() && TestCastFromTo< TInputPixelType, long >() && TestCastFromTo< TInputPixelType, unsigned long >() && TestCastFromTo< TInputPixelType, long long >() && TestCastFromTo< TInputPixelType, unsigned long long >() && TestCastFromTo< TInputPixelType, float >() && TestCastFromTo< TInputPixelType, double >(); return success; } int itkCastImageFilterTest( int, char* [] ) { std::cout << "itkCastImageFilterTest Start" << std::endl; bool success = TestCastTo< char >() && TestCastTo< unsigned char >() && TestCastTo< short >() && TestCastTo< unsigned short >() && TestCastTo< int >() && TestCastTo< unsigned int >() && TestCastTo< long >() && TestCastTo< unsigned long >() && TestCastTo< long long >() && TestCastTo< unsigned long long >() && TestCastTo< float >() && TestCastTo< double >(); std::cout << std::endl; if ( !success ) { std::cout << "An itkCastImageFilter test FAILED." << std::endl; return EXIT_FAILURE; } std::cout << "All itkCastImageFilter tests PASSED." << std::endl; return EXIT_SUCCESS; } <commit_msg>BUG: Fixed error in test.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> #include "itkImage.h" #include "itkCastImageFilter.h" #include "itkRandomImageSource.h" template < class T > std::string GetTypeName() { return "unknown type"; } template < > std::string GetTypeName< char >() { return "char"; } template < > std::string GetTypeName< unsigned char >() { return "unsigned char"; } template < > std::string GetTypeName< short >() { return "short"; } template < > std::string GetTypeName< unsigned short >() { return "unsigned short"; } template < > std::string GetTypeName< int >() { return "int"; } template < > std::string GetTypeName< unsigned int >() { return "unsigned int"; } template < > std::string GetTypeName< long >() { return "long"; } template < > std::string GetTypeName< unsigned long >() { return "unsigned long"; } template < > std::string GetTypeName< long long >() { return "long long"; } template < > std::string GetTypeName< unsigned long long >() { return "unsigned long long"; } template < > std::string GetTypeName< float >() { return "float"; } template < > std::string GetTypeName< double >() { return "double"; } template < class TInputPixelType, class TOutputPixelType > bool TestCastFromTo() { typedef itk::Image< TInputPixelType, 3 > InputImageType; typedef itk::Image< TOutputPixelType, 3 > OutputImageType; typedef itk::CastImageFilter< InputImageType, OutputImageType > FilterType; typedef itk::RandomImageSource< InputImageType > SourceType; typename SourceType::Pointer source = SourceType::New(); typename InputImageType::SizeValueType randomSize[3] = {18, 17, 23}; source->SetSize( randomSize ); typename FilterType::Pointer filter = FilterType::New(); filter->SetInput( source->GetOutput() ); filter->UpdateLargestPossibleRegion(); typedef itk::ImageRegionConstIterator< InputImageType > InputIteratorType; typedef itk::ImageRegionConstIterator< OutputImageType > OutputIteratorType; InputIteratorType it( source->GetOutput(), source->GetOutput()->GetLargestPossibleRegion() ); OutputIteratorType ot( filter->GetOutput(), filter->GetOutput()->GetLargestPossibleRegion() ); bool success = true; std::cout << "Casting from " << GetTypeName< TInputPixelType >() << " to " << GetTypeName< TOutputPixelType >() << " ... "; it.GoToBegin(); ot.GoToBegin(); while ( !it.IsAtEnd() ) { TInputPixelType inValue = it.Value(); TOutputPixelType outValue = ot.Value(); if ( outValue != static_cast< TOutputPixelType >( inValue ) ) { success = false; break; } ++it; ++ot; } if ( success ) { std::cout << "[PASSED]" << std::endl; } else { std::cout << "[FAILED]" << std::endl; } return success; } template < class TInputPixelType > bool TestCastTo() { bool success = TestCastFromTo< TInputPixelType, char >() && TestCastFromTo< TInputPixelType, unsigned char >() && TestCastFromTo< TInputPixelType, short >() && TestCastFromTo< TInputPixelType, unsigned short >() && TestCastFromTo< TInputPixelType, int >() && TestCastFromTo< TInputPixelType, unsigned int >() && TestCastFromTo< TInputPixelType, long >() && TestCastFromTo< TInputPixelType, unsigned long >() && TestCastFromTo< TInputPixelType, long long >() && TestCastFromTo< TInputPixelType, unsigned long long >() && TestCastFromTo< TInputPixelType, float >() && TestCastFromTo< TInputPixelType, double >(); return success; } int itkCastImageFilterTest( int, char* [] ) { std::cout << "itkCastImageFilterTest Start" << std::endl; bool success = TestCastTo< char >() && TestCastTo< unsigned char >() && TestCastTo< short >() && TestCastTo< unsigned short >() && TestCastTo< int >() && TestCastTo< unsigned int >() && TestCastTo< long >() && TestCastTo< unsigned long >() && TestCastTo< long long >() && TestCastTo< unsigned long long >() && TestCastTo< float >() && TestCastTo< double >(); std::cout << std::endl; if ( !success ) { std::cout << "An itkCastImageFilter test FAILED." << std::endl; return EXIT_FAILURE; } std::cout << "All itkCastImageFilter tests PASSED." << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <chrono> #include <exception> #include <stdexcept> // __gnu_cxx::__verbose_terminate_handler #include <fstream> #include <iostream> #include <thread> #include <libtorrent/add_torrent_params.hpp> #include <libtorrent/alert_types.hpp> #include <libtorrent/bencode.hpp> #include <libtorrent/create_torrent.hpp> #include <libtorrent/session.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/storage_defs.hpp> // lt::disabled_storage_constructor #include <libtorrent/torrent_handle.hpp> #include <libtorrent/torrent_info.hpp> int usage(const char *argv0) { std::cerr << "usage: " << argv0 << " <magnet-url>" << std::endl; return 1; } namespace lt = libtorrent; int main(int argc, char *argv[]) { std::set_terminate(__gnu_cxx::__verbose_terminate_handler); lt::session_settings sset; sset.prefer_udp_trackers = false; if (argc != 2) return usage(argv[0]); lt::session sess; sess.set_settings(sset); lt::add_torrent_params atp; atp.url = argv[1]; atp.upload_mode = true; atp.auto_managed = false; atp.paused = false; // Start with "storage == disabled" to avoid pre-allocating any files // mentioned in the torrent file on disk: atp.storage = lt::disabled_storage_constructor; atp.save_path = "."; // save in current dir /* // .flags duplicate .upload_mode/auto_managed/paused // functionality: atp.flags = lt::add_torrent_params::flag_update_subscribe | lt::add_torrent_params::flag_upload_mode | lt::add_torrent_params::flag_apply_ip_filter; */ lt::torrent_handle torh = sess.add_torrent(atp); std::cout << atp.url << ":"; for (;;) { std::deque<lt::alert*> alerts; sess.pop_alerts(&alerts); for (lt::alert const* a : alerts) { std::cout << std::endl << a->message() << std::endl; // quit on error/finish: if (lt::alert_cast<lt::torrent_finished_alert>(a) || lt::alert_cast<lt::torrent_error_alert>(a)) { goto done1; }; } if (torh.status().has_metadata) { sess.pause(); lt::torrent_info tinf = torh.get_torrent_info(); std::cout << tinf.name() << std::endl; std::cout.flush(); std::ofstream ofs; ofs.exceptions(std::ofstream::failbit | std::ofstream::badbit); ofs.open(tinf.name() + ".torrent", std::ofstream::binary); std::ostream_iterator<char> ofsi(ofs); lt::bencode(ofsi, lt::create_torrent(tinf) .generate()); ofs.close(); sess.remove_torrent(torh); goto done0; }; std::cout << "."; std::cout.flush(); std::this_thread::sleep_for( std::chrono::milliseconds(1000)); } done0: return 0; done1: return 1; } // vi: set sw=8 ts=8 noet tw=77: <commit_msg>Use "static" linkage for usage().<commit_after>#include <chrono> #include <exception> #include <stdexcept> // __gnu_cxx::__verbose_terminate_handler #include <fstream> #include <iostream> #include <thread> #include <libtorrent/add_torrent_params.hpp> #include <libtorrent/alert_types.hpp> #include <libtorrent/bencode.hpp> #include <libtorrent/create_torrent.hpp> #include <libtorrent/session.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/storage_defs.hpp> // lt::disabled_storage_constructor #include <libtorrent/torrent_handle.hpp> #include <libtorrent/torrent_info.hpp> static int usage(const char *argv0) { std::cerr << "usage: " << argv0 << " <magnet-url>" << std::endl; return 1; } namespace lt = libtorrent; int main(int argc, char *argv[]) { std::set_terminate(__gnu_cxx::__verbose_terminate_handler); lt::session_settings sset; sset.prefer_udp_trackers = false; if (argc != 2) return usage(argv[0]); lt::session sess; sess.set_settings(sset); lt::add_torrent_params atp; atp.url = argv[1]; atp.upload_mode = true; atp.auto_managed = false; atp.paused = false; // Start with "storage == disabled" to avoid pre-allocating any files // mentioned in the torrent file on disk: atp.storage = lt::disabled_storage_constructor; atp.save_path = "."; // save in current dir /* // .flags duplicate .upload_mode/auto_managed/paused // functionality: atp.flags = lt::add_torrent_params::flag_update_subscribe | lt::add_torrent_params::flag_upload_mode | lt::add_torrent_params::flag_apply_ip_filter; */ lt::torrent_handle torh = sess.add_torrent(atp); std::cout << atp.url << ":"; for (;;) { std::deque<lt::alert*> alerts; sess.pop_alerts(&alerts); for (lt::alert const* a : alerts) { std::cout << std::endl << a->message() << std::endl; // quit on error/finish: if (lt::alert_cast<lt::torrent_finished_alert>(a) || lt::alert_cast<lt::torrent_error_alert>(a)) { goto done1; }; } if (torh.status().has_metadata) { sess.pause(); lt::torrent_info tinf = torh.get_torrent_info(); std::cout << tinf.name() << std::endl; std::cout.flush(); std::ofstream ofs; ofs.exceptions(std::ofstream::failbit | std::ofstream::badbit); ofs.open(tinf.name() + ".torrent", std::ofstream::binary); std::ostream_iterator<char> ofsi(ofs); lt::bencode(ofsi, lt::create_torrent(tinf) .generate()); ofs.close(); sess.remove_torrent(torh); goto done0; }; std::cout << "."; std::cout.flush(); std::this_thread::sleep_for( std::chrono::milliseconds(1000)); } done0: return 0; done1: return 1; } // vi: set sw=8 ts=8 noet tw=77: <|endoftext|>
<commit_before>/** * @file FunctionApproximatorGMR.hpp * @brief FunctionApproximatorGMR class header file. * @author Thibaut Munzer, Freek Stulp * * This file is part of DmpBbo, a set of libraries and programs for the * black-box optimization of dynamical movement primitives. * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech * * DmpBbo is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * DmpBbo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with DmpBbo. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _FUNCTION_APPROXIMATOR_GMR_H_ #define _FUNCTION_APPROXIMATOR_GMR_H_ #include "functionapproximators/FunctionApproximator.hpp" /** @defgroup GMR Gaussian Mixture Regression (GMR) * @ingroup FunctionApproximators */ namespace DmpBbo { // Forward declarations class MetaParametersGMR; class ModelParametersGMR; /** \brief GMR (Gaussian Mixture Regression) function approximator * \ingroup FunctionApproximators * \ingroup GMR */ class FunctionApproximatorGMR : public FunctionApproximator { public: /** Initialize a function approximator with meta- and model-parameters * \param[in] meta_parameters The training algorithm meta-parameters * \param[in] model_parameters The parameters of the trained model. If this parameter is not * passed, the function approximator is initialized as untrained. * In this case, you must call FunctionApproximator::train() before * being able to call FunctionApproximator::predict(). * Either meta_parameters XOR model-parameters can passed as NULL, but not both. */ FunctionApproximatorGMR(const MetaParametersGMR *const meta_parameters, const ModelParametersGMR *const model_parameters=NULL); /** Initialize a function approximator with model parameters * \param[in] model_parameters The parameters of the (previously) trained model. */ FunctionApproximatorGMR(const ModelParametersGMR *const model_parameters); virtual FunctionApproximator* clone(void) const; void train(const Eigen::MatrixXd& input, const Eigen::MatrixXd& target); void predict(const Eigen::MatrixXd& input, Eigen::MatrixXd& output); void predictDot(const Eigen::MatrixXd& inputs, Eigen::MatrixXd& outputs, Eigen::MatrixXd& outputs_dot); void predictVariance(const Eigen::MatrixXd& inputs, Eigen::MatrixXd& variances); std::string getName(void) const { return std::string("GMR"); }; protected: /** Initialize Gaussian for EM algorithm using k-means. * \param[in] data A data matrix (n_exemples x (n_in_dim + n_out_dim)) * \param[out] means A list (std::vector) of n_gaussian non initiallized means (n_in_dim + n_out_dim) * \param[out] priors A list (std::vector) of n_gaussian non initiallized priors * \param[out] covars A list (std::vector) of n_gaussian non initiallized covariance matrices ((n_in_dim + n_out_dim) x (n_in_dim + n_out_dim)) * \param[in] n_max_iter The maximum number of iterations * \author Thibaut Munzer */ void kMeansInit(const Eigen::MatrixXd& data, std::vector<Eigen::VectorXd>& means, std::vector<double>& priors, std::vector<Eigen::MatrixXd>& covars, int n_max_iter=1000); /** Initialize Gaussian for EM algorithm using a same-size slicing on the first dimension (method used in Calinon GMR implementation). * Particulary suited when input is 1-D and data distribution is uniform over input dimension * \param[in] data A data matrix (n_exemples x (n_in_dim + n_out_dim)) * \param[out] means A list (std::vector) of n_gaussian non initiallized means (n_in_dim + n_out_dim) * \param[out] priors A list (std::vector) of n_gaussian non initiallized priors * \param[out] covars A list (std::vector) of n_gaussian non initiallized covariance matrices ((n_in_dim + n_out_dim) x (n_in_dim + n_out_dim)) * \author Thibaut Munzer */ void firstDimSlicingInit(const Eigen::MatrixXd& data, std::vector<Eigen::VectorXd>& means, std::vector<double>& priors, std::vector<Eigen::MatrixXd>& covars); /** EM algorithm. * \param[in] data A (n_exemples x (n_in_dim + n_out_dim)) data matrix * \param[in,out] means A list (std::vector) of n_gaussian means (vector of size (n_in_dim + n_out_dim)) * \param[in,out] priors A list (std::vector) of n_gaussian priors * \param[in,out] covars A list (std::vector) of n_gaussian covariance matrices ((n_in_dim + n_out_dim) x (n_in_dim + n_out_dim)) * \param[in] n_max_iter The maximum number of iterations * \author Thibaut Munzer */ void expectationMaximization(const Eigen::MatrixXd& data, std::vector<Eigen::VectorXd>& means, std::vector<double>& priors, std::vector<Eigen::MatrixXd>& covars, int n_max_iter=50); /** The probability density function (PDF) of the multi-variate normal distribution * \param[in] mu The mean of the normal distribution * \param[in] covar The covariance matrix of the normal distribution * \param[in] input The input data vector for which the PDF will be computed. * \return The PDF value for the input */ static double normalPDF(const Eigen::VectorXd& mu, const Eigen::MatrixXd& covar, const Eigen::VectorXd& input); static void normalPDFDot(const Eigen::VectorXd& mu, const Eigen::MatrixXd& covar, const Eigen::VectorXd& input, double& output, double& output_dot); /** The probability density function (PDF) of the multi-variate normal distribution * \param[in] mu The mean of the normal distribution * \param[in] covar_inverse Inverse of the covariance matrix of the normal distribution * \param[in] input The input data vector for which the PDF will be computed. * \return The PDF value for the input */ static double normalPDFWithInverseCovar(const Eigen::VectorXd& mu, const Eigen::MatrixXd& covar_inverse, const Eigen::VectorXd& input); static void normalPDFWithInverseCovarDot(const Eigen::VectorXd& mu, const Eigen::MatrixXd& covar_inverse, const Eigen::VectorXd& input, double& output, double& output_dot); /** Compute the probabilities that a certain input belongs to each Gaussian in the Gaussian mixture model. * \param[in] gmm The Gaussian mixture model * \param[in] input The input data vector for which the probabilities will be computed. * \param[out] h The probabilities */ static void computeProbabilitiesDot(const ModelParametersGMR* gmm, const Eigen::VectorXd& input, Eigen::VectorXd& h, Eigen::VectorXd& h_dot); static void computeProbabilities(const ModelParametersGMR* gmm, const Eigen::VectorXd& input, Eigen::VectorXd& h); private: /** * Default constructor. * \remarks This default constuctor is required for boost::serialization to work. Since this * constructor should not be called by other classes, it is private (boost::serialization is a * friend) */ FunctionApproximatorGMR(void) {}; /** Give boost serialization access to private members. */ friend class boost::serialization::access; /** Serialize class data members to boost archive. * \param[in] ar Boost archive * \param[in] version Version of the class * See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#simplecase */ template<class Archive> void serialize(Archive & ar, const unsigned int version); /** This is a cached variable whose memory is allocated once during construction. */ Eigen::VectorXd probabilities_cached_; Eigen::VectorXd probabilities_dot_cached_; //double gauss_, gauss_dot_; }; } #include <boost/serialization/export.hpp> /** Register this derived class. */ BOOST_CLASS_EXPORT_KEY2(DmpBbo::FunctionApproximatorGMR, "FunctionApproximatorGMR") /** Don't add version information to archives. */ BOOST_CLASS_IMPLEMENTATION(DmpBbo::FunctionApproximatorGMR,boost::serialization::object_serializable); #endif // !_FUNCTION_APPROXIMATOR_GMR_H_ <commit_msg>Added doxygen group for the derivative functions<commit_after>/** * @file FunctionApproximatorGMR.hpp * @brief FunctionApproximatorGMR class header file. * @author Thibaut Munzer, Freek Stulp * * This file is part of DmpBbo, a set of libraries and programs for the * black-box optimization of dynamical movement primitives. * Copyright (C) 2014 Freek Stulp, ENSTA-ParisTech * * DmpBbo is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * DmpBbo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with DmpBbo. If not, see <http://www.gnu.org/licenses/>. */ #ifndef _FUNCTION_APPROXIMATOR_GMR_H_ #define _FUNCTION_APPROXIMATOR_GMR_H_ #include "functionapproximators/FunctionApproximator.hpp" /** @defgroup GMR Gaussian Mixture Regression (GMR) * @ingroup FunctionApproximators */ namespace DmpBbo { // Forward declarations class MetaParametersGMR; class ModelParametersGMR; /** \brief GMR (Gaussian Mixture Regression) function approximator * \ingroup FunctionApproximators * \ingroup GMR */ class FunctionApproximatorGMR : public FunctionApproximator { public: /** Initialize a function approximator with meta- and model-parameters * \param[in] meta_parameters The training algorithm meta-parameters * \param[in] model_parameters The parameters of the trained model. If this parameter is not * passed, the function approximator is initialized as untrained. * In this case, you must call FunctionApproximator::train() before * being able to call FunctionApproximator::predict(). * Either meta_parameters XOR model-parameters can passed as NULL, but not both. */ FunctionApproximatorGMR(const MetaParametersGMR *const meta_parameters, const ModelParametersGMR *const model_parameters=NULL); /** Initialize a function approximator with model parameters * \param[in] model_parameters The parameters of the (previously) trained model. */ FunctionApproximatorGMR(const ModelParametersGMR *const model_parameters); virtual FunctionApproximator* clone(void) const; void train(const Eigen::MatrixXd& input, const Eigen::MatrixXd& target); void predict(const Eigen::MatrixXd& input, Eigen::MatrixXd& output); void predictVariance(const Eigen::MatrixXd& inputs, Eigen::MatrixXd& variances); std::string getName(void) const { return std::string("GMR"); }; protected: /** Initialize Gaussian for EM algorithm using k-means. * \param[in] data A data matrix (n_exemples x (n_in_dim + n_out_dim)) * \param[out] means A list (std::vector) of n_gaussian non initiallized means (n_in_dim + n_out_dim) * \param[out] priors A list (std::vector) of n_gaussian non initiallized priors * \param[out] covars A list (std::vector) of n_gaussian non initiallized covariance matrices ((n_in_dim + n_out_dim) x (n_in_dim + n_out_dim)) * \param[in] n_max_iter The maximum number of iterations * \author Thibaut Munzer */ void kMeansInit(const Eigen::MatrixXd& data, std::vector<Eigen::VectorXd>& means, std::vector<double>& priors, std::vector<Eigen::MatrixXd>& covars, int n_max_iter=1000); /** Initialize Gaussian for EM algorithm using a same-size slicing on the first dimension (method used in Calinon GMR implementation). * Particulary suited when input is 1-D and data distribution is uniform over input dimension * \param[in] data A data matrix (n_exemples x (n_in_dim + n_out_dim)) * \param[out] means A list (std::vector) of n_gaussian non initiallized means (n_in_dim + n_out_dim) * \param[out] priors A list (std::vector) of n_gaussian non initiallized priors * \param[out] covars A list (std::vector) of n_gaussian non initiallized covariance matrices ((n_in_dim + n_out_dim) x (n_in_dim + n_out_dim)) * \author Thibaut Munzer */ void firstDimSlicingInit(const Eigen::MatrixXd& data, std::vector<Eigen::VectorXd>& means, std::vector<double>& priors, std::vector<Eigen::MatrixXd>& covars); /** EM algorithm. * \param[in] data A (n_exemples x (n_in_dim + n_out_dim)) data matrix * \param[in,out] means A list (std::vector) of n_gaussian means (vector of size (n_in_dim + n_out_dim)) * \param[in,out] priors A list (std::vector) of n_gaussian priors * \param[in,out] covars A list (std::vector) of n_gaussian covariance matrices ((n_in_dim + n_out_dim) x (n_in_dim + n_out_dim)) * \param[in] n_max_iter The maximum number of iterations * \author Thibaut Munzer */ void expectationMaximization(const Eigen::MatrixXd& data, std::vector<Eigen::VectorXd>& means, std::vector<double>& priors, std::vector<Eigen::MatrixXd>& covars, int n_max_iter=50); /** The probability density function (PDF) of the multi-variate normal distribution * \param[in] mu The mean of the normal distribution * \param[in] covar The covariance matrix of the normal distribution * \param[in] input The input data vector for which the PDF will be computed. * \return The PDF value for the input */ static double normalPDF(const Eigen::VectorXd& mu, const Eigen::MatrixXd& covar, const Eigen::VectorXd& input); /** The probability density function (PDF) of the multi-variate normal distribution * \param[in] mu The mean of the normal distribution * \param[in] covar_inverse Inverse of the covariance matrix of the normal distribution * \param[in] input The input data vector for which the PDF will be computed. * \return The PDF value for the input */ static double normalPDFWithInverseCovar(const Eigen::VectorXd& mu, const Eigen::MatrixXd& covar_inverse, const Eigen::VectorXd& input); /** Compute the probabilities that a certain input belongs to each Gaussian in the Gaussian mixture model. * \param[in] gmm The Gaussian mixture model * \param[in] input The input data vector for which the probabilities will be computed. * \param[out] h The probabilities */ static void computeProbabilities(const ModelParametersGMR* gmm, const Eigen::VectorXd& input, Eigen::VectorXd& h); /** @name Derivate of the probability density function * These methods are used to compute the derivate of the probability density function. They have been tested only when the input dimension is one. */ /**@{*/ public: /** Query the function approximator to make a prediction and to compute the derivate of that prediction * \param[in] inputs Input values of the query * \param[out] outputs Predicted output values * \param[out] outputs_dot Predicted derivate values * * \remark This method should be const. But third party functions which is called in this function * have not always been implemented as const (Examples: LWPRObject::predict or IRFRLS::predict ). * Therefore, this function cannot be const. */ void predictDot(const Eigen::MatrixXd& inputs, Eigen::MatrixXd& outputs, Eigen::MatrixXd& outputs_dot); protected: /** Derivate of the probability density function (PDF) of the multi-variate normal distribution * \param[in] mu The mean of the normal distribution * \param[in] covar The covariance matrix of the normal distribution * \param[in] input The input data vector for which the PDF will be computed. * \param[out] output The PDF value for the input * \param[out] output_dot The derivate PDF value for the input */ static void normalPDFDot(const Eigen::VectorXd& mu, const Eigen::MatrixXd& covar, const Eigen::VectorXd& input, double& output, double& output_dot); /** The probability density function (PDF) of the multi-variate normal distribution * \param[in] mu The mean of the normal distribution * \param[in] covar_inverse Inverse of the covariance matrix of the normal distribution * \param[in] input The input data vector for which the PDF will be computed. * \param[out] output The PDF value for the input * \param[out] output_dot The derivate of the PDF for the input */ static void normalPDFWithInverseCovarDot(const Eigen::VectorXd& mu, const Eigen::MatrixXd& covar_inverse, const Eigen::VectorXd& input, double& output, double& output_dot); /** Compute the probabilities that a certain input belongs to each Gaussian in the Gaussian mixture model and its derivative in respect of the input. * \param[in] gmm The Gaussian mixture model * \param[in] input The input data vector for which the probabilities will be computed. * \param[out] h The probabilities * \param[out] h_dot The derivative of h */ static void computeProbabilitiesDot(const ModelParametersGMR* gmm, const Eigen::VectorXd& input, Eigen::VectorXd& h, Eigen::VectorXd& h_dot); ///@} private: /** * Default constructor. * \remarks This default constuctor is required for boost::serialization to work. Since this * constructor should not be called by other classes, it is private (boost::serialization is a * friend) */ FunctionApproximatorGMR(void) {}; /** Give boost serialization access to private members. */ friend class boost::serialization::access; /** Serialize class data members to boost archive. * \param[in] ar Boost archive * \param[in] version Version of the class * See http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/tutorial.html#simplecase */ template<class Archive> void serialize(Archive & ar, const unsigned int version); /** This is a cached variable whose memory is allocated once during construction. */ Eigen::VectorXd probabilities_cached_; Eigen::VectorXd probabilities_dot_cached_; }; } #include <boost/serialization/export.hpp> /** Register this derived class. */ BOOST_CLASS_EXPORT_KEY2(DmpBbo::FunctionApproximatorGMR, "FunctionApproximatorGMR") /** Don't add version information to archives. */ BOOST_CLASS_IMPLEMENTATION(DmpBbo::FunctionApproximatorGMR,boost::serialization::object_serializable); #endif // !_FUNCTION_APPROXIMATOR_GMR_H_ <|endoftext|>
<commit_before><commit_msg>ignore the (unsupported ) group customshape when exporting xlsx<commit_after><|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_setup_evid.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_setup_evid.H /// @brief Setup External Voltage IDs /// // *HWP HW Owner : Greg Still <[email protected]> // *HWP FW Owner : Prasad Bg Ranganath <[email protected]> // *Team : PM // *Consumed by : HB // *Level : 3 /// #ifndef __P9_SETUP_EVID_H__ #define __P9_SETUP_EVID_H__ #include <fapi2.H> #include <p9_pstate_parameter_block.H> extern "C" { /// @typedef VoltageConfigActions_t /// enum of the two actions this hwp can perform /// it can either compute default voltage settings /// otherwise it can apply voltage setting to the system typedef enum { COMPUTE_VOLTAGE_SETTINGS, APPLY_VOLTAGE_SETTINGS } VoltageConfigActions_t; /// @typedef p9_setup_evid_FP_t /// function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_setup_evid_FP_t) ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&, const VoltageConfigActions_t); /// @brief Set safe mode values to DPLL fmult,fmin and fmax /// @param [in] i_target TARGET_TYPE_PROC_CHIP /// @param [in] i_safe_mode_values Safe mode values /// @param [out] o_vddm_mv external vdd voltaget value /// @param [in] i_freq_proc_refclock_khz proc clock frequency /// @param [in] i_proc_dpll_divider proc dpll divider value //@return fapi::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. fapi2::ReturnCode p9_setup_dpll_values (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const Safe_mode_parameters i_safe_mode_values, uint32_t& o_vddm_mv, const uint32_t i_freq_proc_refclock_khz, const uint32_t i_proc_dpll_divider); /// @brief Read attributes containing part's boot voltages(VDD,VCS and VDN) /// and set these voltage using the AVSBUS interface (VDD, VDN and VCS). /// /// @param [in] i_target TARGET_TYPE_PROC_CHIP /// @param [in] i_action Describes whether you wish to COMPUTE voltage settings /// during the step or if you would like to APPLY them. /// @attr /// @attritem ATTR_VCS_BOOT_VOLTAGE - 1mV grandularity setting for VCS rail /// @attritem ATTR_VDD_BOOT_VOLTAGE - 1mV grandularity setting for VDD rail /// @attritem ATTR_VDN_BOOT_VOLTAGE - 1mV grandularity setting for VDN rail /// @attritem ATTR_VDD_AVSBUS_BUSNUM - AVSBus Number having the VDD VRM /// @attritem ATTR_VDD_AVSBUS_RAIL - AVSBus Rail number for VDD VRM /// @attritem ATTR_VDN_AVSBUS_BUSNUM - AVSBus Number having the VDN VRM /// @attritem ATTR_VDN_AVSBUS_RAIL - AVSBus Rail number for VDN VRM /// @attritem ATTR_VCS_AVSBUS_BUSNUM - AVSBus Number having the VCS VRM /// @attritem ATTR_VCS_AVSBUS_RAIL - AVSBus Rail number for VCS VRM /// ///@return fapi::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. fapi2::ReturnCode p9_setup_evid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const VoltageConfigActions_t i_action); } // extern C #endif // __P9_SETUP_EVID_H__ <commit_msg>SAFE mode:moved writing safe mode value from istep 6 to istep 10<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_setup_evid.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_setup_evid.H /// @brief Setup External Voltage IDs /// // *HWP HW Owner : Greg Still <[email protected]> // *HWP FW Owner : Prasad Bg Ranganath <[email protected]> // *Team : PM // *Consumed by : HB // *Level : 3 /// #ifndef __P9_SETUP_EVID_H__ #define __P9_SETUP_EVID_H__ #include <fapi2.H> #include <p9_pstate_parameter_block.H> extern "C" { /// @typedef VoltageConfigActions_t /// enum of the two actions this hwp can perform /// it can either compute default voltage settings /// otherwise it can apply voltage setting to the system typedef enum { COMPUTE_VOLTAGE_SETTINGS, APPLY_VOLTAGE_SETTINGS } VoltageConfigActions_t; /// @typedef p9_setup_evid_FP_t /// function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_setup_evid_FP_t) ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&, const VoltageConfigActions_t); /// @brief Set safe mode values to DPLL fmult,fmin and fmax /// @param [in] i_target TARGET_TYPE_PROC_CHIP /// @param [in] i_freq_proc_refclock_khz proc clock frequency /// @param [in] i_proc_dpll_divider proc dpll divider value //@return fapi::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. fapi2::ReturnCode p9_setup_dpll_values (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint32_t i_freq_proc_refclock_khz, const uint32_t i_proc_dpll_divider); /// @brief Read attributes containing part's boot voltages(VDD,VCS and VDN) /// and set these voltage using the AVSBUS interface (VDD, VDN and VCS). /// /// @param [in] i_target TARGET_TYPE_PROC_CHIP /// @param [in] i_action Describes whether you wish to COMPUTE voltage settings /// during the step or if you would like to APPLY them. /// @attr /// @attritem ATTR_VCS_BOOT_VOLTAGE - 1mV grandularity setting for VCS rail /// @attritem ATTR_VDD_BOOT_VOLTAGE - 1mV grandularity setting for VDD rail /// @attritem ATTR_VDN_BOOT_VOLTAGE - 1mV grandularity setting for VDN rail /// @attritem ATTR_VDD_AVSBUS_BUSNUM - AVSBus Number having the VDD VRM /// @attritem ATTR_VDD_AVSBUS_RAIL - AVSBus Rail number for VDD VRM /// @attritem ATTR_VDN_AVSBUS_BUSNUM - AVSBus Number having the VDN VRM /// @attritem ATTR_VDN_AVSBUS_RAIL - AVSBus Rail number for VDN VRM /// @attritem ATTR_VCS_AVSBUS_BUSNUM - AVSBus Number having the VCS VRM /// @attritem ATTR_VCS_AVSBUS_RAIL - AVSBus Rail number for VCS VRM /// ///@return fapi::ReturnCode. FAPI2_RC_SUCCESS if success, else error code. fapi2::ReturnCode p9_setup_evid(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const VoltageConfigActions_t i_action); } // extern C #endif // __P9_SETUP_EVID_H__ <|endoftext|>
<commit_before>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, [email protected] // // This file is part of Virvo. // // Virvo is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "vvdebugmsg.h" #include "vvrequestmanagement.h" #include "vvrendercontext.h" #include "vvtoolshed.h" #include <algorithm> #include <GL/glew.h> #include <sstream> #include <istream> #include <fstream> #include <string> #define GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048 #define GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049 class vvGpu::GpuData { public: GpuData() { glName = ""; Xdsp = ""; cuda = false; openGL = false; cudaDevice = -1; wSystem = vvRenderContext::VV_NONE; } std::string glName; std::string Xdsp; bool cuda; bool openGL; int cudaDevice; vvRenderContext::WindowingSystem wSystem; bool operator == (const GpuData& other) const { return this->glName == other.glName && this->Xdsp == other.Xdsp && this->cuda == other.cuda && this->openGL == other.openGL && this->cudaDevice == other.cudaDevice && this->wSystem == other.wSystem; } }; std::vector<vvGpu*> gpus; std::vector<vvGpu*> vvGpu::list() { vvDebugMsg::msg(3, "vvGpu::list() Enter"); const char* serverEnv = "VV_SERVER_PATH"; if (getenv(serverEnv)) { std::string filepath = std::string(getenv(serverEnv)) + std::string("/vserver.config"); std::ifstream fin(filepath.c_str()); if(!fin.is_open()) { std::string errmsg = std::string("vvGpu::list() could not open config file ")+filepath; vvDebugMsg::msg(0, errmsg.c_str()); } uint lineNum = 0; std::string line; while(fin.good()) { lineNum++; std::getline(fin, line); std::vector<std::string> subStrs = vvToolshed::split(line, "="); if(subStrs.size() < 2) { vvDebugMsg::msg(2, "vvGpu::list() nothing to parse in config file line ", (int)lineNum); } else { if(vvToolshed::strCompare("gpu", subStrs[0].c_str()) == 0) { line.erase(0,line.find_first_of("=",0)+1); vvGpu::createGpu(line); } else if(vvToolshed::strCompare("node", subStrs[0].c_str()) == 0) { // NODE bla bla } } } } else { std::string errmsg = std::string("vvGpu::list() Environment variable ")+std::string(serverEnv)+std::string(" not set."); vvDebugMsg::msg(1, errmsg.c_str()); } return gpus; } vvGpu::vvGpuInfo vvGpu::getInfo(vvGpu *gpu) { vvDebugMsg::msg(3, "vvGpu::getInfo() Enter"); vvGpuInfo inf = { -1, -1 }; if(gpu->_data->openGL) { vvContextOptions co; co.displayName = gpu->_data->Xdsp; co.doubleBuffering = false; co.height = 1; co.width = 1; co.type = vvContextOptions::VV_WINDOW; vvRenderContext context = vvRenderContext(co); context.makeCurrent(); glGetIntegerv(GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &(inf.totalMem)); glGetIntegerv(GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &(inf.freeMem)); } else if(gpu->_data->cuda) { // TODO: Implement cuda-case here! } return inf; } vvGpu* vvGpu::createGpu(std::string& data) { vvDebugMsg::msg(3, "vvGpu::createGpu() Enter"); std::vector<std::string> attributes = vvToolshed::split(data, ","); if(attributes.size() > 0) { vvGpu* gpu = new vvGpu(); for(std::vector<std::string>::iterator attrib = attributes.begin(); attrib != attributes.end(); attrib++) { std::vector<std::string> nameValue = vvToolshed::split(*attrib, "="); if(nameValue.size() < 2) { vvDebugMsg::msg(0, "vvGpu::parseGpuData() parse error: attribute value missing"); continue; } const char* attribNames[] = { "name", // 1 "xdsp", // 2 "cuda", // 3 "opengl", // 4 "windowingsystem" // 5 }; uint attrName = std::find(attribNames, attribNames+5, (nameValue[0])) - attribNames; attrName = (attrName < 12) ? (attrName + 1) : 0; switch(attrName) { case 1: gpu->_data->glName = nameValue[1]; break; case 2: gpu->_data->Xdsp = nameValue[1]; break; case 3: gpu->_data->cuda = vvToolshed::strCompare(nameValue[1].c_str(), "true") == 0 ? true : false; break; case 4: gpu->_data->openGL = vvToolshed::strCompare(nameValue[1].c_str(), "true") == 0 ? true : false; break; case 5: if(vvToolshed::strCompare(nameValue[1].c_str(), "X11")) { gpu->_data->wSystem = vvRenderContext::VV_X11; } else if(vvToolshed::strCompare(nameValue[1].c_str(), "WGL")) { gpu->_data->wSystem = vvRenderContext::VV_WGL; } else if(vvToolshed::strCompare(nameValue[1].c_str(), "COCOA")) { gpu->_data->wSystem = vvRenderContext::VV_COCOA; } else { vvDebugMsg::msg(2, "vvGpu::parseGpuData() parse error: unknown windowingsystem type"); gpu->_data->wSystem = vvRenderContext::VV_NONE; } break; default: vvDebugMsg::msg(2, "vvGpu::createGpu() parse error: unknown attribute"); delete gpu; return NULL; } } // check if gpu already known vvGpu *found = NULL; for(std::vector<vvGpu*>::iterator g = gpus.begin(); g != gpus.end(); g++) { if(**g == *gpu) found = *g; } if(found) { delete gpu; return found; } else { gpus.push_back(gpu); return gpu; } } else { return NULL; } } void vvGpu::clearGpus() { for(std::vector<vvGpu*>::iterator g = gpus.begin(); g!=gpus.end(); g++) { delete *g; } gpus.clear(); } vvGpu::vvGpu() { _data = new GpuData; } vvGpu::~vvGpu() { delete _data; } vvGpu& vvGpu::operator = (const vvGpu& src) { (void)src; return *this; } bool vvGpu::operator == (const vvGpu& other) const { return *this->_data == *other._data; } // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <commit_msg>shout more helpful errors for vvGpu<commit_after>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, [email protected] // // This file is part of Virvo. // // Virvo is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #include "vvdebugmsg.h" #include "vvrequestmanagement.h" #include "vvrendercontext.h" #include "vvtoolshed.h" #include <algorithm> #include <GL/glew.h> #include <sstream> #include <istream> #include <fstream> #include <string> #define GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX 0x9048 #define GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX 0x9049 class vvGpu::GpuData { public: GpuData() { glName = ""; Xdsp = ""; cuda = false; openGL = false; cudaDevice = -1; wSystem = vvRenderContext::VV_NONE; } std::string glName; std::string Xdsp; bool cuda; bool openGL; int cudaDevice; vvRenderContext::WindowingSystem wSystem; bool operator == (const GpuData& other) const { return this->glName == other.glName && this->Xdsp == other.Xdsp && this->cuda == other.cuda && this->openGL == other.openGL && this->cudaDevice == other.cudaDevice && this->wSystem == other.wSystem; } }; std::vector<vvGpu*> gpus; std::vector<vvGpu*> vvGpu::list() { vvDebugMsg::msg(3, "vvGpu::list() Enter"); const char* serverEnv = "VV_SERVER_PATH"; if (getenv(serverEnv)) { std::string filepath = std::string(getenv(serverEnv)) + std::string("/vserver.config"); std::ifstream fin(filepath.c_str()); if(!fin.is_open()) { std::string errmsg = std::string("vvGpu::list() could not open config file ")+filepath; vvDebugMsg::msg(0, errmsg.c_str()); } uint lineNum = 0; std::string line; while(fin.good()) { lineNum++; std::getline(fin, line); std::vector<std::string> subStrs = vvToolshed::split(line, "="); if(subStrs.size() < 2) { vvDebugMsg::msg(2, "vvGpu::list() nothing to parse in config file line ", (int)lineNum); } else { if(vvToolshed::strCompare("gpu", subStrs[0].c_str()) == 0) { line.erase(0,line.find_first_of("=",0)+1); vvGpu::createGpu(line); } else if(vvToolshed::strCompare("node", subStrs[0].c_str()) == 0) { // NODE bla bla } } } } else { std::string errmsg = std::string("vvGpu::list() Environment variable ")+std::string(serverEnv)+std::string(" not set."); vvDebugMsg::msg(1, errmsg.c_str()); } return gpus; } vvGpu::vvGpuInfo vvGpu::getInfo(vvGpu *gpu) { vvDebugMsg::msg(3, "vvGpu::getInfo() Enter"); vvGpuInfo inf = { -1, -1 }; if(gpu->_data->openGL) { vvContextOptions co; co.displayName = gpu->_data->Xdsp; co.doubleBuffering = false; co.height = 1; co.width = 1; co.type = vvContextOptions::VV_WINDOW; vvRenderContext context = vvRenderContext(co); context.makeCurrent(); glGetIntegerv(GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &(inf.totalMem)); glGetIntegerv(GPU_MEMORY_INFO_CURRENT_AVAILABLE_VIDMEM_NVX, &(inf.freeMem)); } else if(gpu->_data->cuda) { // TODO: Implement cuda-case here! } return inf; } vvGpu* vvGpu::createGpu(std::string& data) { vvDebugMsg::msg(3, "vvGpu::createGpu() Enter"); std::vector<std::string> attributes = vvToolshed::split(data, ","); if(attributes.size() > 0) { vvGpu* gpu = new vvGpu(); for(std::vector<std::string>::iterator attrib = attributes.begin(); attrib != attributes.end(); attrib++) { std::vector<std::string> nameValue = vvToolshed::split(*attrib, "="); if(nameValue.size() < 2) { vvDebugMsg::msg(0, "vvGpu::parseGpuData() parse error: attribute value missing"); continue; } const char* attribNames[] = { "name", // 1 "xdsp", // 2 "cuda", // 3 "opengl", // 4 "windowingsystem" // 5 }; uint attrName = std::find(attribNames, attribNames+5, (nameValue[0])) - attribNames; attrName = (attrName < 12) ? (attrName + 1) : 0; switch(attrName) { case 1: gpu->_data->glName = nameValue[1]; break; case 2: gpu->_data->Xdsp = nameValue[1]; break; case 3: gpu->_data->cuda = vvToolshed::strCompare(nameValue[1].c_str(), "true") == 0 ? true : false; break; case 4: gpu->_data->openGL = vvToolshed::strCompare(nameValue[1].c_str(), "true") == 0 ? true : false; break; case 5: if(vvToolshed::strCompare(nameValue[1].c_str(), "X11")) { gpu->_data->wSystem = vvRenderContext::VV_X11; } else if(vvToolshed::strCompare(nameValue[1].c_str(), "WGL")) { gpu->_data->wSystem = vvRenderContext::VV_WGL; } else if(vvToolshed::strCompare(nameValue[1].c_str(), "COCOA")) { gpu->_data->wSystem = vvRenderContext::VV_COCOA; } else { vvDebugMsg::msg(0, "vvGpu::parseGpuData() parse error: unknown windowingsystem type"); gpu->_data->wSystem = vvRenderContext::VV_NONE; } break; default: std::string errmsg = std::string("vvGpu::createGpu() parse error: unknown attribute near: ")+std::string(nameValue[0]); vvDebugMsg::msg(0, errmsg.c_str()); delete gpu; return NULL; } } // check if gpu already known vvGpu *found = NULL; for(std::vector<vvGpu*>::iterator g = gpus.begin(); g != gpus.end(); g++) { if(**g == *gpu) found = *g; } if(found) { delete gpu; return found; } else { gpus.push_back(gpu); return gpu; } } else { return NULL; } } void vvGpu::clearGpus() { for(std::vector<vvGpu*>::iterator g = gpus.begin(); g!=gpus.end(); g++) { delete *g; } gpus.clear(); } vvGpu::vvGpu() { _data = new GpuData; } vvGpu::~vvGpu() { delete _data; } vvGpu& vvGpu::operator = (const vvGpu& src) { (void)src; return *this; } bool vvGpu::operator == (const vvGpu& other) const { return *this->_data == *other._data; } // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <|endoftext|>
<commit_before>#include "InterfaceInternal.h" extern void _dyld_register_func_for_add_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide)); typedef uint64_t addr_t; void *getSegmentContent(mach_header_t *header, char *segName) { struct load_command *load_cmd; segment_command_t *seg_cmd; section_t *sect; // initialize the segment info load_cmd = (struct load_command *)((addr_t)header + sizeof(mach_header_t)); for (int i = 0; i < header->ncmds; i++, load_cmd = (struct load_command *)((addr_t)load_cmd + load_cmd->cmdsize)) { if (load_cmd->cmd == LC_SEGMENT_ARCH_DEPENDENT) { seg_cmd = (segment_command_t *)load_cmd; if (!strcmp(seg_cmd->segname, segName)) { size_t fileoff = seg_cmd->fileoff; void *content = (void *)((addr_t)header + fileoff); return content; } } } return NULL; } void rebase_stub(const struct mach_header *mh, intptr_t vmaddr_slide) { void *zDATAContent = getSegmentContent((mach_header_t *)mh, "__zDATA"); if (zDATAContent) { InterceptorStatic *interceptor = (InterceptorStatic *)zDATAContent; if (interceptor->this_ && ((addr_t)interceptor->this_ != (addr_t)zDATAContent)) { // set interceptor initialized flag. interceptor->this_ == (uint64_t)zDATAContent; // iterate all entry for (int i = 0; i < interceptor->count; i++) { interceptor->entry[i] += vmaddr_slide; HookEntryStatic *entry = reinterpret_cast<HookEntryStatic *>(interceptor->entry[i]); entry->relocated_origin_function += vmaddr_slide; entry->trampoline_target_stub = (uint64_t *)((uint64_t)entry->trampoline_target_stub + vmaddr_slide); *entry->trampoline_target_stub = entry->relocated_origin_function; } } } } __attribute__((constructor)) void _rebase_process() { _dyld_register_func_for_add_image(rebase_stub); } <commit_msg>[plugin] update MachOManipulator plugin<commit_after>#include "InterfaceInternal.h" extern void _dyld_register_func_for_add_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide)); typedef uint64_t addr_t; void *getSegmentContent(mach_header_t *header, char *segName) { struct load_command *load_cmd; segment_command_t *seg_cmd; section_t *sect; // initialize the segment info load_cmd = (struct load_command *)((addr_t)header + sizeof(mach_header_t)); for (int i = 0; i < header->ncmds; i++, load_cmd = (struct load_command *)((addr_t)load_cmd + load_cmd->cmdsize)) { if (load_cmd->cmd == LC_SEGMENT_ARCH_DEPENDENT) { seg_cmd = (segment_command_t *)load_cmd; if (!strcmp(seg_cmd->segname, segName)) { size_t fileoff = seg_cmd->fileoff; void *content = (void *)((addr_t)header + fileoff); return content; } } } return NULL; } void rebase_stub(const struct mach_header *mh, intptr_t vmaddr_slide) { void *zDATAContent = getSegmentContent((mach_header_t *)mh, "__zDATA"); if (zDATAContent) { InterceptorStatic *interceptor = (InterceptorStatic *)zDATAContent; if (interceptor->this_ && ((addr_t)interceptor->this_ != (addr_t)zDATAContent)) { // set interceptor initialized flag. interceptor->this_ = (uint64_t)zDATAContent; // iterate all entry for (int i = 0; i < interceptor->count; i++) { interceptor->entry[i] += vmaddr_slide; HookEntryStatic *entry = reinterpret_cast<HookEntryStatic *>(interceptor->entry[i]); entry->relocated_origin_function += vmaddr_slide; entry->trampoline_target_stub = (uint64_t *)((uint64_t)entry->trampoline_target_stub + vmaddr_slide); *entry->trampoline_target_stub = entry->relocated_origin_function; } } } } __attribute__((constructor)) void _rebase_process() { _dyld_register_func_for_add_image(rebase_stub); } <|endoftext|>
<commit_before>//Mancala AI //Copyright Matthew Chandler 2012 #include <iostream> #include <iomanip> #include <vector> #include <limits> #include <cstdlib> //board: //2 rows of 6 bowls //2 larger bowls for scoring (stores) // //Rules //play is CCW //ending in player's own store yields extra turn //ending in empty bowl earns that piece and all those in the bowl across from it //game ends when a player has no legal moves left // //good heuristics: //score - opponent's score //possibly good: //number of availible moves //seeds in play //seed distribution (large piles waiting to be collected? seed ratio between sides) //possibilty of extra turns //if we wanted to, we could use a genetic algorithm for determining the importance of each of these // //representation //circular array? // 11 10 9 8 7 6 // 0 1 2 3 4 5 // p1 store, p2 store //From there, we would need logic to add to player's own store and skip the opponents. //if we abstract out the actual array indexes, we can use 2 starting pointers to easily flip the board //With that in mind, it might be better to use a Digraph, so we can have a truly circular setup //each node could have a next, prev, and across pointer, and one that points to the stores for the ends (NULL otherwise) // // // //If we wanted to get really fancy, we could do 3D graphics with particle physics for the seeds. struct Bowl { public: Bowl(const int Count = 0, const int Next = 0, const int Across = 0): count(Count), next(Next), across(Across) {} int count; int next, across; }; class Board { public: Board(const int Num_bowls = 6, const int Num_seeds = 4): num_bowls(Num_bowls), num_seeds(Num_seeds) { bowls.resize(2 * num_bowls + 2); p1_start = 0; p1_store = num_bowls; p2_start = num_bowls + 1; p2_store = 2 * num_bowls + 1; for(size_t i = 0; i < bowls.size(); ++i) { if(i < bowls.size() - 1) bowls[i].next = i + 1; else bowls[i].next = 0; if(i != (size_t)num_bowls && i != 2 * (size_t)num_bowls + 1) { bowls[i].across = 2 * num_bowls - i; bowls[i].count = num_seeds; } } } //perform a move //returns true if the move earns an extra turn bool move(int bowl) { if(bowl < 0 || bowl >= num_bowls) return false; bowl += p1_start; int seeds = bowls[bowl].count; if(seeds == 0) return false; bowls[bowl].count = 0; //make the move for(int i = 0; i < seeds; ++i) { bowl = bowls[bowl].next; if(bowl == p2_store) bowl = bowls[bowl].next; bowls[bowl].count += 1; } //extra turn if we land in our own store if(bowl == p1_store) return true; //if we land in an empty bowl, we get the last seed sown and all the seeds from the bowl across if(bowls[bowl].count == 1 && bowls[bowls[bowl].across].count > 0) { bowls[p1_store].count += 1 + bowls[bowls[bowl].across].count; bowls[bowls[bowl].across].count = 0; bowls[bowl].count = 0; } return false; } //swap sides of the board void swapsides() { std::swap(p1_start, p2_start); std::swap(p1_store, p2_store); } //is the game over bool finished() const { int p1_side = 0; for(int i = p1_start; i < p1_start + 6; ++i) p1_side |= bowls[i].count; if(p1_side == 0) return true; int p2_side = 0; for(int i = p2_start; i < p2_start + 6; ++i) p2_side |= bowls[i].count; return p2_side == 0; } //heuristics to evaluate the board status int evaluate() const { //simple return bowls[p1_store].count - bowls[p2_store].count; } void crapprint() const //delete me! { std::cout<<" "; for(int i = p1_start; i < p1_start + 6; ++i) std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[bowls[i].across].count<<" "; std::cout<<std::endl; std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[p2_store].count<<std::setw(3*7)<<" "<<std::setw(2)<<bowls[p1_store].count<<std::endl; std::cout<<" "; for(int i = p1_start; i < p1_start + 6; ++i) std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[i].count<<" "; std::cout<<std::endl; std::cout<<" "; for(int i = 0; i < 6 ; ++i) std::cout<<std::setw(2)<<std::setfill(' ')<<i<<" "; std::cout<<std::endl; } int num_bowls, num_seeds; std::vector<Bowl> bowls; int p1_start, p2_start; int p1_store, p2_store; }; enum PLAYER {PLAYER_MIN, PLAYER_MAX}; int choosemove_alphabeta(Board b, int depth, PLAYER player, int alpha, int beta) { if(player == PLAYER_MAX) { if(depth == 0) return b.evaluate(); //move toward closest win, avoid loss as long as possible if(b.finished()) { int diff = b.evaluate(); if(diff > 0) return 1000 + depth; else return -1000 - depth; } for(int i = 0; i < 6; ++i) { if(b.bowls[b.p1_start + i].count == 0) continue; Board sub_b = b; sub_b.move(i); // do we get another move? sub_b.swapsides(); int score = choosemove_alphabeta(sub_b, depth - 1, PLAYER_MIN, alpha, beta); if(score >= beta) return beta; if(score > alpha) alpha = score; } return alpha; } else { if(depth == 0) return -b.evaluate(); //move toward closest win, avoid loss as long as possible if(b.finished()) { int diff = b.evaluate(); if(diff > 0) return -1000 - depth; else return 1000 + depth; } for(int i = 0; i < 6; ++i) { if(b.bowls[b.p1_start + i].count == 0) continue; Board sub_b = b; sub_b.move(i); // do we get another move? sub_b.swapsides(); int score = choosemove_alphabeta(sub_b, depth - 1, PLAYER_MAX, alpha, beta); if(score <= alpha) return alpha; if(score < beta) beta = score; } return beta; } } int choosemove(Board b) //purposely doing pass by value here as to not corrupt passed board (we may want to use different method when we do actual move search) { int best = std::numeric_limits<int>::min(); std::vector<int> best_i; //loop over available moves for(int i =0; i < 6; ++i) { if(b.bowls[b.p1_start + i].count == 0) continue; Board sub_b = b; sub_b.move(i); sub_b.swapsides(); int score = choosemove_alphabeta(sub_b, 10, PLAYER_MIN, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); if(score > best) { best = score; best_i.clear(); best_i.push_back(i); } if(score == best); best_i.push_back(i); } return best_i[0];//rand() % best_i.size()]; } int main() { srand(time(0)); Board b; //b.bowls=std::vector<Bowl>({Bowl(3,1,12), Bowl(2,2,11), Bowl(1,3,10), Bowl(0,4,9), Bowl(10,5,8), Bowl(0,6,7), Bowl(0,7,0), Bowl(1,8,5), Bowl(0,9,4), Bowl(10,10,3), Bowl(1,11,2), Bowl(1,12,1), Bowl(1,13,0), Bowl(0,0,0)}); char nextmove = '\0'; int player = 1; while(!b.finished() && nextmove != 'q' && nextmove != 'Q') { std::cout<<"Player "<<player<<std::endl; b.crapprint(); std::cout<<"Best move: "<<choosemove(b)<<std::endl; std::cout<<"Next move: "; std::cin>>nextmove; std::cout<<std::endl; if(nextmove == 'S' || nextmove == 's') { b.swapsides(); player = (player == 1) ? 2 : 1; } if(nextmove >= '0' && nextmove <= '5') { if(!b.move(nextmove - '0')); { b.swapsides(); player = (player == 1) ? 2 : 1; } } } if(b.finished()) { std::cout<<"Player "<<player<<std::endl; b.crapprint(); if(b.bowls[b.p1_store].count == b.bowls[b.p2_store].count) std::cout<<"Tie"<<std::endl; else if(player == 1) if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count) std::cout<<"Player 1 wins"<<std::endl; else std::cout<<"Player 2 wins"<<std::endl; else if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count) std::cout<<"Player 2 wins"<<std::endl; else std::cout<<"Player 1 wins"<<std::endl; if(abs(b.bowls[b.p1_store].count - b.bowls[b.p2_store].count) >= 10) std::cout<<"FATALITY"<<std::endl; } return 0; } <commit_msg>added extra move code<commit_after>//Mancala AI //Copyright Matthew Chandler 2012 #include <iostream> #include <iomanip> #include <vector> #include <limits> #include <cstdlib> //board: //2 rows of 6 bowls //2 larger bowls for scoring (stores) // //Rules //play is CCW //ending in player's own store yields extra turn //ending in empty bowl earns that piece and all those in the bowl across from it //game ends when a player has no legal moves left // //good heuristics: //score - opponent's score //possibly good: //number of availible moves //seeds in play //seed distribution (large piles waiting to be collected? seed ratio between sides) //possibilty of extra turns //if we wanted to, we could use a genetic algorithm for determining the importance of each of these // //representation //circular array? // 11 10 9 8 7 6 // 0 1 2 3 4 5 // p1 store, p2 store //From there, we would need logic to add to player's own store and skip the opponents. //if we abstract out the actual array indexes, we can use 2 starting pointers to easily flip the board //With that in mind, it might be better to use a Digraph, so we can have a truly circular setup //each node could have a next, prev, and across pointer, and one that points to the stores for the ends (NULL otherwise) // // // //If we wanted to get really fancy, we could do 3D graphics with particle physics for the seeds. struct Bowl { public: Bowl(const int Count = 0, const int Next = 0, const int Across = 0): count(Count), next(Next), across(Across) {} int count; int next, across; }; class Board { public: Board(const int Num_bowls = 6, const int Num_seeds = 4): num_bowls(Num_bowls), num_seeds(Num_seeds) { bowls.resize(2 * num_bowls + 2); p1_start = 0; p1_store = num_bowls; p2_start = num_bowls + 1; p2_store = 2 * num_bowls + 1; for(size_t i = 0; i < bowls.size(); ++i) { if(i < bowls.size() - 1) bowls[i].next = i + 1; else bowls[i].next = 0; if(i != (size_t)num_bowls && i != 2 * (size_t)num_bowls + 1) { bowls[i].across = 2 * num_bowls - i; bowls[i].count = num_seeds; } } } //perform a move //returns true if the move earns an extra turn bool move(int bowl) { if(bowl < 0 || bowl >= num_bowls) return false; bowl += p1_start; int seeds = bowls[bowl].count; if(seeds == 0) return false; bowls[bowl].count = 0; //make the move for(int i = 0; i < seeds; ++i) { bowl = bowls[bowl].next; if(bowl == p2_store) bowl = bowls[bowl].next; bowls[bowl].count += 1; } //extra turn if we land in our own store if(bowl == p1_store) return true; //if we land in an empty bowl, we get the last seed sown and all the seeds from the bowl across if(bowls[bowl].count == 1 && bowls[bowls[bowl].across].count > 0) { bowls[p1_store].count += 1 + bowls[bowls[bowl].across].count; bowls[bowls[bowl].across].count = 0; bowls[bowl].count = 0; } return false; } //swap sides of the board void swapsides() { std::swap(p1_start, p2_start); std::swap(p1_store, p2_store); } //is the game over bool finished() const { int p1_side = 0; for(int i = p1_start; i < p1_start + 6; ++i) p1_side |= bowls[i].count; if(p1_side == 0) return true; int p2_side = 0; for(int i = p2_start; i < p2_start + 6; ++i) p2_side |= bowls[i].count; return p2_side == 0; } //heuristics to evaluate the board status int evaluate() const { //simple return bowls[p1_store].count - bowls[p2_store].count; } void crapprint() const //delete me! { std::cout<<" "; for(int i = p1_start; i < p1_start + 6; ++i) std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[bowls[i].across].count<<" "; std::cout<<std::endl; std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[p2_store].count<<std::setw(3*7)<<" "<<std::setw(2)<<bowls[p1_store].count<<std::endl; std::cout<<" "; for(int i = p1_start; i < p1_start + 6; ++i) std::cout<<std::setw(2)<<std::setfill(' ')<<bowls[i].count<<" "; std::cout<<std::endl; std::cout<<" "; for(int i = 0; i < 6 ; ++i) std::cout<<std::setw(2)<<std::setfill(' ')<<i<<" "; std::cout<<std::endl; } int num_bowls, num_seeds; std::vector<Bowl> bowls; int p1_start, p2_start; int p1_store, p2_store; }; enum PLAYER {PLAYER_MIN, PLAYER_MAX}; int choosemove_alphabeta(Board b, int depth, PLAYER player, int alpha, int beta) { if(player == PLAYER_MAX) { if(depth == 0) return b.evaluate(); //move toward closest win, avoid loss as long as possible if(b.finished()) { int diff = b.evaluate(); if(diff == 0) return depth; else if(diff > 0) return 1000 + diff + depth; else return -1000 + diff - depth; } for(int i = 0; i < 6; ++i) { if(b.bowls[b.p1_start + i].count == 0) continue; Board sub_b = b; int score = 0; if(sub_b.move(i)) // do we get another move? score = choosemove_alphabeta(sub_b, depth - 1, PLAYER_MAX, alpha, beta); else { sub_b.swapsides(); score = choosemove_alphabeta(sub_b, depth - 1, PLAYER_MIN, alpha, beta); } if(score >= beta) return beta; if(score > alpha) alpha = score; } return alpha; } else { if(depth == 0) return -b.evaluate(); //move toward closest win, avoid loss as long as possible if(b.finished()) { int diff = b.evaluate(); if(diff == 0) return -depth; else if(diff > 0) return -1000 - diff - depth; else return 1000 - diff + depth; } for(int i = 0; i < 6; ++i) { if(b.bowls[b.p1_start + i].count == 0) continue; Board sub_b = b; int score = 0; if(sub_b.move(i)) // do we get another move? score = choosemove_alphabeta(sub_b, depth - 1, PLAYER_MIN, alpha, beta); else { sub_b.swapsides(); score = choosemove_alphabeta(sub_b, depth - 1, PLAYER_MAX, alpha, beta); } if(score <= alpha) return alpha; if(score < beta) beta = score; } return beta; } } int choosemove(Board b) //purposely doing pass by value here as to not corrupt passed board (we may want to use different method when we do actual move search) { int best = std::numeric_limits<int>::min(); std::vector<int> best_i; //loop over available moves for(int i =0; i < 6; ++i) { if(b.bowls[b.p1_start + i].count == 0) continue; Board sub_b = b; int score = 0; if(sub_b.move(i)) score = choosemove_alphabeta(sub_b, 10, PLAYER_MAX, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); else { sub_b.swapsides(); score = choosemove_alphabeta(sub_b, 10, PLAYER_MIN, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); } //std::cout<<"choose: "<<i<<" "<<score<<" "<<-sub_b.evaluate()<<std::endl; if(score > best) { best = score; best_i.clear(); best_i.push_back(i); } if(score == best); best_i.push_back(i); } return best_i[rand() % best_i.size()]; } int main() { srand(time(0)); Board b; //b.bowls=std::vector<Bowl>({Bowl(1,1,12), Bowl(0,2,11), Bowl(0,3,10), Bowl(0,4,9), Bowl(2,5,8), Bowl(1,6,7), Bowl(0,7,0), Bowl(0,8,5), Bowl(0,9,4), Bowl(0,10,3), Bowl(0,11,2), Bowl(0,12,1), Bowl(1,13,0), Bowl(0,0,0)}); char nextmove = '\0'; int player = 1; while(std::cin && !b.finished() && nextmove != 'q' && nextmove != 'Q') { std::cout<<"Player "<<player<<std::endl; b.crapprint(); std::cout<<"Best move: "<<choosemove(b)<<std::endl; std::cout<<"Next move: "; std::cin>>nextmove; std::cout<<std::endl; if(nextmove == 'S' || nextmove == 's') { b.swapsides(); player = (player == 1) ? 2 : 1; } if(nextmove >= '0' && nextmove <= '5') { if(!b.move(nextmove - '0')) { b.swapsides(); player = (player == 1) ? 2 : 1; } } } if(b.finished()) { std::cout<<"Player "<<player<<std::endl; b.crapprint(); if(b.bowls[b.p1_store].count == b.bowls[b.p2_store].count) std::cout<<"Tie"<<std::endl; else if(player == 1) if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count) std::cout<<"Player 1 wins"<<std::endl; else std::cout<<"Player 2 wins"<<std::endl; else if(b.bowls[b.p1_store].count > b.bowls[b.p2_store].count) std::cout<<"Player 2 wins"<<std::endl; else std::cout<<"Player 1 wins"<<std::endl; if(abs(b.bowls[b.p1_store].count - b.bowls[b.p2_store].count) >= 10) std::cout<<"FATALITY"<<std::endl; } return 0; } <|endoftext|>
<commit_before>#include "iconproducer.h" #include <LXQt/Settings> #include <XdgIcon> #include <QDebug> #include <QtSvg/QSvgRenderer> #include <QPainter> #include <math.h> IconProducer::IconProducer(Solid::Battery *battery, QObject *parent) : QObject(parent) { connect(battery, &Solid::Battery::chargeStateChanged, this, &IconProducer::updateState); connect(battery, &Solid::Battery::chargePercentChanged, this, &IconProducer::updateChargePercent); connect(&mSettings, SIGNAL(settingsChanged()), this, SLOT(update())); mChargePercent = battery->chargePercent(); mState = battery->chargeState(); themeChanged(); } IconProducer::IconProducer(QObject *parent): QObject(parent) { themeChanged(); update(); } void IconProducer::updateChargePercent(int newChargePercent) { mChargePercent = newChargePercent; update(); } void IconProducer::updateState(int newState) { mState = (Solid::Battery::ChargeState) newState; update(); } void IconProducer::update() { QString newIconName; if (mSettings.isUseThemeIcons()) { QMap<float, QString> *levelNameMap = (mState == Solid::Battery::Discharging ? &mLevelNameMapDischarging : &mLevelNameMapCharging); foreach (float level, levelNameMap->keys()) { if (level >= mChargePercent) { newIconName = levelNameMap->value(level); break; } } } if (mSettings.isUseThemeIcons() && newIconName == mIconName) return; mIconName = newIconName; mIcon = mSettings.isUseThemeIcons() ? QIcon::fromTheme(mIconName) : circleIcon(); emit iconChanged(); } void IconProducer::themeChanged() { /* * We maintain specific charge-level-to-icon-name mappings for Oxygen and Awoken and * asume all other themes adhere to the freedesktop standard. * This is certainly not true, and as bug reports come in stating that * this and that theme is not working we will probably have to add new * mappings beside Oxygen and Awoken */ mLevelNameMapDischarging.clear(); mLevelNameMapCharging.clear(); if (QIcon::themeName() == "oxygen") { // Means: // Use 'battery-low' for levels up to 10 // - 'battery-caution' for levels between 10 and 20 // - 'battery-040' for levels between 20 and 40, etc.. mLevelNameMapDischarging[10] = "battery-low"; mLevelNameMapDischarging[20] = "battery-caution"; mLevelNameMapDischarging[40] = "battery-040"; mLevelNameMapDischarging[60] = "battery-060"; mLevelNameMapDischarging[80] = "battery-080"; mLevelNameMapDischarging[101] = "battery-100"; mLevelNameMapCharging[10] = "battery-charging-low"; mLevelNameMapCharging[20] = "battery-charging-caution"; mLevelNameMapCharging[40] = "battery-charging-040"; mLevelNameMapCharging[60] = "battery-charging-060"; mLevelNameMapCharging[80] = "battery-charging-080"; mLevelNameMapCharging[101] = "battery-charging"; } else if (QIcon::themeName().startsWith("AwOken")) // AwOken, AwOkenWhite, AwOkenDark { mLevelNameMapDischarging[5] = "battery-000"; mLevelNameMapDischarging[30] = "battery-020"; mLevelNameMapDischarging[50] = "battery-040"; mLevelNameMapDischarging[70] = "battery-060"; mLevelNameMapDischarging[95] = "battery-080"; mLevelNameMapDischarging[101] = "battery-100"; mLevelNameMapCharging[5] = "battery-000-charging"; mLevelNameMapCharging[30] = "battery-020-charging"; mLevelNameMapCharging[50] = "battery-040-charging"; mLevelNameMapCharging[70] = "battery-060-charging"; mLevelNameMapCharging[95] = "battery-080-charging"; mLevelNameMapCharging[101] = "battery-100-charging"; } else // As default we fall back to the freedesktop scheme. { mLevelNameMapDischarging[3] = "battery-empty"; mLevelNameMapDischarging[10] = "battery-caution"; mLevelNameMapDischarging[50] = "battery-low"; mLevelNameMapDischarging[90] = "battery-good"; mLevelNameMapDischarging[101] = "battery-full"; mLevelNameMapCharging[3] = "battery-empty"; mLevelNameMapCharging[10] = "battery-caution-charging"; mLevelNameMapCharging[50] = "battery-low-charging"; mLevelNameMapCharging[90] = "battery-good-charging"; mLevelNameMapCharging[101] = "battery-full-charging"; } update(); } QIcon& IconProducer::circleIcon() { static QMap<Solid::Battery::ChargeState, QMap<int, QIcon> > cache; int chargeLevelAsInt = (int) (mChargePercent + 0.49); if (!cache[mState].contains(chargeLevelAsInt)) cache[mState][chargeLevelAsInt] = buildCircleIcon(mState, mChargePercent); return cache[mState][chargeLevelAsInt]; } QIcon IconProducer::buildCircleIcon(Solid::Battery::ChargeState state, int chargeLevel) { static QString svg_template = "<svg\n" " xmlns:dc='http://purl.org/dc/elements/1.1/'\n" " xmlns:cc='http://creativecommons.org/ns#'\n" " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'\n" " xmlns:svg='http://www.w3.org/2000/svg'\n" " xmlns='http://www.w3.org/2000/svg'\n" " version='1.1'\n" " width='200'\n" " height='200'>\n" "\n" "<defs>\n" " <linearGradient id='greenGradient' x1='0%' y1='0%' x2='100%' y2='100%'>\n" " <stop offset='0%' style='stop-color:rgb(125,255,125);stop-opacity:1' />\n" " <stop offset='150%' style='stop-color:rgb(15,125,15);stop-opacity:1' />\n" " </linearGradient>\n" "</defs>\n" "\n" "<circle cx='100' cy='100' r='99' style='fill:#FFFFFF;stroke:none; opacity:0.2;'/>\n" "<path d='M 100,20 A80,80 0, LARGE_ARC_FLAG, SWEEP_FLAG, END_X,END_Y' style='fill:none; stroke:url(#greenGradient); stroke-width:38;' />\n" "<path d='M 100,20 A80,80 0, LARGE_ARC_FLAG, SWEEP_FLAG, END_X,END_Y' style='fill:none; stroke:red; stroke-width:38; opacity:RED_OPACITY' />\n" "\n" " STATE_MARKER\n" "\n" "</svg>"; static QString filledCircle = "<circle cx='100' cy='100' r='35'/>"; static QString plus = "<path d='M 60,100 L140,100 M100,60 L100,140' style='stroke:black; stroke-width:30;'/>"; static QString minus = "<path d='M 60,100 L140,100' style='stroke:black; stroke-width:30;'/>"; static QString hollowCircle = "<circle cx='100' cy='100' r='30' style='fill:none;stroke:black;stroke-width:10'/>"; QString svg = svg_template; if (chargeLevel > 99) chargeLevel = 99; double angle = M_PI_2 + 2 * M_PI * chargeLevel / 100; double circle_endpoint_x = 80.0 * cos(angle) + 100; double circle_endpoint_y = -80.0 * sin(angle) + 100; QString largeArgFlag = chargeLevel > 50 ? "1" : "0"; QString sweepFlag = "0"; svg.replace(QString("END_X"), QString::number(circle_endpoint_x)); svg.replace(QString("END_Y"), QString::number(circle_endpoint_y)); svg.replace(QString("LARGE_ARC_FLAG"), largeArgFlag); svg.replace(QString("SWEEP_FLAG"), sweepFlag); switch (state) { case Solid::Battery::FullyCharged: svg.replace("STATE_MARKER", filledCircle); break; case Solid::Battery::Charging: svg.replace("STATE_MARKER", plus); break; case Solid::Battery::Discharging: svg.replace("STATE_MARKER", minus); break; default: svg.replace("STATE_MARKER", hollowCircle); } if (state != Solid::Battery::FullyCharged && state != Solid::Battery::Charging && chargeLevel < mSettings.getPowerLowLevel() + 30) { if (chargeLevel <= mSettings.getPowerLowLevel() + 10) svg.replace("RED_OPACITY", "1"); else svg.replace("RED_OPACITY", QString::number((mSettings.getPowerLowLevel() + 30 - chargeLevel)/20)); } else svg.replace("RED_OPACITY", "0"); // qDebug() << svg; // Paint the svg on a pixmap and create an icon from that. QSvgRenderer render(svg.toLatin1()); QPixmap pixmap(render.defaultSize()); pixmap.fill(QColor(0,0,0,0)); QPainter painter(&pixmap); render.render(&painter); return QIcon(pixmap); } <commit_msg>Fix red-painting of built-in icon when power low<commit_after>#include "iconproducer.h" #include <LXQt/Settings> #include <XdgIcon> #include <QDebug> #include <QtSvg/QSvgRenderer> #include <QPainter> #include <math.h> IconProducer::IconProducer(Solid::Battery *battery, QObject *parent) : QObject(parent) { connect(battery, &Solid::Battery::chargeStateChanged, this, &IconProducer::updateState); connect(battery, &Solid::Battery::chargePercentChanged, this, &IconProducer::updateChargePercent); connect(&mSettings, SIGNAL(settingsChanged()), this, SLOT(update())); mChargePercent = battery->chargePercent(); mState = battery->chargeState(); themeChanged(); } IconProducer::IconProducer(QObject *parent): QObject(parent) { themeChanged(); update(); } void IconProducer::updateChargePercent(int newChargePercent) { mChargePercent = newChargePercent; update(); } void IconProducer::updateState(int newState) { mState = (Solid::Battery::ChargeState) newState; update(); } void IconProducer::update() { QString newIconName; if (mSettings.isUseThemeIcons()) { QMap<float, QString> *levelNameMap = (mState == Solid::Battery::Discharging ? &mLevelNameMapDischarging : &mLevelNameMapCharging); foreach (float level, levelNameMap->keys()) { if (level >= mChargePercent) { newIconName = levelNameMap->value(level); break; } } } if (mSettings.isUseThemeIcons() && newIconName == mIconName) return; mIconName = newIconName; mIcon = mSettings.isUseThemeIcons() ? QIcon::fromTheme(mIconName) : circleIcon(); emit iconChanged(); } void IconProducer::themeChanged() { /* * We maintain specific charge-level-to-icon-name mappings for Oxygen and Awoken and * asume all other themes adhere to the freedesktop standard. * This is certainly not true, and as bug reports come in stating that * this and that theme is not working we will probably have to add new * mappings beside Oxygen and Awoken */ mLevelNameMapDischarging.clear(); mLevelNameMapCharging.clear(); if (QIcon::themeName() == "oxygen") { // Means: // Use 'battery-low' for levels up to 10 // - 'battery-caution' for levels between 10 and 20 // - 'battery-040' for levels between 20 and 40, etc.. mLevelNameMapDischarging[10] = "battery-low"; mLevelNameMapDischarging[20] = "battery-caution"; mLevelNameMapDischarging[40] = "battery-040"; mLevelNameMapDischarging[60] = "battery-060"; mLevelNameMapDischarging[80] = "battery-080"; mLevelNameMapDischarging[101] = "battery-100"; mLevelNameMapCharging[10] = "battery-charging-low"; mLevelNameMapCharging[20] = "battery-charging-caution"; mLevelNameMapCharging[40] = "battery-charging-040"; mLevelNameMapCharging[60] = "battery-charging-060"; mLevelNameMapCharging[80] = "battery-charging-080"; mLevelNameMapCharging[101] = "battery-charging"; } else if (QIcon::themeName().startsWith("AwOken")) // AwOken, AwOkenWhite, AwOkenDark { mLevelNameMapDischarging[5] = "battery-000"; mLevelNameMapDischarging[30] = "battery-020"; mLevelNameMapDischarging[50] = "battery-040"; mLevelNameMapDischarging[70] = "battery-060"; mLevelNameMapDischarging[95] = "battery-080"; mLevelNameMapDischarging[101] = "battery-100"; mLevelNameMapCharging[5] = "battery-000-charging"; mLevelNameMapCharging[30] = "battery-020-charging"; mLevelNameMapCharging[50] = "battery-040-charging"; mLevelNameMapCharging[70] = "battery-060-charging"; mLevelNameMapCharging[95] = "battery-080-charging"; mLevelNameMapCharging[101] = "battery-100-charging"; } else // As default we fall back to the freedesktop scheme. { mLevelNameMapDischarging[3] = "battery-empty"; mLevelNameMapDischarging[10] = "battery-caution"; mLevelNameMapDischarging[50] = "battery-low"; mLevelNameMapDischarging[90] = "battery-good"; mLevelNameMapDischarging[101] = "battery-full"; mLevelNameMapCharging[3] = "battery-empty"; mLevelNameMapCharging[10] = "battery-caution-charging"; mLevelNameMapCharging[50] = "battery-low-charging"; mLevelNameMapCharging[90] = "battery-good-charging"; mLevelNameMapCharging[101] = "battery-full-charging"; } update(); } QIcon& IconProducer::circleIcon() { static QMap<Solid::Battery::ChargeState, QMap<int, QIcon> > cache; int chargeLevelAsInt = (int) (mChargePercent + 0.49); if (!cache[mState].contains(chargeLevelAsInt)) cache[mState][chargeLevelAsInt] = buildCircleIcon(mState, mChargePercent); return cache[mState][chargeLevelAsInt]; } QIcon IconProducer::buildCircleIcon(Solid::Battery::ChargeState state, int chargeLevel) { static QString svg_template = "<svg\n" " xmlns:dc='http://purl.org/dc/elements/1.1/'\n" " xmlns:cc='http://creativecommons.org/ns#'\n" " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'\n" " xmlns:svg='http://www.w3.org/2000/svg'\n" " xmlns='http://www.w3.org/2000/svg'\n" " version='1.1'\n" " width='200'\n" " height='200'>\n" "\n" "<defs>\n" " <linearGradient id='greenGradient' x1='0%' y1='0%' x2='100%' y2='100%'>\n" " <stop offset='0%' style='stop-color:rgb(125,255,125);stop-opacity:1' />\n" " <stop offset='150%' style='stop-color:rgb(15,125,15);stop-opacity:1' />\n" " </linearGradient>\n" "</defs>\n" "\n" "<circle cx='100' cy='100' r='99' style='fill:#FFFFFF;stroke:none; opacity:0.2;'/>\n" "<path d='M 100,20 A80,80 0, LARGE_ARC_FLAG, SWEEP_FLAG, END_X,END_Y' style='fill:none; stroke:url(#greenGradient); stroke-width:38;' />\n" "<path d='M 100,20 A80,80 0, LARGE_ARC_FLAG, SWEEP_FLAG, END_X,END_Y' style='fill:none; stroke:red; stroke-width:38; opacity:RED_OPACITY' />\n" "\n" " STATE_MARKER\n" "\n" "</svg>"; static QString filledCircle = "<circle cx='100' cy='100' r='35'/>"; static QString plus = "<path d='M 60,100 L140,100 M100,60 L100,140' style='stroke:black; stroke-width:30;'/>"; static QString minus = "<path d='M 60,100 L140,100' style='stroke:black; stroke-width:30;'/>"; static QString hollowCircle = "<circle cx='100' cy='100' r='30' style='fill:none;stroke:black;stroke-width:10'/>"; QString svg = svg_template; if (chargeLevel > 99) chargeLevel = 99; double angle = M_PI_2 + 2 * M_PI * chargeLevel / 100; double circle_endpoint_x = 80.0 * cos(angle) + 100; double circle_endpoint_y = -80.0 * sin(angle) + 100; QString largeArgFlag = chargeLevel > 50 ? "1" : "0"; QString sweepFlag = "0"; svg.replace(QString("END_X"), QString::number(circle_endpoint_x)); svg.replace(QString("END_Y"), QString::number(circle_endpoint_y)); svg.replace(QString("LARGE_ARC_FLAG"), largeArgFlag); svg.replace(QString("SWEEP_FLAG"), sweepFlag); switch (state) { case Solid::Battery::FullyCharged: svg.replace("STATE_MARKER", filledCircle); break; case Solid::Battery::Charging: svg.replace("STATE_MARKER", plus); break; case Solid::Battery::Discharging: svg.replace("STATE_MARKER", minus); break; default: svg.replace("STATE_MARKER", hollowCircle); } if (state != Solid::Battery::FullyCharged && state != Solid::Battery::Charging && chargeLevel < mSettings.getPowerLowLevel() + 30) { if (chargeLevel <= mSettings.getPowerLowLevel() + 10) svg.replace("RED_OPACITY", "1"); else svg.replace("RED_OPACITY", QString::number((mSettings.getPowerLowLevel() + 30 - chargeLevel)/20.0)); } else svg.replace("RED_OPACITY", "0"); // qDebug() << svg; // Paint the svg on a pixmap and create an icon from that. QSvgRenderer render(svg.toLatin1()); QPixmap pixmap(render.defaultSize()); pixmap.fill(QColor(0,0,0,0)); QPainter painter(&pixmap); render.render(&painter); return QIcon(pixmap); } <|endoftext|>
<commit_before>#ifndef CHANNEL_HPP_ #define CHANNEL_HPP_ #include <stdexcept> #include <fiber_channel.h> namespace fiberpp { template<typename EventDescriptorType, typename EventPayloadType> class UnboundedMultiProducerChannel { private: struct event_wrapper; public: typedef EventDescriptorType event_descriptor; typedef EventPayloadType event_payload; struct event { public: event(event_descriptor type, event_wrapper* wrapper) : type(type), wrapper(wrapper) {} const event_descriptor& getType() const { return type; } event_payload& getPayload() { return payload; } const event_payload& getPayload() const { return payload; } void setPayload(const event_payload& p) { payload = p; } private: event_descriptor type; public: event_wrapper* wrapper; private: event_payload payload; }; UnboundedMultiProducerChannel(fiber_signal_t* signal) { if(!fiber_unbounded_channel_init(&channel, signal)) { throw std::runtime_error("UnboundedMultiProducerEventSource() - error creating channel"); } } ~UnboundedMultiProducerChannel() { fiber_unbounded_channel_destroy(&channel); } //returns true if a fiber was scheduled as a result of sending the event bool send(event* e) { return fiber_unbounded_channel_send(&channel, e->wrapper); } event* receive() { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(fiber_unbounded_channel_receive(&channel)); event* const e = &reinterpret_cast<event_wrapper*>(wrapper->data)->e; e->wrapper = wrapper; return e; } event* tryReceive() { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(fiber_unbounded_channel_try_receive(&channel)); if(!wrapper) { return NULL; } event* const e = &reinterpret_cast<event_wrapper*>(wrapper->data)->e; e->wrapper = wrapper; return e; } private: struct event_wrapper : public fiber_unbounded_channel_message_t { event_wrapper(const event_descriptor& type) : e(type, this) { this->data = this; } event e; }; fiber_unbounded_channel_t channel; public: static event* allocEvent(const event_descriptor& type) { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(malloc(sizeof(*wrapper))); if(!wrapper) { throw std::bad_alloc(); } try { new (wrapper) event_wrapper(type); } catch(...) { free(wrapper); throw; } return &wrapper->e; } static void freeEvent(event* e) { event_wrapper* const wrapper = e->wrapper; e->~event(); free(wrapper); } }; template<typename EventDescriptorType, typename EventPayloadType> class UnboundedSingleProducerChannel { private: struct event_wrapper; public: typedef EventDescriptorType event_descriptor; typedef EventPayloadType event_payload; struct event { public: event(event_descriptor type, event_wrapper* wrapper) : type(type), wrapper(wrapper) {} const event_descriptor& getType() const { return type; } event_payload& getPayload() { return payload; } const event_payload& getPayload() const { return payload; } void setPayload(const event_payload& p) { payload = p; } private: event_descriptor type; public: event_wrapper* wrapper; private: event_payload payload; }; UnboundedSingleProducerChannel(fiber_signal_t* signal) { if(!fiber_unbounded_sp_channel_init(&channel, signal)) { throw std::runtime_error("UnboundedMultiProducerEventSource() - error creating channel"); } } ~UnboundedSingleProducerChannel() { fiber_unbounded_sp_channel_destroy(&channel); } //returns true if a fiber was scheduled as a result of sending the event bool send(event* e) { return fiber_unbounded_sp_channel_send(&channel, e->wrapper); } event* receive() { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(fiber_unbounded_sp_channel_receive(&channel)); event* const e = &reinterpret_cast<event_wrapper*>(wrapper->data)->e; e->wrapper = wrapper; return e; } event* tryReceive() { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(fiber_unbounded_sp_channel_try_receive(&channel)); if(!wrapper) { return NULL; } event* const e = &reinterpret_cast<event_wrapper*>(wrapper->data)->e; e->wrapper = wrapper; return e; } private: struct event_wrapper : public fiber_unbounded_sp_channel_message_t { event_wrapper(const event_descriptor& type) : e(type, this) { this->data = this; } event e; }; fiber_unbounded_sp_channel_t channel; public: static event* allocEvent(const event_descriptor& type) { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(malloc(sizeof(*wrapper))); if(!wrapper) { throw std::bad_alloc(); } try { new (wrapper) event_wrapper(type); } catch(...) { free(wrapper); throw; } return &wrapper->e; } static void freeEvent(event* e) { event_wrapper* const wrapper = e->wrapper; e->~event(); free(wrapper); } }; template<typename ChannelType> class ChannelSelector { public: typedef typename ChannelType::event event; typedef typename ChannelType::event_descriptor event_descriptor; typedef typename ChannelType::event_payload event_payload; ChannelSelector(size_t numChannels, ChannelType** channels, fiber_signal_t* signal) : signal(signal), numChannels(numChannels), channels(channels) { if(!numChannels || !channels) { throw std::runtime_error("MultiChannel() - must provide channels"); } for(size_t i = 0; i < numChannels; ++i) { if(!channels[i]) { throw std::runtime_error("MultiChannel() - NULL channel provided"); } } } event* receive() { while(1) { for(size_t i = 0; i < numChannels; ++i) { event* const ret = channels[i]->tryReceive(); if(ret) { return ret; } } if(signal) { fiber_signal_wait(signal); } } return NULL; } event* tryReceive() { for(size_t i = 0; i < numChannels; ++i) { event* const ret = channels[i]->tryReceive(); if(ret) { return ret; } } return NULL; } static event* allocEvent(const event_descriptor& type) { return ChannelType::allocEvent(); } static void freeEvent(event* e) { ChannelType::freeEvent(e); } private: fiber_signal_t* signal; size_t numChannels; ChannelType** channels; }; }; #endif <commit_msg>cleaner channel.hpp<commit_after>#ifndef CHANNEL_HPP_ #define CHANNEL_HPP_ #include <stdexcept> #include <fiber_channel.h> namespace fiberpp { template<typename EventDescriptorType, typename EventPayloadType> class UnboundedMultiProducerChannel { private: struct event_wrapper; public: typedef EventDescriptorType event_descriptor; typedef EventPayloadType event_payload; struct event { friend class UnboundedMultiProducerChannel; public: event(event_descriptor type, event_wrapper* wrapper) : type(type), wrapper(wrapper) {} const event_descriptor& getType() const { return type; } event_payload& getPayload() { return payload; } const event_payload& getPayload() const { return payload; } void setPayload(const event_payload& p) { payload = p; } private: event_descriptor type; event_wrapper* wrapper; event_payload payload; }; UnboundedMultiProducerChannel(fiber_signal_t* signal) { if(!fiber_unbounded_channel_init(&channel, signal)) { throw std::runtime_error("UnboundedMultiProducerEventSource() - error creating channel"); } } ~UnboundedMultiProducerChannel() { fiber_unbounded_channel_destroy(&channel); } //returns true if a fiber was scheduled as a result of sending the event bool send(event* e) { return fiber_unbounded_channel_send(&channel, e->wrapper); } event* receive() { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(fiber_unbounded_channel_receive(&channel)); event* const e = &reinterpret_cast<event_wrapper*>(wrapper->data)->e; e->wrapper = wrapper; return e; } event* tryReceive() { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(fiber_unbounded_channel_try_receive(&channel)); if(!wrapper) { return NULL; } event* const e = &reinterpret_cast<event_wrapper*>(wrapper->data)->e; e->wrapper = wrapper; return e; } private: struct event_wrapper : public fiber_unbounded_channel_message_t { event_wrapper(const event_descriptor& type) : e(type, this) { this->data = this; } event e; }; fiber_unbounded_channel_t channel; public: static event* allocEvent(const event_descriptor& type) { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(malloc(sizeof(*wrapper))); if(!wrapper) { throw std::bad_alloc(); } try { new (wrapper) event_wrapper(type); } catch(...) { free(wrapper); throw; } return &wrapper->e; } static void freeEvent(event* e) { event_wrapper* const wrapper = e->wrapper; e->~event(); free(wrapper); } }; template<typename EventDescriptorType, typename EventPayloadType> class UnboundedSingleProducerChannel { private: struct event_wrapper; public: typedef EventDescriptorType event_descriptor; typedef EventPayloadType event_payload; struct event { friend class UnboundedSingleProducerChannel; public: event(event_descriptor type, event_wrapper* wrapper) : type(type), wrapper(wrapper) {} const event_descriptor& getType() const { return type; } event_payload& getPayload() { return payload; } const event_payload& getPayload() const { return payload; } void setPayload(const event_payload& p) { payload = p; } private: event_descriptor type; event_wrapper* wrapper; event_payload payload; }; UnboundedSingleProducerChannel(fiber_signal_t* signal) { if(!fiber_unbounded_sp_channel_init(&channel, signal)) { throw std::runtime_error("UnboundedMultiProducerEventSource() - error creating channel"); } } ~UnboundedSingleProducerChannel() { fiber_unbounded_sp_channel_destroy(&channel); } //returns true if a fiber was scheduled as a result of sending the event bool send(event* e) { return fiber_unbounded_sp_channel_send(&channel, e->wrapper); } event* receive() { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(fiber_unbounded_sp_channel_receive(&channel)); event* const e = &reinterpret_cast<event_wrapper*>(wrapper->data)->e; e->wrapper = wrapper; return e; } event* tryReceive() { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(fiber_unbounded_sp_channel_try_receive(&channel)); if(!wrapper) { return NULL; } event* const e = &reinterpret_cast<event_wrapper*>(wrapper->data)->e; e->wrapper = wrapper; return e; } private: struct event_wrapper : public fiber_unbounded_sp_channel_message_t { event_wrapper(const event_descriptor& type) : e(type, this) { this->data = this; } event e; }; fiber_unbounded_sp_channel_t channel; public: static event* allocEvent(const event_descriptor& type) { event_wrapper* const wrapper = reinterpret_cast<event_wrapper*>(malloc(sizeof(*wrapper))); if(!wrapper) { throw std::bad_alloc(); } try { new (wrapper) event_wrapper(type); } catch(...) { free(wrapper); throw; } return &wrapper->e; } static void freeEvent(event* e) { event_wrapper* const wrapper = e->wrapper; e->~event(); free(wrapper); } }; template<typename ChannelType> class ChannelSelector { public: typedef typename ChannelType::event event; typedef typename ChannelType::event_descriptor event_descriptor; typedef typename ChannelType::event_payload event_payload; ChannelSelector(size_t numChannels, ChannelType** channels, fiber_signal_t* signal) : signal(signal), numChannels(numChannels), channels(channels) { if(!numChannels || !channels) { throw std::runtime_error("MultiChannel() - must provide channels"); } for(size_t i = 0; i < numChannels; ++i) { if(!channels[i]) { throw std::runtime_error("MultiChannel() - NULL channel provided"); } } } event* receive() { while(1) { for(size_t i = 0; i < numChannels; ++i) { event* const ret = channels[i]->tryReceive(); if(ret) { return ret; } } if(signal) { fiber_signal_wait(signal); } } return NULL; } event* tryReceive() { for(size_t i = 0; i < numChannels; ++i) { event* const ret = channels[i]->tryReceive(); if(ret) { return ret; } } return NULL; } static event* allocEvent(const event_descriptor& type) { return ChannelType::allocEvent(); } static void freeEvent(event* e) { ChannelType::freeEvent(e); } private: fiber_signal_t* signal; size_t numChannels; ChannelType** channels; }; }; #endif <|endoftext|>
<commit_before>#include <iostream> #include <array> #include "tinycl.h" #include "sparsematrix.h" #include "cgsolver.h" CGSolver::CGSolver(const SparseMatrix<float> &mat, const std::vector<float> &b, tcl::Context &context, int iter, float len) : context(context), maxIterations(iter), dimensions(mat.dim), matElems(mat.elements.size()), convergeLength(len) { loadKernels(); createBuffers(mat, b); } void CGSolver::solve(){ initSolve(); float rLen = 100; int i = 0; for (i = 0; i < maxIterations && rLen >= convergeLength; ++i){ //Compute Ap context.runNDKernel(matVecMult, cl::NDRange(dimensions), cl::NullRange, cl::NullRange, false); //Compute p dot Ap dot.setArg(0, aMultp); dot.setArg(1, p); dot.setArg(2, apDotp); context.runNDKernel(dot, cl::NDRange(dimensions / 2), cl::NullRange, cl::NullRange, false); context.runNDKernel(updateAlpha, cl::NDRange(1), cl::NullRange, cl::NullRange, false); context.runNDKernel(updateXR, cl::NDRange(dimensions), cl::NullRange, cl::NullRange, false); //Find new r dot r dot.setArg(0, r); dot.setArg(1, r); dot.setArg(2, rDotr[1]); context.runNDKernel(dot, cl::NDRange(dimensions / 2), cl::NullRange, cl::NullRange, false); context.runNDKernel(updateDir, cl::NDRange(dimensions), cl::NullRange, cl::NullRange, false); //Update old r dot r and find rLen context.mQueue.enqueueCopyBuffer(rDotr[1], rDotr[0], 0, 0, sizeof(float)); context.readData(rDotr[1], sizeof(float), &rLen, 0, true); rLen = std::sqrtf(rLen); } std::cout << "solution took: " << i << " iterations, final residual length: " << rLen << std::endl; } void CGSolver::updateB(const std::vector<float> &b){ bVec = context.buffer(tcl::MEM::READ_ONLY, dimensions * sizeof(float), &b[0]); } void CGSolver::updateB(cl::Buffer &b){ bVec = b; } std::vector<float> CGSolver::getResult(){ std::vector<float> res; res.resize(dimensions); context.readData(result, dimensions * sizeof(float), &res[0], 0, true); return res; } cl::Buffer CGSolver::getResultBuffer(){ return result; } void CGSolver::loadKernels(){ program = context.loadProgram("../res/cg_solver.cl"); initVects = cl::Kernel(program, "init_vects"); matVecMult = cl::Kernel(program, "mat_vec_mult"); dot = cl::Kernel(program, "big_dot"); updateXR = cl::Kernel(program, "update_xr"); updateDir = cl::Kernel(program, "update_dir"); updateAlpha = cl::Kernel(program, "update_alpha"); } void CGSolver::createBuffers(const SparseMatrix<float> &mat, const std::vector<float> &b){ std::vector<int> rows, cols; std::vector<float> vals; rows.resize(mat.elements.size()); cols.resize(mat.elements.size()); vals.resize(mat.elements.size()); mat.getRaw(&rows[0], &cols[0], &vals[0]); matrix[MATRIX::ROW] = context.buffer(tcl::MEM::READ_ONLY, rows.size() * sizeof(int), &rows[0]); matrix[MATRIX::COL] = context.buffer(tcl::MEM::READ_ONLY, cols.size() * sizeof(int), &cols[0]); matrix[MATRIX::VAL] = context.buffer(tcl::MEM::READ_ONLY, vals.size() * sizeof(float), &vals[0]); //In the case that we want to upload everything but the b vector, skip creating it if (!b.empty()){ bVec = context.buffer(tcl::MEM::READ_ONLY, dimensions * sizeof(float), &b[0]); } result = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); //Setup the other buffers we'll need for the computation r = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); p = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); aMultp = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); apDotp = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); alpha = context.buffer(tcl::MEM::READ_WRITE, sizeof(float), nullptr); for (int i = 0; i < 2; ++i){ rDotr[i] = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); } } void CGSolver::initSolve(){ initVects.setArg(0, result); initVects.setArg(1, r); initVects.setArg(2, p); initVects.setArg(3, bVec); //We can run the intialization kernel while we setup more stuff, so start it now context.runNDKernel(initVects, cl::NDRange(dimensions), cl::NullRange, cl::NullRange, false); //We can do the same thing for finding the initial r dot r buffer dot.setArg(0, r); dot.setArg(1, r); dot.setArg(2, rDotr[0]); context.runNDKernel(dot, cl::NDRange(dimensions / 2), cl::NullRange, cl::NullRange, false); matVecMult.setArg(0, sizeof(int), &matElems); matVecMult.setArg(1, matrix[MATRIX::ROW]); matVecMult.setArg(2, matrix[MATRIX::COL]); matVecMult.setArg(3, matrix[MATRIX::VAL]); matVecMult.setArg(4, p); matVecMult.setArg(5, aMultp); updateXR.setArg(0, alpha); updateXR.setArg(1, p); updateXR.setArg(2, aMultp); updateXR.setArg(3, result); updateXR.setArg(4, r); updateDir.setArg(0, rDotr[1]); updateDir.setArg(1, rDotr[0]); updateDir.setArg(2, r); updateDir.setArg(3, p); updateAlpha.setArg(0, rDotr[0]); updateAlpha.setArg(1, apDotp); updateAlpha.setArg(2, alpha); } <commit_msg>CGSolver should update the kernel argument when updating b<commit_after>#include <iostream> #include <array> #include "tinycl.h" #include "sparsematrix.h" #include "cgsolver.h" CGSolver::CGSolver(const SparseMatrix<float> &mat, const std::vector<float> &b, tcl::Context &context, int iter, float len) : context(context), maxIterations(iter), dimensions(mat.dim), matElems(mat.elements.size()), convergeLength(len) { loadKernels(); createBuffers(mat, b); } void CGSolver::solve(){ initSolve(); float rLen = 100; int i = 0; for (i = 0; i < maxIterations && rLen >= convergeLength; ++i){ //Compute Ap context.runNDKernel(matVecMult, cl::NDRange(dimensions), cl::NullRange, cl::NullRange, false); //Compute p dot Ap dot.setArg(0, aMultp); dot.setArg(1, p); dot.setArg(2, apDotp); context.runNDKernel(dot, cl::NDRange(dimensions / 2), cl::NullRange, cl::NullRange, false); context.runNDKernel(updateAlpha, cl::NDRange(1), cl::NullRange, cl::NullRange, false); context.runNDKernel(updateXR, cl::NDRange(dimensions), cl::NullRange, cl::NullRange, false); //Find new r dot r dot.setArg(0, r); dot.setArg(1, r); dot.setArg(2, rDotr[1]); context.runNDKernel(dot, cl::NDRange(dimensions / 2), cl::NullRange, cl::NullRange, false); context.runNDKernel(updateDir, cl::NDRange(dimensions), cl::NullRange, cl::NullRange, false); //Update old r dot r and find rLen context.mQueue.enqueueCopyBuffer(rDotr[1], rDotr[0], 0, 0, sizeof(float)); context.readData(rDotr[1], sizeof(float), &rLen, 0, true); rLen = std::sqrtf(rLen); } std::cout << "solution took: " << i << " iterations, final residual length: " << rLen << std::endl; } void CGSolver::updateB(const std::vector<float> &b){ bVec = context.buffer(tcl::MEM::READ_ONLY, dimensions * sizeof(float), &b[0]); initVects.setArg(3, bVec); } void CGSolver::updateB(cl::Buffer &b){ bVec = b; initVects.setArg(3, bVec); } std::vector<float> CGSolver::getResult(){ std::vector<float> res; res.resize(dimensions); context.readData(result, dimensions * sizeof(float), &res[0], 0, true); return res; } cl::Buffer CGSolver::getResultBuffer(){ return result; } void CGSolver::loadKernels(){ program = context.loadProgram("../res/cg_solver.cl"); initVects = cl::Kernel(program, "init_vects"); matVecMult = cl::Kernel(program, "mat_vec_mult"); dot = cl::Kernel(program, "big_dot"); updateXR = cl::Kernel(program, "update_xr"); updateDir = cl::Kernel(program, "update_dir"); updateAlpha = cl::Kernel(program, "update_alpha"); } void CGSolver::createBuffers(const SparseMatrix<float> &mat, const std::vector<float> &b){ std::vector<int> rows, cols; std::vector<float> vals; rows.resize(mat.elements.size()); cols.resize(mat.elements.size()); vals.resize(mat.elements.size()); mat.getRaw(&rows[0], &cols[0], &vals[0]); matrix[MATRIX::ROW] = context.buffer(tcl::MEM::READ_ONLY, rows.size() * sizeof(int), &rows[0]); matrix[MATRIX::COL] = context.buffer(tcl::MEM::READ_ONLY, cols.size() * sizeof(int), &cols[0]); matrix[MATRIX::VAL] = context.buffer(tcl::MEM::READ_ONLY, vals.size() * sizeof(float), &vals[0]); //In the case that we want to upload everything but the b vector if (!b.empty()){ bVec = context.buffer(tcl::MEM::READ_ONLY, dimensions * sizeof(float), &b[0]); } result = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); //Setup the other buffers we'll need for the computation r = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); p = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); aMultp = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); apDotp = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); alpha = context.buffer(tcl::MEM::READ_WRITE, sizeof(float), nullptr); for (int i = 0; i < 2; ++i){ rDotr[i] = context.buffer(tcl::MEM::READ_WRITE, dimensions * sizeof(float), nullptr); } } void CGSolver::initSolve(){ initVects.setArg(0, result); initVects.setArg(1, r); initVects.setArg(2, p); initVects.setArg(3, bVec); //We can run the intialization kernel while we setup more stuff, so start it now context.runNDKernel(initVects, cl::NDRange(dimensions), cl::NullRange, cl::NullRange, false); //We can do the same thing for finding the initial r dot r buffer dot.setArg(0, r); dot.setArg(1, r); dot.setArg(2, rDotr[0]); context.runNDKernel(dot, cl::NDRange(dimensions / 2), cl::NullRange, cl::NullRange, false); matVecMult.setArg(0, sizeof(int), &matElems); matVecMult.setArg(1, matrix[MATRIX::ROW]); matVecMult.setArg(2, matrix[MATRIX::COL]); matVecMult.setArg(3, matrix[MATRIX::VAL]); matVecMult.setArg(4, p); matVecMult.setArg(5, aMultp); updateXR.setArg(0, alpha); updateXR.setArg(1, p); updateXR.setArg(2, aMultp); updateXR.setArg(3, result); updateXR.setArg(4, r); updateDir.setArg(0, rDotr[1]); updateDir.setArg(1, rDotr[0]); updateDir.setArg(2, r); updateDir.setArg(3, p); updateAlpha.setArg(0, rDotr[0]); updateAlpha.setArg(1, apDotp); updateAlpha.setArg(2, alpha); } <|endoftext|>
<commit_before> #include <boost/python.hpp> #include <boost/python/def.hpp> #include <scitbx/array_family/flex_types.h> #include "../centroid.h" using namespace boost::python; namespace dials { namespace integration { namespace boost_python { void export_centroid() { def("centroid2d", &centroid2d <scitbx::af::flex_int>); def("centroid3d", &centroid3d <scitbx::af::flex_int>); def("centroid2d", &centroid2d <scitbx::af::flex_int, scitbx::af::flex_int>); def("centroid3d", &centroid3d <scitbx::af::flex_int, scitbx::af::flex_int>); } } // namespace = boost_python }} // namespace = dials::spot_prediction <commit_msg>Changed the way that the centroid functions are wrapped in boost python code. <commit_after> #include <boost/python.hpp> #include <boost/python/def.hpp> #include <scitbx/array_family/flex_types.h> #include "../centroid.h" using namespace boost::python; namespace dials { namespace integration { namespace boost_python { void export_centroid() { scitbx::vec2 <double> (*centroid2d_int)(const scitbx::af::flex_int&, scitbx::af::tiny <int, 4>) = &centroid2d <scitbx::af::flex_int>; scitbx::vec2 <double> (*centroid2d_int_mask)(const scitbx::af::flex_int&, const scitbx::af::flex_int&, scitbx::af::tiny <int, 4>, int) = &centroid2d <scitbx::af::flex_int, scitbx::af::flex_int>; scitbx::vec3 <double> (*centroid3d_int)(const scitbx::af::flex_int&, scitbx::af::tiny <int, 6>) = &centroid3d <scitbx::af::flex_int>; scitbx::vec3 <double> (*centroid3d_int_mask)(const scitbx::af::flex_int&, const scitbx::af::flex_int&, scitbx::af::tiny <int, 6>, int) = &centroid3d <scitbx::af::flex_int, scitbx::af::flex_int>; def("centroid2d", centroid2d_int); def("centroid3d", centroid3d_int); def("centroid2d", centroid2d_int_mask); def("centroid3d", centroid3d_int_mask); } } // namespace = boost_python }} // namespace = dials::spot_prediction <|endoftext|>
<commit_before> #include "Timestamp.h" namespace Vq { Timestamp::Timestamp( const TimeVal &timeVal ) { } Timestamp::Timestamp( const Timestamp &other ) { } Timestamp::Timestamp( Timestamp &&other ) { } Timestamp & Timestamp::operator = ( const Timestamp &other ) { } Timestamp & Timestamp::operator = ( const Timestamp &&other ) { } bool Timestamp::operator == ( const Timestamp &other ) { } bool Timestamp::operator != ( const Timestamp &other ) { } bool Timestamp::operator > ( const Timestamp &other ) { } bool Timestamp::operator >= ( const Timestamp &other ) { } bool Timestamp::operator < ( const Timestamp &other ) { } bool Timestamp::operator <= ( const Timestamp &other ) { } Timestamp Timestamp::operator + ( const Timestamp &other ) { } Timestamp Timestamp::operator - ( const Timestamp &other ) { } Timestamp & Timestamp::operator += ( const Timestamp &other ) { } Timestamp & Timestamp::operator -= ( const Timestamp &other ) { } Timestamp::TimeVal Timestamp::toUTCMicroSec() const { } Timestamp::TimeVal Timestamp::toPosixMicroSec() const { } Timestamp Timestamp::now() { } Timestamp Timestamp::fromPosixEpoch( const std::time_t &time ) { } Timestamp Timestamp::fromUTCTime( const TimeVal &utc ) { } } <commit_msg>Started impl of timestamp<commit_after>#include <memory> #include "Timestamp.h" namespace Vq { class Timestamp::Data { public: explicit Data( const Timestamp::TimeVal &val ) : m_val( val ) { } Timestamp::TimeVal & val() { return m_val; } private: Timestamp::TimeVal m_val; }; Timestamp::Timestamp( const TimeVal &timeVal ) : m_data( std::make_unique< Timestamp::Data >( timeVal )) { } Timestamp::Timestamp( const Timestamp &other ) : m_data( std::make_unique< Timestamp::Data >( other.m_data->val() )) { } Timestamp::Timestamp( Timestamp &&other ) : m_data( std::make_unique< Timestamp::Data >( std::move( other.m_data->val() ))) { } Timestamp & Timestamp::operator = ( const Timestamp &other ) { *m_data = *other.m_data; return *this; } Timestamp & Timestamp::operator = ( const Timestamp &&other ) { *m_data = std::move( *other.m_data ); return *this; } bool Timestamp::operator == ( const Timestamp &other ) { return m_data->val() == other.m_data->val(); } bool Timestamp::operator != ( const Timestamp &other ) { return ! ( *this == other ); } bool Timestamp::operator > ( const Timestamp &other ) { return m_data->val() > other.m_data->val(); } bool Timestamp::operator >= ( const Timestamp &other ) { return m_data->val() >= other.m_data->val(); } bool Timestamp::operator < ( const Timestamp &other ) { return m_data->val() < other.m_data->val(); } bool Timestamp::operator <= ( const Timestamp &other ) { return m_data->val() <= other.m_data->val(); } Timestamp Timestamp::operator + ( const Timestamp &other ) { auto sum = m_data->val() + other.m_data->val(); return Timestamp{ sum }; } Timestamp Timestamp::operator - ( const Timestamp &other ) { auto diff = m_data->val() - other.m_data->val(); return Timestamp{ diff}; } Timestamp & Timestamp::operator += ( const Timestamp &other ) { m_data->val() += other.m_data->val(); return *this; } Timestamp & Timestamp::operator -= ( const Timestamp &other ) { m_data->val() -= other.m_data->val(); return *this; } Timestamp::TimeVal Timestamp::toUTCMicroSec() const { } Timestamp::TimeVal Timestamp::toPosixMicroSec() const { } Timestamp Timestamp::now() { } Timestamp Timestamp::fromPosixEpoch( const std::time_t &time ) { } Timestamp Timestamp::fromUTCTime( const TimeVal &utc ) { } } <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2008-2009 Soeren Sonnenburg * Copyright (C) 2008-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/lib/ShogunException.h> #include <shogun/lib/memory.h> #include <shogun/lib/common.h> #include <shogun/lib/Map.h> #include <shogun/base/SGObject.h> using namespace shogun; #ifdef TRACE_MEMORY_ALLOCS extern CMap<void*, shogun::MemoryBlock>* sg_mallocs; MemoryBlock::MemoryBlock() : ptr(NULL), size(0), file(NULL), line(-1), is_sgobject(false) { } MemoryBlock::MemoryBlock(void* p) : ptr(p), size(0), file(NULL), line(-1), is_sgobject(false) { } MemoryBlock::MemoryBlock(void* p, size_t sz, const char* fname, int linenr) : ptr(p), size(sz), file(fname), line(linenr), is_sgobject(false) { } MemoryBlock::MemoryBlock(const MemoryBlock &b) { ptr=b.ptr; size=b.size; file=b.file; line=b.line; is_sgobject=b.is_sgobject; } bool MemoryBlock::operator==(const MemoryBlock &b) const { return ptr==b.ptr; } void MemoryBlock::display() { if (line!=-1) { printf("Memory block at %p of size %lld bytes (allocated in %s line %d)\n", ptr, (long long int) size, file, line); } else { if (is_sgobject) { CSGObject* obj=(CSGObject*) ptr; printf("SGObject '%s' at %p of size %lld bytes with %d ref's\n", obj->get_name(), obj, (long long int) size, obj->ref_count()); } else { printf("Object at %p of size %lld bytes\n", ptr, (long long int) size); } } } void MemoryBlock::set_sgobject() { is_sgobject=true; } #endif void* operator new(size_t size) throw (std::bad_alloc) { void *p=malloc(size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size)); #endif if (!p) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using new().\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using new.\n"); } return p; } void operator delete(void *p) throw() { #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->remove(p); #endif free(p); } void* operator new[](size_t size) throw(std::bad_alloc) { void *p=malloc(size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size)); #endif if (!p) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using new[].\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using new[].\n"); } return p; } void operator delete[](void *p) throw() { #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->remove(p); #endif free(p); } void* sg_malloc(size_t size #ifdef TRACE_MEMORY_ALLOCS , const char* file, int line #endif ) { void* p=malloc(size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size, file, line)); #endif if (!p) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using malloc.\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using malloc.\n"); } return p; } void* sg_calloc(size_t num, size_t size #ifdef TRACE_MEMORY_ALLOCS , const char* file, int line #endif ) { void* p=calloc(num, size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size, file, line)); #endif if (!p) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using calloc.\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using calloc.\n"); } return p; } void sg_free(void* ptr) { #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->remove(ptr); #endif free(ptr); } void* sg_realloc(void* ptr, size_t size #ifdef TRACE_MEMORY_ALLOCS , const char* file, int line #endif ) { void* p=realloc(ptr, size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->remove(ptr); if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size, file, line)); #endif if (!p && (size || !ptr)) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using realloc.\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using realloc.\n"); } return p; } #ifdef TRACE_MEMORY_ALLOCS void list_memory_allocs() { MemoryBlock* temp; if (sg_mallocs) { int32_t num=sg_mallocs->get_num_elements(); int32_t size=sg_mallocs->get_array_size(); printf("%d Blocks are allocated:\n", num); for (int32_t i=0; i<size; i++) { temp=sg_mallocs->get_element_ptr(i); if (temp!=NULL) temp->display(); } } } #endif <commit_msg>add specialization for SGVector and malloc/calloc/realloc/free<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2008-2009 Soeren Sonnenburg * Copyright (C) 2008-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/lib/ShogunException.h> #include <shogun/lib/memory.h> #include <shogun/lib/common.h> #include <shogun/lib/Map.h> #include <shogun/base/SGObject.h> #include <shogun/lib/SGVector.h> using namespace shogun; #ifdef TRACE_MEMORY_ALLOCS extern CMap<void*, shogun::MemoryBlock>* sg_mallocs; MemoryBlock::MemoryBlock() : ptr(NULL), size(0), file(NULL), line(-1), is_sgobject(false) { } MemoryBlock::MemoryBlock(void* p) : ptr(p), size(0), file(NULL), line(-1), is_sgobject(false) { } MemoryBlock::MemoryBlock(void* p, size_t sz, const char* fname, int linenr) : ptr(p), size(sz), file(fname), line(linenr), is_sgobject(false) { } MemoryBlock::MemoryBlock(const MemoryBlock &b) { ptr=b.ptr; size=b.size; file=b.file; line=b.line; is_sgobject=b.is_sgobject; } bool MemoryBlock::operator==(const MemoryBlock &b) const { return ptr==b.ptr; } void MemoryBlock::display() { if (line!=-1) { printf("Memory block at %p of size %lld bytes (allocated in %s line %d)\n", ptr, (long long int) size, file, line); } else { if (is_sgobject) { CSGObject* obj=(CSGObject*) ptr; printf("SGObject '%s' at %p of size %lld bytes with %d ref's\n", obj->get_name(), obj, (long long int) size, obj->ref_count()); } else { printf("Object at %p of size %lld bytes\n", ptr, (long long int) size); } } } void MemoryBlock::set_sgobject() { is_sgobject=true; } #endif void* operator new(size_t size) throw (std::bad_alloc) { void *p=malloc(size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size)); #endif if (!p) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using new().\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using new.\n"); } return p; } void operator delete(void *p) throw() { #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->remove(p); #endif free(p); } void* operator new[](size_t size) throw(std::bad_alloc) { void *p=malloc(size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size)); #endif if (!p) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using new[].\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using new[].\n"); } return p; } void operator delete[](void *p) throw() { #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->remove(p); #endif free(p); } void* sg_malloc(size_t size #ifdef TRACE_MEMORY_ALLOCS , const char* file, int line #endif ) { void* p=malloc(size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size, file, line)); #endif if (!p) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using malloc.\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using malloc.\n"); } return p; } void* sg_calloc(size_t num, size_t size #ifdef TRACE_MEMORY_ALLOCS , const char* file, int line #endif ) { void* p=calloc(num, size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size, file, line)); #endif if (!p) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using calloc.\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using calloc.\n"); } return p; } void sg_free(void* ptr) { #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->remove(ptr); #endif free(ptr); } void* sg_realloc(void* ptr, size_t size #ifdef TRACE_MEMORY_ALLOCS , const char* file, int line #endif ) { void* p=realloc(ptr, size); #ifdef TRACE_MEMORY_ALLOCS if (sg_mallocs) sg_mallocs->remove(ptr); if (sg_mallocs) sg_mallocs->add(p, MemoryBlock(p,size, file, line)); #endif if (!p && (size || !ptr)) { const size_t buf_len=128; char buf[buf_len]; size_t written=snprintf(buf, buf_len, "Out of memory error, tried to allocate %lld bytes using realloc.\n", (long long int) size); if (written<buf_len) throw ShogunException(buf); else throw ShogunException("Out of memory error using realloc.\n"); } return p; } #ifdef TRACE_MEMORY_ALLOCS void list_memory_allocs() { MemoryBlock* temp; if (sg_mallocs) { int32_t num=sg_mallocs->get_num_elements(); int32_t size=sg_mallocs->get_array_size(); printf("%d Blocks are allocated:\n", num); for (int32_t i=0; i<size; i++) { temp=sg_mallocs->get_element_ptr(i); if (temp!=NULL) temp->display(); } } } #endif #ifdef TRACE_MEMORY_ALLOCS #define SG_SPECIALIZED_MALLOC(type) \ template<> type* sg_generic_malloc<type >(size_t len, const char* file, int line) \ { \ return new type[len](); \ } \ \ template<> type* sg_generic_calloc<type >(size_t len, const char* file, int line) \ { \ return new type[len](); \ } \ \ template<> type* sg_generic_realloc<type >(type* ptr, size_t len, const char* file, int line) \ { \ return NULL; \ } \ \ template<> void sg_generic_free<type >(type* ptr) \ { \ delete[] ptr; \ } #else // TRACE_MEMORY_ALLOCS #define SG_SPECIALIZED_MALLOC(type) \ template<> type* sg_generic_malloc<type >(size_t len) \ { \ return new type[len](); \ } \ \ template<> type* sg_generic_calloc<type >(size_t len) \ { \ return new type[len](); \ } \ \ template<> type* sg_generic_realloc<type >(type* ptr, size_t len) \ { \ return NULL; \ } \ \ template<> void sg_generic_free<type >(type* ptr) \ { \ delete[] ptr; \ } #endif // TRACE_MEMORY_ALLOCS SG_SPECIALIZED_MALLOC(SGVector<bool>) SG_SPECIALIZED_MALLOC(SGVector<char>) SG_SPECIALIZED_MALLOC(SGVector<int8_t>) SG_SPECIALIZED_MALLOC(SGVector<uint8_t>) SG_SPECIALIZED_MALLOC(SGVector<int16_t>) SG_SPECIALIZED_MALLOC(SGVector<uint16_t>) SG_SPECIALIZED_MALLOC(SGVector<int32_t>) SG_SPECIALIZED_MALLOC(SGVector<uint32_t>) SG_SPECIALIZED_MALLOC(SGVector<int64_t>) SG_SPECIALIZED_MALLOC(SGVector<uint64_t>) SG_SPECIALIZED_MALLOC(SGVector<float32_t>) SG_SPECIALIZED_MALLOC(SGVector<float64_t>) SG_SPECIALIZED_MALLOC(SGVector<floatmax_t>) #undef SG_GENERIC_MALLOC <|endoftext|>
<commit_before>#include "plot.h" #include "curvedata.h" #include "signaldata.h" #include <qwt_plot_grid.h> #include <qwt_plot_layout.h> #include <qwt_plot_canvas.h> #include <qwt_plot_marker.h> #include <qwt_plot_curve.h> #include <qwt_plot_directpainter.h> #include <qwt_curve_fitter.h> #include <qwt_painter.h> #include <qwt_scale_engine.h> #include <qwt_scale_draw.h> #include <qwt_plot_zoomer.h> #include <qwt_plot_panner.h> #include <qwt_plot_magnifier.h> #include <qwt_text.h> #include <qevent.h> #include <limits> #include <cassert> class MyScaleDraw : public QwtScaleDraw { virtual QwtText label(double value) const { return QString::number(value, 'f', 2); } }; class MyZoomer: public QwtPlotZoomer { public: MyZoomer(QwtPlotCanvas *canvas): QwtPlotZoomer(canvas) { setTrackerMode(AlwaysOn); } virtual QwtText trackerTextF(const QPointF &pos) const { QColor bg(Qt::white); bg.setAlpha(200); QwtText text = QwtPlotZoomer::trackerTextF(pos); text.setBackgroundBrush( QBrush( bg )); return text; } }; Plot::Plot(QWidget *parent): QwtPlot(parent), d_interval(0.0, 10.0), d_timerId(-1) { setAutoReplot(false); // The backing store is important, when working with widget // overlays ( f.e rubberbands for zooming ). // Here we don't have them and the internal // backing store of QWidget is good enough. canvas()->setPaintAttribute(QwtPlotCanvas::BackingStore, false); #if defined(Q_WS_X11) // Even if not recommended by TrollTech, Qt::WA_PaintOutsidePaintEvent // works on X11. This has a nice effect on the performance. canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, true); // Disabling the backing store of Qt improves the performance // for the direct painter even more, but the canvas becomes // a native window of the window system, receiving paint events // for resize and expose operations. Those might be expensive // when there are many points and the backing store of // the canvas is disabled. So in this application // we better don't both backing stores. if ( canvas()->testPaintAttribute( QwtPlotCanvas::BackingStore ) ) { canvas()->setAttribute(Qt::WA_PaintOnScreen, true); canvas()->setAttribute(Qt::WA_NoSystemBackground, true); } #endif initGradient(); plotLayout()->setAlignCanvasToScales(true); setAxisTitle(QwtPlot::xBottom, "Time [s]"); setAxisScale(QwtPlot::xBottom, d_interval.minValue(), d_interval.maxValue()); setAxisScale(QwtPlot::yLeft, -4.0, 4.0); setAxisScaleDraw(QwtPlot::xBottom, new MyScaleDraw); QwtPlotGrid *grid = new QwtPlotGrid(); grid->setPen(QPen(Qt::gray, 0.0, Qt::DotLine)); grid->enableX(false); grid->enableXMin(false); grid->enableY(true); grid->enableYMin(false); grid->attach(this); d_origin = new QwtPlotMarker(); d_origin->setLineStyle(QwtPlotMarker::HLine); d_origin->setValue(d_interval.minValue() + d_interval.width() / 2.0, 0.0); d_origin->setLinePen(QPen(Qt::gray, 0.0, Qt::DashLine)); d_origin->attach(this); QwtPlotZoomer* zoomer = new MyZoomer(canvas()); zoomer->setMousePattern(QwtEventPattern::QwtEventPattern::MouseSelect1, Qt::LeftButton, Qt::ShiftModifier); // zoomer->setMousePattern(QwtEventPattern::MouseSelect3, // Qt::RightButton); QwtPlotPanner *panner = new QwtPlotPanner(canvas()); //panner->setAxisEnabled(QwtPlot::yRight, false); panner->setMouseButton(Qt::LeftButton); // zoom in/out with the wheel QwtPlotMagnifier* magnifier = new QwtPlotMagnifier(canvas()); magnifier->setMouseButton(Qt::MiddleButton); const QColor c(Qt::darkBlue); zoomer->setRubberBandPen(c); zoomer->setTrackerPen(c); this->setMinimumHeight(200); } Plot::~Plot() { } void Plot::addSignal(SignalData* signalData, QColor color) { QwtPlotCurve* d_curve = new QwtPlotCurve(); d_curve->setStyle(QwtPlotCurve::Lines); d_curve->setPen(QPen(color)); #if 1 d_curve->setRenderHint(QwtPlotItem::RenderAntialiased, true); #endif #if 1 d_curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, false); #endif d_curve->setData(new CurveData(signalData)); d_curve->attach(this); mSignals[signalData] = d_curve; } void Plot::removeSignal(SignalData* signalData) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); curve->detach(); delete curve; mSignals.remove(signalData); } void Plot::setSignalVisible(SignalData* signalData, bool visible) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); if (visible) { curve->attach(this); } else { curve->detach(); } } void Plot::initGradient() { QPalette pal = canvas()->palette(); #if QT_VERSION >= 0x040400 QLinearGradient gradient( 0.0, 0.0, 1.0, 0.0 ); gradient.setCoordinateMode( QGradient::StretchToDeviceMode ); //gradient.setColorAt(0.0, QColor( 0, 49, 110 ) ); //gradient.setColorAt(1.0, QColor( 0, 87, 174 ) ); gradient.setColorAt(0.0, QColor( 255, 255, 255 ) ); gradient.setColorAt(1.0, QColor( 255, 255, 255 ) ); pal.setBrush(QPalette::Window, QBrush(gradient)); #else pal.setBrush(QPalette::Window, QBrush( color )); #endif canvas()->setPalette(pal); } void Plot::start() { d_timerId = startTimer(33); } void Plot::stop() { killTimer(d_timerId); } void Plot::replot() { // Lock the signal data objects, then plot the data and unlock. QList<SignalData*> signalDataList = mSignals.keys(); foreach (SignalData* signalData, signalDataList) { signalData->lock(); } QwtPlot::replot(); foreach (SignalData* signalData, signalDataList) { signalData->unlock(); } } double Plot::timeWindow() { return d_interval.width(); } void Plot::setTimeWindow(double interval) { if ( interval > 0.0 && interval != d_interval.width() ) { d_interval.setMinValue(d_interval.maxValue() - interval); } } void Plot::setYScale(double scale) { setAxisScale(QwtPlot::yLeft, -scale, scale); } void Plot::timerEvent(QTimerEvent *event) { if ( event->timerId() == d_timerId ) { if (!mSignals.size()) { return; } float maxTime = std::numeric_limits<float>::min(); QList<SignalData*> signalDataList = mSignals.keys(); foreach (SignalData* signalData, signalDataList) { signalData->updateValues(); if (signalData->size()) { float signalMaxTime = signalData->value(signalData->size() - 1).x(); if (signalMaxTime > maxTime) { maxTime = signalMaxTime; } } } if (maxTime != std::numeric_limits<float>::min()) { d_interval = QwtInterval(maxTime - d_interval.width(), maxTime); setAxisScale(QwtPlot::xBottom, d_interval.minValue(), d_interval.maxValue()); QwtScaleEngine* engine = axisScaleEngine(QwtPlot::xBottom); //engine->setAttribute(QwtScaleEngine::Floating, true); //engine->setMargins(0,50.0); QwtScaleDiv scaleDiv = engine->divideScale(d_interval.minValue(), d_interval.maxValue(), 0, 0); QList<double> majorTicks; double majorStep = scaleDiv.range() / 5.0; for (int i = 0; i <= 5; ++i) { majorTicks << scaleDiv.lowerBound() + i*majorStep; } majorTicks.back() = scaleDiv.upperBound(); QList<double> minorTicks; double minorStep = scaleDiv.range() / 25.0; for (int i = 0; i <= 25; ++i) { minorTicks << scaleDiv.lowerBound() + i*minorStep; } minorTicks.back() = scaleDiv.upperBound(); scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks); scaleDiv.setTicks(QwtScaleDiv::MinorTick, minorTicks); setAxisScaleDiv(QwtPlot::xBottom, scaleDiv); /* QwtScaleDiv scaleDiv;// = *axisScaleDiv(QwtPlot::xBottom); scaleDiv.setInterval(d_interval); QList<double> majorTicks; majorTicks << d_interval.minValue() << d_interval.maxValue(); scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks); setAxisScaleDiv(QwtPlot::xBottom, scaleDiv); */ //printf("update x axis interval: [%f, %f]\n", d_interval.minValue(), d_interval.maxValue()); } this->replot(); } QwtPlot::timerEvent(event); } <commit_msg>signal_scope: invert the direction of mouse wheel zoom<commit_after>#include "plot.h" #include "curvedata.h" #include "signaldata.h" #include <qwt_plot_grid.h> #include <qwt_plot_layout.h> #include <qwt_plot_canvas.h> #include <qwt_plot_marker.h> #include <qwt_plot_curve.h> #include <qwt_plot_directpainter.h> #include <qwt_curve_fitter.h> #include <qwt_painter.h> #include <qwt_scale_engine.h> #include <qwt_scale_draw.h> #include <qwt_plot_zoomer.h> #include <qwt_plot_panner.h> #include <qwt_plot_magnifier.h> #include <qwt_text.h> #include <qevent.h> #include <limits> #include <cassert> class MyScaleDraw : public QwtScaleDraw { virtual QwtText label(double value) const { return QString::number(value, 'f', 2); } }; class MyZoomer: public QwtPlotZoomer { public: MyZoomer(QwtPlotCanvas *canvas): QwtPlotZoomer(canvas) { setTrackerMode(AlwaysOn); } virtual QwtText trackerTextF(const QPointF &pos) const { QColor bg(Qt::white); bg.setAlpha(200); QwtText text = QwtPlotZoomer::trackerTextF(pos); text.setBackgroundBrush( QBrush( bg )); return text; } }; class MyMagnifier: public QwtPlotMagnifier { public: MyMagnifier(QwtPlotCanvas *canvas): QwtPlotMagnifier(canvas) { } protected: // Normally, a value < 1.0 zooms in, a value > 1.0 zooms out. // This function is overloaded to invert the magnification direction. virtual void rescale( double factor ) { factor = qAbs( factor ); factor = (1-factor) + 1; this->QwtPlotMagnifier::rescale(factor); } }; Plot::Plot(QWidget *parent): QwtPlot(parent), d_interval(0.0, 10.0), d_timerId(-1) { setAutoReplot(false); // The backing store is important, when working with widget // overlays ( f.e rubberbands for zooming ). // Here we don't have them and the internal // backing store of QWidget is good enough. canvas()->setPaintAttribute(QwtPlotCanvas::BackingStore, false); #if defined(Q_WS_X11) // Even if not recommended by TrollTech, Qt::WA_PaintOutsidePaintEvent // works on X11. This has a nice effect on the performance. canvas()->setAttribute(Qt::WA_PaintOutsidePaintEvent, true); // Disabling the backing store of Qt improves the performance // for the direct painter even more, but the canvas becomes // a native window of the window system, receiving paint events // for resize and expose operations. Those might be expensive // when there are many points and the backing store of // the canvas is disabled. So in this application // we better don't both backing stores. if ( canvas()->testPaintAttribute( QwtPlotCanvas::BackingStore ) ) { canvas()->setAttribute(Qt::WA_PaintOnScreen, true); canvas()->setAttribute(Qt::WA_NoSystemBackground, true); } #endif initGradient(); plotLayout()->setAlignCanvasToScales(true); setAxisTitle(QwtPlot::xBottom, "Time [s]"); setAxisScale(QwtPlot::xBottom, d_interval.minValue(), d_interval.maxValue()); setAxisScale(QwtPlot::yLeft, -4.0, 4.0); setAxisScaleDraw(QwtPlot::xBottom, new MyScaleDraw); QwtPlotGrid *grid = new QwtPlotGrid(); grid->setPen(QPen(Qt::gray, 0.0, Qt::DotLine)); grid->enableX(false); grid->enableXMin(false); grid->enableY(true); grid->enableYMin(false); grid->attach(this); d_origin = new QwtPlotMarker(); d_origin->setLineStyle(QwtPlotMarker::HLine); d_origin->setValue(d_interval.minValue() + d_interval.width() / 2.0, 0.0); d_origin->setLinePen(QPen(Qt::gray, 0.0, Qt::DashLine)); d_origin->attach(this); QwtPlotZoomer* zoomer = new MyZoomer(canvas()); zoomer->setMousePattern(QwtEventPattern::QwtEventPattern::MouseSelect1, Qt::LeftButton, Qt::ShiftModifier); // zoomer->setMousePattern(QwtEventPattern::MouseSelect3, // Qt::RightButton); QwtPlotPanner *panner = new QwtPlotPanner(canvas()); //panner->setAxisEnabled(QwtPlot::yRight, false); panner->setMouseButton(Qt::LeftButton); // zoom in/out with the wheel QwtPlotMagnifier* magnifier = new MyMagnifier(canvas()); magnifier->setMouseButton(Qt::MiddleButton); const QColor c(Qt::darkBlue); zoomer->setRubberBandPen(c); zoomer->setTrackerPen(c); this->setMinimumHeight(200); } Plot::~Plot() { } void Plot::addSignal(SignalData* signalData, QColor color) { QwtPlotCurve* d_curve = new QwtPlotCurve(); d_curve->setStyle(QwtPlotCurve::Lines); d_curve->setPen(QPen(color)); #if 1 d_curve->setRenderHint(QwtPlotItem::RenderAntialiased, true); #endif #if 1 d_curve->setPaintAttribute(QwtPlotCurve::ClipPolygons, false); #endif d_curve->setData(new CurveData(signalData)); d_curve->attach(this); mSignals[signalData] = d_curve; } void Plot::removeSignal(SignalData* signalData) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); curve->detach(); delete curve; mSignals.remove(signalData); } void Plot::setSignalVisible(SignalData* signalData, bool visible) { if (!signalData) { return; } QwtPlotCurve* curve = mSignals.value(signalData); assert(curve); if (visible) { curve->attach(this); } else { curve->detach(); } } void Plot::initGradient() { QPalette pal = canvas()->palette(); #if QT_VERSION >= 0x040400 QLinearGradient gradient( 0.0, 0.0, 1.0, 0.0 ); gradient.setCoordinateMode( QGradient::StretchToDeviceMode ); //gradient.setColorAt(0.0, QColor( 0, 49, 110 ) ); //gradient.setColorAt(1.0, QColor( 0, 87, 174 ) ); gradient.setColorAt(0.0, QColor( 255, 255, 255 ) ); gradient.setColorAt(1.0, QColor( 255, 255, 255 ) ); pal.setBrush(QPalette::Window, QBrush(gradient)); #else pal.setBrush(QPalette::Window, QBrush( color )); #endif canvas()->setPalette(pal); } void Plot::start() { d_timerId = startTimer(33); } void Plot::stop() { killTimer(d_timerId); } void Plot::replot() { // Lock the signal data objects, then plot the data and unlock. QList<SignalData*> signalDataList = mSignals.keys(); foreach (SignalData* signalData, signalDataList) { signalData->lock(); } QwtPlot::replot(); foreach (SignalData* signalData, signalDataList) { signalData->unlock(); } } double Plot::timeWindow() { return d_interval.width(); } void Plot::setTimeWindow(double interval) { if ( interval > 0.0 && interval != d_interval.width() ) { d_interval.setMinValue(d_interval.maxValue() - interval); } } void Plot::setYScale(double scale) { setAxisScale(QwtPlot::yLeft, -scale, scale); } void Plot::timerEvent(QTimerEvent *event) { if ( event->timerId() == d_timerId ) { if (!mSignals.size()) { return; } float maxTime = std::numeric_limits<float>::min(); QList<SignalData*> signalDataList = mSignals.keys(); foreach (SignalData* signalData, signalDataList) { signalData->updateValues(); if (signalData->size()) { float signalMaxTime = signalData->value(signalData->size() - 1).x(); if (signalMaxTime > maxTime) { maxTime = signalMaxTime; } } } if (maxTime != std::numeric_limits<float>::min()) { d_interval = QwtInterval(maxTime - d_interval.width(), maxTime); setAxisScale(QwtPlot::xBottom, d_interval.minValue(), d_interval.maxValue()); QwtScaleEngine* engine = axisScaleEngine(QwtPlot::xBottom); //engine->setAttribute(QwtScaleEngine::Floating, true); //engine->setMargins(0,50.0); QwtScaleDiv scaleDiv = engine->divideScale(d_interval.minValue(), d_interval.maxValue(), 0, 0); QList<double> majorTicks; double majorStep = scaleDiv.range() / 5.0; for (int i = 0; i <= 5; ++i) { majorTicks << scaleDiv.lowerBound() + i*majorStep; } majorTicks.back() = scaleDiv.upperBound(); QList<double> minorTicks; double minorStep = scaleDiv.range() / 25.0; for (int i = 0; i <= 25; ++i) { minorTicks << scaleDiv.lowerBound() + i*minorStep; } minorTicks.back() = scaleDiv.upperBound(); scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks); scaleDiv.setTicks(QwtScaleDiv::MinorTick, minorTicks); setAxisScaleDiv(QwtPlot::xBottom, scaleDiv); /* QwtScaleDiv scaleDiv;// = *axisScaleDiv(QwtPlot::xBottom); scaleDiv.setInterval(d_interval); QList<double> majorTicks; majorTicks << d_interval.minValue() << d_interval.maxValue(); scaleDiv.setTicks(QwtScaleDiv::MajorTick, majorTicks); setAxisScaleDiv(QwtPlot::xBottom, scaleDiv); */ //printf("update x axis interval: [%f, %f]\n", d_interval.minValue(), d_interval.maxValue()); } this->replot(); } QwtPlot::timerEvent(event); } <|endoftext|>
<commit_before>/* * (C) 2010,2014,2015 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "cli.h" #if defined(BOTAN_HAS_X509_CERTIFICATES) #include <botan/certstor.h> #include <botan/pkcs8.h> #include <botan/x509_ca.h> #include <botan/x509cert.h> #include <botan/x509path.h> #include <botan/x509self.h> #if defined(BOTAN_HAS_OCSP) #include <botan/ocsp.h> #endif namespace Botan_CLI { class Sign_Cert final : public Command { public: Sign_Cert() : Command("sign_cert --ca-key-pass= --hash=SHA-256 " "--duration=365 ca_cert ca_key pkcs10_req") {} void go() override { Botan::X509_Certificate ca_cert(get_arg("ca_cert")); std::unique_ptr<Botan::PKCS8_PrivateKey> key; if(flag_set("ca_key_pass")) { key.reset(Botan::PKCS8::load_key(get_arg("ca_key"), rng(), get_arg("ca_key_pass"))); } else { key.reset(Botan::PKCS8::load_key(get_arg("ca_key"), rng())); } if(!key) throw CLI_Error("Failed to load key from " + get_arg("ca_key")); Botan::X509_CA ca(ca_cert, *key, get_arg("hash"), rng()); Botan::PKCS10_Request req(get_arg("pkcs10_req")); auto now = std::chrono::system_clock::now(); Botan::X509_Time start_time(now); typedef std::chrono::duration<int, std::ratio<86400>> days; Botan::X509_Time end_time(now + days(get_arg_sz("duration"))); Botan::X509_Certificate new_cert = ca.sign_request(req, rng(), start_time, end_time); output() << new_cert.PEM_encode(); } }; BOTAN_REGISTER_COMMAND("sign_cert", Sign_Cert); class Cert_Info final : public Command { public: Cert_Info() : Command("cert_info --ber file") {} void go() override { Botan::DataSource_Stream in(get_arg("file"), flag_set("ber")); while(!in.end_of_data()) { try { Botan::X509_Certificate cert(in); try { output() << cert.to_string() << std::endl; } catch(Botan::Exception& e) { // to_string failed - report the exception and continue output() << "X509_Certificate::to_string failed: " << e.what() << "\n"; } } catch(Botan::Exception& e) { if(!in.end_of_data()) output() << "X509_Certificate parsing failed " << e.what() << "\n"; } } } }; BOTAN_REGISTER_COMMAND("cert_info", Cert_Info); #if defined(BOTAN_HAS_OCSP) && defined(BOTAN_HAS_HTTP_UTIL) class OCSP_Check final : public Command { public: OCSP_Check() : Command("ocsp_check subject issuer") {} void go() override { Botan::X509_Certificate subject(get_arg("subject")); Botan::X509_Certificate issuer(get_arg("issuer")); Botan::Certificate_Store_In_Memory cas; cas.add_certificate(issuer); Botan::OCSP::Response resp = Botan::OCSP::online_check(issuer, subject, &cas); auto status = resp.status_for(issuer, subject, std::chrono::system_clock::now()); if(status == Botan::Certificate_Status_Code::VERIFIED) { output() << "OCSP check OK\n"; } else { output() << "OCSP check failed " << Botan::Path_Validation_Result::status_string(status) << "\n"; } } }; BOTAN_REGISTER_COMMAND("ocsp_check", OCSP_Check); #endif // OCSP && HTTP class Cert_Verify final : public Command { public: Cert_Verify() : Command("cert_verify subject *ca_certs") {} void go() override { Botan::X509_Certificate subject_cert(get_arg("subject")); Botan::Certificate_Store_In_Memory trusted; for(auto&& certfile : get_arg_list("ca_certs")) { trusted.add_certificate(Botan::X509_Certificate(certfile)); } Botan::Path_Validation_Restrictions restrictions; Botan::Path_Validation_Result result = Botan::x509_path_validate(subject_cert, restrictions, trusted); if(result.successful_validation()) { output() << "Certificate passes validation checks\n"; } else { output() << "Certificate did not validate - " << result.result_string() << "\n"; } } }; BOTAN_REGISTER_COMMAND("cert_verify", Cert_Verify); class Gen_Self_Signed final : public Command { public: Gen_Self_Signed() : Command("gen_self_signed key CN --country= --dns= " "--organization= --email= --key-pass= --ca --hash=SHA-256") {} void go() override { std::unique_ptr<Botan::Private_Key> key( Botan::PKCS8::load_key(get_arg("key"), rng(), get_arg("key-pass"))); if(!key) throw CLI_Error("Failed to load key from " + get_arg("key")); Botan::X509_Cert_Options opts; opts.common_name = get_arg("CN"); opts.country = get_arg("country"); opts.organization = get_arg("organization"); opts.email = get_arg("email"); opts.dns = get_arg("dns"); if(flag_set("ca")) opts.CA_key(); Botan::X509_Certificate cert = Botan::X509::create_self_signed_cert(opts, *key, get_arg("hash"), rng()); output() << cert.PEM_encode(); } }; BOTAN_REGISTER_COMMAND("gen_self_signed", Gen_Self_Signed); class Generate_PKCS10 final : public Command { public: Generate_PKCS10() : Command("gen_pkcs10 key CN --country= --organization= " "--email= --key-pass= --hash=SHA-256") {} void go() override { std::unique_ptr<Botan::Private_Key> key( Botan::PKCS8::load_key(get_arg("key"), rng(), get_arg("key-pass"))); if(!key) throw CLI_Error("Failed to load key from " + get_arg("key")); Botan::X509_Cert_Options opts; opts.common_name = get_arg("CN"); opts.country = get_arg("country"); opts.organization = get_arg("organization"); opts.email = get_arg("email"); Botan::PKCS10_Request req = Botan::X509::create_cert_req(opts, *key, get_arg("hash"), rng()); output() << req.PEM_encode(); } }; BOTAN_REGISTER_COMMAND("gen_pkcs10", Generate_PKCS10); } #endif <commit_msg>CLI OCSP: fix expected OK return code<commit_after>/* * (C) 2010,2014,2015 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include "cli.h" #if defined(BOTAN_HAS_X509_CERTIFICATES) #include <botan/certstor.h> #include <botan/pkcs8.h> #include <botan/x509_ca.h> #include <botan/x509cert.h> #include <botan/x509path.h> #include <botan/x509self.h> #if defined(BOTAN_HAS_OCSP) #include <botan/ocsp.h> #endif namespace Botan_CLI { class Sign_Cert final : public Command { public: Sign_Cert() : Command("sign_cert --ca-key-pass= --hash=SHA-256 " "--duration=365 ca_cert ca_key pkcs10_req") {} void go() override { Botan::X509_Certificate ca_cert(get_arg("ca_cert")); std::unique_ptr<Botan::PKCS8_PrivateKey> key; if(flag_set("ca_key_pass")) { key.reset(Botan::PKCS8::load_key(get_arg("ca_key"), rng(), get_arg("ca_key_pass"))); } else { key.reset(Botan::PKCS8::load_key(get_arg("ca_key"), rng())); } if(!key) throw CLI_Error("Failed to load key from " + get_arg("ca_key")); Botan::X509_CA ca(ca_cert, *key, get_arg("hash"), rng()); Botan::PKCS10_Request req(get_arg("pkcs10_req")); auto now = std::chrono::system_clock::now(); Botan::X509_Time start_time(now); typedef std::chrono::duration<int, std::ratio<86400>> days; Botan::X509_Time end_time(now + days(get_arg_sz("duration"))); Botan::X509_Certificate new_cert = ca.sign_request(req, rng(), start_time, end_time); output() << new_cert.PEM_encode(); } }; BOTAN_REGISTER_COMMAND("sign_cert", Sign_Cert); class Cert_Info final : public Command { public: Cert_Info() : Command("cert_info --ber file") {} void go() override { Botan::DataSource_Stream in(get_arg("file"), flag_set("ber")); while(!in.end_of_data()) { try { Botan::X509_Certificate cert(in); try { output() << cert.to_string() << std::endl; } catch(Botan::Exception& e) { // to_string failed - report the exception and continue output() << "X509_Certificate::to_string failed: " << e.what() << "\n"; } } catch(Botan::Exception& e) { if(!in.end_of_data()) output() << "X509_Certificate parsing failed " << e.what() << "\n"; } } } }; BOTAN_REGISTER_COMMAND("cert_info", Cert_Info); #if defined(BOTAN_HAS_OCSP) && defined(BOTAN_HAS_HTTP_UTIL) class OCSP_Check final : public Command { public: OCSP_Check() : Command("ocsp_check subject issuer") {} void go() override { Botan::X509_Certificate subject(get_arg("subject")); Botan::X509_Certificate issuer(get_arg("issuer")); Botan::Certificate_Store_In_Memory cas; cas.add_certificate(issuer); Botan::OCSP::Response resp = Botan::OCSP::online_check(issuer, subject, &cas); auto status = resp.status_for(issuer, subject, std::chrono::system_clock::now()); if(status == Botan::Certificate_Status_Code::OCSP_RESPONSE_GOOD) { output() << "OCSP check OK\n"; } else { output() << "OCSP check failed " << Botan::Path_Validation_Result::status_string(status) << "\n"; } } }; BOTAN_REGISTER_COMMAND("ocsp_check", OCSP_Check); #endif // OCSP && HTTP class Cert_Verify final : public Command { public: Cert_Verify() : Command("cert_verify subject *ca_certs") {} void go() override { Botan::X509_Certificate subject_cert(get_arg("subject")); Botan::Certificate_Store_In_Memory trusted; for(auto&& certfile : get_arg_list("ca_certs")) { trusted.add_certificate(Botan::X509_Certificate(certfile)); } Botan::Path_Validation_Restrictions restrictions; Botan::Path_Validation_Result result = Botan::x509_path_validate(subject_cert, restrictions, trusted); if(result.successful_validation()) { output() << "Certificate passes validation checks\n"; } else { output() << "Certificate did not validate - " << result.result_string() << "\n"; } } }; BOTAN_REGISTER_COMMAND("cert_verify", Cert_Verify); class Gen_Self_Signed final : public Command { public: Gen_Self_Signed() : Command("gen_self_signed key CN --country= --dns= " "--organization= --email= --key-pass= --ca --hash=SHA-256") {} void go() override { std::unique_ptr<Botan::Private_Key> key( Botan::PKCS8::load_key(get_arg("key"), rng(), get_arg("key-pass"))); if(!key) throw CLI_Error("Failed to load key from " + get_arg("key")); Botan::X509_Cert_Options opts; opts.common_name = get_arg("CN"); opts.country = get_arg("country"); opts.organization = get_arg("organization"); opts.email = get_arg("email"); opts.dns = get_arg("dns"); if(flag_set("ca")) opts.CA_key(); Botan::X509_Certificate cert = Botan::X509::create_self_signed_cert(opts, *key, get_arg("hash"), rng()); output() << cert.PEM_encode(); } }; BOTAN_REGISTER_COMMAND("gen_self_signed", Gen_Self_Signed); class Generate_PKCS10 final : public Command { public: Generate_PKCS10() : Command("gen_pkcs10 key CN --country= --organization= " "--email= --key-pass= --hash=SHA-256") {} void go() override { std::unique_ptr<Botan::Private_Key> key( Botan::PKCS8::load_key(get_arg("key"), rng(), get_arg("key-pass"))); if(!key) throw CLI_Error("Failed to load key from " + get_arg("key")); Botan::X509_Cert_Options opts; opts.common_name = get_arg("CN"); opts.country = get_arg("country"); opts.organization = get_arg("organization"); opts.email = get_arg("email"); Botan::PKCS10_Request req = Botan::X509::create_cert_req(opts, *key, get_arg("hash"), rng()); output() << req.PEM_encode(); } }; BOTAN_REGISTER_COMMAND("gen_pkcs10", Generate_PKCS10); } #endif <|endoftext|>
<commit_before> #include <togo/core/error/assert.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/log/log.hpp> #include <togo/core/collection/array.hpp> #include <togo/core/string/string.hpp> #include <togo/core/io/memory_stream.hpp> #include <quanta/core/object/object.hpp> #include <togo/support/test.hpp> #include <cmath> using namespace quanta; #define TSN(d) {true, d, {}}, #define TSE(d, e) {true, d, e}, #define TSS(d) {true, d, d}, #define TF(d) {false, d, {}}, struct Test { bool success; StringRef data; StringRef expected_output; } const tests[]{ // whitespace TSN("") TSN(" ") TSN("\n") TSN(" \t\n") // comments TF("\\") TF("\\*") TSN("\\\\") TSN("\\**\\") TSN("\\*\nblah\n*\\") // nested TF("\\* \\* *\\") TSN("\\* \\**\\ *\\") // constants TSE("null", "null") TSE("false", "false") TSE("true", "true") // identifiers TSE("a", "a") TSE("á", "á") TSE(".á", ".á") TSE("_", "_") TSE("a\nb", "a\nb") // markers TSE("~", "~") TSE("~x", "~x") TSE("~~x", "~~x") TSE("~~~x", "~~~x") TSE("^", "^") TSE("^x", "^x") TSE("^^x", "^^x") TSE("^^^x", "^^^x") TSE("G~~x", "G~~x") TSE(" G~x", "G~x") TSE("G~^x", "G~^x") TSE("?", "?") TSE("?~x", "?~x") TSE(" ?x", "?x") TSE("?^x", "?^x") // source TSE("x$0", "x") TSE("x$0$0", "x") TSE("x$0$1", "x") TSE("x$0$?", "x") TSE("x$1", "x$1") TSE("x$1$0", "x$1") TSE("x$1$?", "x$1$?") TSE("x$1$2", "x$1$2") TSE("x$?1", "x$?1") TSE("x$?1$0", "x$?1") TSE("x$?1$?", "x$?1$?") TSE("x$?1$2", "x$?1$2") TSE("x$?$?", "x$?$?") // integer & decimal TSE(" 1", "1") TSE("+1", "1") TSE("-1", "-1") TSE("+.1", "0.1") TSE("-.1", "-0.1") TSE(" 1.1", "1.1") TSE("+1.1", "1.1") TSE("-1.1", "-1.1") TSE(" 1.1e1", "11") TSE("+1.1e1", "11") TSE("-1.1e1", "-11") TSE(" 1.1e+1", "11") TSE("+1.1e+1", "11") TSE("-1.1e+1", "-11") TSE(" 1.1e-1", "0.11") TSE("+1.1e-1", "0.11") TSE("-1.1e-1", "-0.11") // units TSE("1a", "1a") TSE("1µg", "1µg") // times TF("2-") TF("201-") TF("2015-") TF("2015-01") TF("2015-01-") TF("2015-01-02-") TSS("2015-01-02") TSE("2015-01-02T", "2015-01-02") TSS("01-02") TSE("01-02T", "01-02") TSS("02T") TF("01:0") TF("01:02:") TF("01:02:0") TF("01:02:03:") TF("01:02:03:00") TSE("01:02", "01:02:00") TSS("01:02:03") TF("01T02") TSS("2015-01-02T03:04:05") TSE("2015-01-02T03:04", "2015-01-02T03:04:00") TSS("01-02T03:04:05") TSE("01-02T03:04", "01-02T03:04:00") TSS("02T03:04:05") TSE("02T03:04", "02T03:04:00") // strings TSE("\"\"", "\"\"") TSE("\"a\"", "a") TSE("``````", "\"\"") TSE("```a```", "a") TSE("\"\\t\"", "\"\t\"") TSE("\"\\n\"", "```\n```") // names TF("=") TF("a=") TF("=,") TF("=;") TF("=\n") TSE("a=1", "a = 1") TSE("a=b", "a = b") TSE("a = 1", "a = 1") TSE("a = b", "a = b") TSE("a=\"\"", "a = \"\"") TSE("a=\"ab\"", "a = ab") TSE("a=\"a b\"", "a = \"a b\"") TF("a=\"\n") TSE("a=```ab```", "a = ab") TSE("a=```a b```", "a = \"a b\"") TSE("a=```a\nb```", "a = ```a\nb```") // tags TF(":") TF("::") TF(":,") TF(":;") TF(":\n") TF(":\"a\"") TF(":```a```") TF(":1") TSE(":x", ":x") TF(":x:") TF(":x=") TF("x=:") TSE("x:y", "x:y") TSE(":x:y", ":x:y") TSE(":?x", ":?x") TSE(":G~x", ":G~x") TSE(":~x", ":~x") TSE(":~~x", ":~~x") TSE(":~~~x", ":~~~x") TSE(":^x", ":^x") TSE(":^^x", ":^^x") TSE(":^^^x", ":^^^x") TSE(":?~x", ":?~x") TSE(":?~~x", ":?~~x") TSE(":?~~~x", ":?~~~x") TSE(":?^x", ":?^x") TSE(":?^^x", ":?^^x") TSE(":?^^^x", ":?^^^x") TSE(":G~~x", ":G~~x") TSE(":G~~~x", ":G~~~x") TSE(":G~~~~x", ":G~~~~x") TSE(":G~^x", ":G~^x") TSE(":G~^^x", ":G~^^x") TSE(":G~^^^x", ":G~^^^x") TF(":x(") TSE(":x()", ":x") TSE(":x( )", ":x") TSE(":x(\t)", ":x") TSE(":x(\n)", ":x") TSE(":x(1)", ":x(1)") TSE(":x(y)", ":x(y)") TSE(":x(y,z)", ":x(y, z)") TSE(":x(y;z)", ":x(y, z)") TSE(":x(y\nz)", ":x(y, z)") // scopes TF("{") TF("(") TF("[") TF("x[+") TF("x[,") TF("x[;") TF("x[\n") TSE("{}", "null") TSE("{{}}", "{\n\tnull\n}") TSE("x{}", "x") TSE("x[]", "x") TSE("x[1]", "x[1]") TSE("x[y]", "x[y]") TSE("x[y:a(1){2}, b]", "x[y:a(1){\n\t2\n}, b]") // expressions TF("x + ") TF("x - ,") TF("x * ;") TF("{x / }") TSE("x + y", "x + y") TSE("a[x - y]", "a[x - y]") TSE("a[x - y, 1 * 2, z]", "a[x - y, 1 * 2, z]") TSE(":a(x * y)", ":a(x * y)") TSE("{x / y}", "{\n\tx / y\n}") TSE("x + y - z", "x + y - z") TSS("x\nz + w") TSE("x + y, z / w", "x + y\nz / w") }; void check(Test const& test) { TOGO_LOGF( "reading (%3u): <%.*s>\n", test.data.size, test.data.size, test.data.data ); Object root; MemoryReader in_stream{test.data}; ObjectParserInfo pinfo; if (object::read_text(root, in_stream, pinfo)) { MemoryStream out_stream{memory::default_allocator(), test.expected_output.size + 1}; TOGO_ASSERTE(object::write_text(root, out_stream)); StringRef output{ reinterpret_cast<char*>(array::begin(out_stream.data())), static_cast<unsigned>(out_stream.size()) }; // Remove trailing newline if (output.size > 0) { --output.size; } TOGO_LOGF( "rewritten (%3u): <%.*s>\n", output.size, output.size, output.data ); TOGO_ASSERT(test.success, "read succeeded when it should have failed"); TOGO_ASSERT( string::compare_equal(test.expected_output, output), "output does not match" ); } else { TOGO_LOGF( "failed to read%s: [%2u,%2u]: %s\n", test.success ? " (UNEXPECTED)" : "", pinfo.line, pinfo.column, pinfo.message ); TOGO_ASSERT(!test.success, "read failed when it should have succeeded"); } TOGO_LOG("\n"); } signed main() { memory_init(); for (auto& test : tests) { check(test); } return 0; } <commit_msg>lib/core/test/object/io_text: added named & signed value tests.<commit_after> #include <togo/core/error/assert.hpp> #include <togo/core/utility/utility.hpp> #include <togo/core/log/log.hpp> #include <togo/core/collection/array.hpp> #include <togo/core/string/string.hpp> #include <togo/core/io/memory_stream.hpp> #include <quanta/core/object/object.hpp> #include <togo/support/test.hpp> #include <cmath> using namespace quanta; #define TSN(d) {true, d, {}}, #define TSE(d, e) {true, d, e}, #define TSS(d) {true, d, d}, #define TF(d) {false, d, {}}, struct Test { bool success; StringRef data; StringRef expected_output; } const tests[]{ // whitespace TSN("") TSN(" ") TSN("\n") TSN(" \t\n") // comments TF("\\") TF("\\*") TSN("\\\\") TSN("\\**\\") TSN("\\*\nblah\n*\\") // nested TF("\\* \\* *\\") TSN("\\* \\**\\ *\\") // constants TSE("null", "null") TSE("false", "false") TSE("true", "true") // identifiers TSE("a", "a") TSE("á", "á") TSE(".á", ".á") TSE("_", "_") TSE("a\nb", "a\nb") // markers TSE("~", "~") TSE("~x", "~x") TSE("~~x", "~~x") TSE("~~~x", "~~~x") TSE("^", "^") TSE("^x", "^x") TSE("^^x", "^^x") TSE("^^^x", "^^^x") TSE("G~~x", "G~~x") TSE(" G~x", "G~x") TSE("G~^x", "G~^x") TSE("?", "?") TSE("?~x", "?~x") TSE(" ?x", "?x") TSE("?^x", "?^x") // source TSE("x$0", "x") TSE("x$0$0", "x") TSE("x$0$1", "x") TSE("x$0$?", "x") TSE("x$1", "x$1") TSE("x$1$0", "x$1") TSE("x$1$?", "x$1$?") TSE("x$1$2", "x$1$2") TSE("x$?1", "x$?1") TSE("x$?1$0", "x$?1") TSE("x$?1$?", "x$?1$?") TSE("x$?1$2", "x$?1$2") TSE("x$?$?", "x$?$?") // integer & decimal TSE(" 1", "1") TSE("+1", "1") TSE("-1", "-1") TSE("+.1", "0.1") TSE("-.1", "-0.1") TSE(" 1.1", "1.1") TSE("+1.1", "1.1") TSE("-1.1", "-1.1") TSE(" 1.1e1", "11") TSE("+1.1e1", "11") TSE("-1.1e1", "-11") TSE(" 1.1e+1", "11") TSE("+1.1e+1", "11") TSE("-1.1e+1", "-11") TSE(" 1.1e-1", "0.11") TSE("+1.1e-1", "0.11") TSE("-1.1e-1", "-0.11") // units TSE("1a", "1a") TSE("1µg", "1µg") // times TF("2-") TF("201-") TF("2015-") TF("2015-01") TF("2015-01-") TF("2015-01-02-") TSS("2015-01-02") TSE("2015-01-02T", "2015-01-02") TSS("01-02") TSE("01-02T", "01-02") TSS("02T") TF("01:0") TF("01:02:") TF("01:02:0") TF("01:02:03:") TF("01:02:03:00") TSE("01:02", "01:02:00") TSS("01:02:03") TF("01T02") TSS("2015-01-02T03:04:05") TSE("2015-01-02T03:04", "2015-01-02T03:04:00") TSS("01-02T03:04:05") TSE("01-02T03:04", "01-02T03:04:00") TSS("02T03:04:05") TSE("02T03:04", "02T03:04:00") // strings TSE("\"\"", "\"\"") TSE("\"a\"", "a") TSE("``````", "\"\"") TSE("```a```", "a") TSE("\"\\t\"", "\"\t\"") TSE("\"\\n\"", "```\n```") // names TF("=") TF("a=") TF("=,") TF("=;") TF("=\n") TSE("a=1", "a = 1") TSE("a=b", "a = b") TSE("a = 1", "a = 1") TSE("a = b", "a = b") TSE("a = +1", "a = 1") TSS("a = -1") TSE("a=\"\"", "a = \"\"") TSE("a=\"ab\"", "a = ab") TSE("a=\"a b\"", "a = \"a b\"") TF("a=\"\n") TSE("a=```ab```", "a = ab") TSE("a=```a b```", "a = \"a b\"") TSE("a=```a\nb```", "a = ```a\nb```") // tags TF(":") TF("::") TF(":,") TF(":;") TF(":\n") TF(":\"a\"") TF(":```a```") TF(":1") TSE(":x", ":x") TF(":x:") TF(":x=") TF("x=:") TSE("x:y", "x:y") TSE(":x:y", ":x:y") TSE(":?x", ":?x") TSE(":G~x", ":G~x") TSE(":~x", ":~x") TSE(":~~x", ":~~x") TSE(":~~~x", ":~~~x") TSE(":^x", ":^x") TSE(":^^x", ":^^x") TSE(":^^^x", ":^^^x") TSE(":?~x", ":?~x") TSE(":?~~x", ":?~~x") TSE(":?~~~x", ":?~~~x") TSE(":?^x", ":?^x") TSE(":?^^x", ":?^^x") TSE(":?^^^x", ":?^^^x") TSE(":G~~x", ":G~~x") TSE(":G~~~x", ":G~~~x") TSE(":G~~~~x", ":G~~~~x") TSE(":G~^x", ":G~^x") TSE(":G~^^x", ":G~^^x") TSE(":G~^^^x", ":G~^^^x") TF(":x(") TSE(":x()", ":x") TSE(":x( )", ":x") TSE(":x(\t)", ":x") TSE(":x(\n)", ":x") TSE(":x(1)", ":x(1)") TSE(":x(y)", ":x(y)") TSE(":x(y,z)", ":x(y, z)") TSE(":x(y;z)", ":x(y, z)") TSE(":x(y\nz)", ":x(y, z)") // scopes TF("{") TF("(") TF("[") TF("x[+") TF("x[,") TF("x[;") TF("x[\n") TSE("{}", "null") TSE("{{}}", "{\n\tnull\n}") TSE("x{}", "x") TSE("x[]", "x") TSE("x[1]", "x[1]") TSE("x[y]", "x[y]") TSE("x[y:a(1){2}, b]", "x[y:a(1){\n\t2\n}, b]") // expressions TF("x + ") TF("x - ,") TF("x * ;") TF("{x / }") TSE("x + y", "x + y") TSE("a[x - y]", "a[x - y]") TSE("a[x - y, 1 * 2, z]", "a[x - y, 1 * 2, z]") TSE(":a(x * y)", ":a(x * y)") TSE("{x / y}", "{\n\tx / y\n}") TSE("x + y - z", "x + y - z") TSS("x\nz + w") TSE("x + y, z / w", "x + y\nz / w") }; void check(Test const& test) { TOGO_LOGF( "reading (%3u): <%.*s>\n", test.data.size, test.data.size, test.data.data ); Object root; MemoryReader in_stream{test.data}; ObjectParserInfo pinfo; if (object::read_text(root, in_stream, pinfo)) { MemoryStream out_stream{memory::default_allocator(), test.expected_output.size + 1}; TOGO_ASSERTE(object::write_text(root, out_stream)); StringRef output{ reinterpret_cast<char*>(array::begin(out_stream.data())), static_cast<unsigned>(out_stream.size()) }; // Remove trailing newline if (output.size > 0) { --output.size; } TOGO_LOGF( "rewritten (%3u): <%.*s>\n", output.size, output.size, output.data ); TOGO_ASSERT(test.success, "read succeeded when it should have failed"); TOGO_ASSERT( string::compare_equal(test.expected_output, output), "output does not match" ); } else { TOGO_LOGF( "failed to read%s: [%2u,%2u]: %s\n", test.success ? " (UNEXPECTED)" : "", pinfo.line, pinfo.column, pinfo.message ); TOGO_ASSERT(!test.success, "read failed when it should have succeeded"); } TOGO_LOG("\n"); } signed main() { memory_init(); for (auto& test : tests) { check(test); } return 0; } <|endoftext|>
<commit_before>#include "sequence.h" namespace magic_bean{ const int64_t kInitialValue = -1; Sequence::Sequence() { value_.store(kInitialValue); } Sequence::Sequence(int64_t initial_value) { value_.store(initial_value); } int64_t Sequence::Get() const { return value_.load(std::memory_order::memory_order_acquire); } void Sequence::Set(int64_t value) { value_.store(value, std::memory_order::memory_order_release); } int64_t Sequence::IncrementAndGet() { return AddAndGet(1L); } int64_t Sequence::AddAndGet(int64_t increment) { int64_t current_value, new_value; return 0; } } //end namespace <commit_msg>modify sequence.cc<commit_after>#include "sequence.h" namespace magic_bean{ const int64_t kInitialValue = -1; Sequence::Sequence() { value_.store(kInitialValue); } Sequence::Sequence(int64_t initial_value) { value_.store(initial_value); } int64_t Sequence::Get() const { return value_.load(std::memory_order::memory_order_acquire); } void Sequence::Set(int64_t value) { value_.store(value, std::memory_order::memory_order_release); } int64_t Sequence::IncrementAndGet() { return AddAndGet(1L); } int64_t Sequence::AddAndGet(int64_t increment) { int64_t current_value, new_value; current_value = value_.load(std::memory_order::memory_order_relaxed); do { new_value = current_value + increment; } while(!value_.compare_exchange_weak(current_value, new_value)); return new_value; } } //end namespace <|endoftext|>
<commit_before><commit_msg>misc: Stop "using namespace std" in protoio.cc.<commit_after><|endoftext|>
<commit_before>/* Copyright libCellML Contributors 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 "test_utils.h" #include "gtest/gtest.h" #include <libcellml> TEST(Maths, setAndGetMath) { libcellml::ComponentPtr c = libcellml::Component::create(); c->setMath(EMPTY_MATH); EXPECT_EQ(EMPTY_MATH, c->math()); } TEST(Maths, appendAndSerialiseMathComponent) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = createModelWithComponent(); libcellml::ComponentPtr c = m->component(0); c->appendMath(EMPTY_MATH); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Maths, appendAndRemoveMathFromComponent) { const std::string eNoMath = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component/>\n" "</model>\n"; const std::string eWithMath = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = createModelWithComponent(); libcellml::ComponentPtr c = m->component(0); libcellml::PrinterPtr printer = libcellml::Printer::create(); c->appendMath(EMPTY_MATH); std::string a = printer->printModel(m); EXPECT_EQ(eWithMath, a); c->removeMath(); a = printer->printModel(m); EXPECT_EQ(eNoMath, a); c->appendMath(EMPTY_MATH); a = printer->printModel(m); EXPECT_EQ(eWithMath, a); c->setMath(""); a = printer->printModel(m); EXPECT_EQ(eNoMath, a); } TEST(Maths, appendSerialiseAndParseMathInComponent) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); m->addComponent(c); c->appendMath(EMPTY_MATH); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(e, a); // Parse libcellml::ParserPtr parser = libcellml::Parser::create(); libcellml::ModelPtr model = parser->parseModel(e); a = printer->printModel(model); EXPECT_EQ(e, a); } TEST(Maths, modelWithTwoVariablesAndTwoInvalidMaths) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component\">\n" " <variable name=\"variable1\"/>\n" " <variable name=\"variable2\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); libcellml::VariablePtr v1 = libcellml::Variable::create(); libcellml::VariablePtr v2 = libcellml::Variable::create(); c->setName("component"); v1->setName("variable1"); v2->setName("variable2"); c->addVariable(v1); c->addVariable(v2); c->appendMath(EMPTY_MATH); c->appendMath(EMPTY_MATH); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Maths, modelWithTwoVariablesWithInitialValuesAndInvalidMath) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component\">\n" " <variable name=\"variable1\" initial_value=\"1.0\"/>\n" " <variable name=\"variable2\" initial_value=\"-1.0\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); libcellml::VariablePtr v1 = libcellml::Variable::create(); libcellml::VariablePtr v2 = libcellml::Variable::create(); c->setName("component"); v1->setName("variable1"); v2->setName("variable2"); v1->setInitialValue("1.0"); v2->setInitialValue("-1.0"); c->addVariable(v1); c->addVariable(v2); c->appendMath(EMPTY_MATH); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } // 1.xiii.a TEST(Maths, modelWithTwoVariablesWithInitialValuesAndValidMath) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component\">\n" " <variable name=\"A\" initial_value=\"1.0\"/>\n" " <variable name=\"B\" initial_value=\"-1.0\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A</ci>\n" " <ci>B</ci>\n" " </apply>\n" " </apply>\n" " </math>\n" " </component>\n" "</model>\n"; const std::string math = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A</ci>\n" " <ci>B</ci>\n" " </apply>\n" " </apply>\n" "</math>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); libcellml::VariablePtr v1 = libcellml::Variable::create(); libcellml::VariablePtr v2 = libcellml::Variable::create(); c->setName("component"); v1->setName("A"); v2->setName("B"); v1->setInitialValue("1.0"); v2->setInitialValue("-1.0"); c->addVariable(v1); c->addVariable(v2); c->appendMath(math); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } // 1.xiv.a TEST(Maths, twoComponentsWithMathAndConnectionAndParse) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component1\">\n" " <variable name=\"A1\"/>\n" " <variable name=\"B1\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C1</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A1</ci>\n" " <ci>B1</ci>\n" " </apply>\n" " </apply>\n" " </math>\n" " </component>\n" " <component name=\"component2\">\n" " <variable name=\"A2\"/>\n" " <variable name=\"B2\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C2</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A2</ci>\n" " <ci>B2</ci>\n" " </apply>\n" " </apply>\n" " </math>\n" " </component>\n" " <connection component_1=\"component1\" component_2=\"component2\">\n" " <map_variables variable_1=\"A1\" variable_2=\"A2\"/>\n" " </connection>\n" "</model>\n"; const std::string math1 = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C1</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A1</ci>\n" " <ci>B1</ci>\n" " </apply>\n" " </apply>\n" "</math>\n"; const std::string math2 = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C2</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A2</ci>\n" " <ci>B2</ci>\n" " </apply>\n" " </apply>\n" "</math>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr comp1 = libcellml::Component::create(); libcellml::ComponentPtr comp2 = libcellml::Component::create(); libcellml::VariablePtr v11 = libcellml::Variable::create(); libcellml::VariablePtr v12 = libcellml::Variable::create(); libcellml::VariablePtr v21 = libcellml::Variable::create(); libcellml::VariablePtr v22 = libcellml::Variable::create(); comp1->setName("component1"); comp2->setName("component2"); v11->setName("A1"); v12->setName("B1"); v21->setName("A2"); v22->setName("B2"); comp1->addVariable(v11); comp1->addVariable(v12); comp2->addVariable(v21); comp2->addVariable(v22); comp1->appendMath(math1); comp2->appendMath(math2); m->addComponent(comp1); m->addComponent(comp2); libcellml::Variable::addEquivalence(v11, v21); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(e, a); // Parse libcellml::ParserPtr parser = libcellml::Parser::create(); libcellml::ModelPtr model = parser->parseModel(e); a = printer->printModel(model); EXPECT_EQ(e, a); } TEST(Maths, addingMathMLAsACompleteDocument) { const std::string errorMessage = "LibXml2 error: XML declaration allowed only at the start of the document."; const std::string e = "<?xml version= \"1.0 \" encoding= \"UTF-8 \"?>\n" "<model xmlns= \"http://www.cellml.org/cellml/2.0# \">\n" " <component name= \"parameters \">\n" " <math xmlns= \"http://www.w3.org/1998/Math/MathML \">\n" " <apply>\n" " <divide/>\n" " <ci>eff</ci>\n" " <ci>t_ave</ci>\n" " </apply>\n" " </math>\n" " </component>\n" "</model>\n"; const std::string math = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <divide/>\n" " <ci> eff </ci>\n" " <ci> t_ave </ci>\n" " </apply>\n" "</math>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr comp = libcellml::Component::create(); comp->setName("parameters"); comp->appendMath(math); m->addComponent(comp); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(size_t(1), printer->issueCount()); EXPECT_EQ(errorMessage, printer->issue(0)->description()); EXPECT_EQ("", a); } <commit_msg>Fixes for clang format.<commit_after>/* Copyright libCellML Contributors 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 "test_utils.h" #include "gtest/gtest.h" #include <libcellml> TEST(Maths, setAndGetMath) { libcellml::ComponentPtr c = libcellml::Component::create(); c->setMath(EMPTY_MATH); EXPECT_EQ(EMPTY_MATH, c->math()); } TEST(Maths, appendAndSerialiseMathComponent) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = createModelWithComponent(); libcellml::ComponentPtr c = m->component(0); c->appendMath(EMPTY_MATH); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Maths, appendAndRemoveMathFromComponent) { const std::string eNoMath = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component/>\n" "</model>\n"; const std::string eWithMath = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = createModelWithComponent(); libcellml::ComponentPtr c = m->component(0); libcellml::PrinterPtr printer = libcellml::Printer::create(); c->appendMath(EMPTY_MATH); std::string a = printer->printModel(m); EXPECT_EQ(eWithMath, a); c->removeMath(); a = printer->printModel(m); EXPECT_EQ(eNoMath, a); c->appendMath(EMPTY_MATH); a = printer->printModel(m); EXPECT_EQ(eWithMath, a); c->setMath(""); a = printer->printModel(m); EXPECT_EQ(eNoMath, a); } TEST(Maths, appendSerialiseAndParseMathInComponent) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); m->addComponent(c); c->appendMath(EMPTY_MATH); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(e, a); // Parse libcellml::ParserPtr parser = libcellml::Parser::create(); libcellml::ModelPtr model = parser->parseModel(e); a = printer->printModel(model); EXPECT_EQ(e, a); } TEST(Maths, modelWithTwoVariablesAndTwoInvalidMaths) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component\">\n" " <variable name=\"variable1\"/>\n" " <variable name=\"variable2\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); libcellml::VariablePtr v1 = libcellml::Variable::create(); libcellml::VariablePtr v2 = libcellml::Variable::create(); c->setName("component"); v1->setName("variable1"); v2->setName("variable2"); c->addVariable(v1); c->addVariable(v2); c->appendMath(EMPTY_MATH); c->appendMath(EMPTY_MATH); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Maths, modelWithTwoVariablesWithInitialValuesAndInvalidMath) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component\">\n" " <variable name=\"variable1\" initial_value=\"1.0\"/>\n" " <variable name=\"variable2\" initial_value=\"-1.0\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\"/>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); libcellml::VariablePtr v1 = libcellml::Variable::create(); libcellml::VariablePtr v2 = libcellml::Variable::create(); c->setName("component"); v1->setName("variable1"); v2->setName("variable2"); v1->setInitialValue("1.0"); v2->setInitialValue("-1.0"); c->addVariable(v1); c->addVariable(v2); c->appendMath(EMPTY_MATH); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } // 1.xiii.a TEST(Maths, modelWithTwoVariablesWithInitialValuesAndValidMath) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component\">\n" " <variable name=\"A\" initial_value=\"1.0\"/>\n" " <variable name=\"B\" initial_value=\"-1.0\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A</ci>\n" " <ci>B</ci>\n" " </apply>\n" " </apply>\n" " </math>\n" " </component>\n" "</model>\n"; const std::string math = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A</ci>\n" " <ci>B</ci>\n" " </apply>\n" " </apply>\n" "</math>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); libcellml::VariablePtr v1 = libcellml::Variable::create(); libcellml::VariablePtr v2 = libcellml::Variable::create(); c->setName("component"); v1->setName("A"); v2->setName("B"); v1->setInitialValue("1.0"); v2->setInitialValue("-1.0"); c->addVariable(v1); c->addVariable(v2); c->appendMath(math); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } // 1.xiv.a TEST(Maths, twoComponentsWithMathAndConnectionAndParse) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component1\">\n" " <variable name=\"A1\"/>\n" " <variable name=\"B1\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C1</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A1</ci>\n" " <ci>B1</ci>\n" " </apply>\n" " </apply>\n" " </math>\n" " </component>\n" " <component name=\"component2\">\n" " <variable name=\"A2\"/>\n" " <variable name=\"B2\"/>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C2</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A2</ci>\n" " <ci>B2</ci>\n" " </apply>\n" " </apply>\n" " </math>\n" " </component>\n" " <connection component_1=\"component1\" component_2=\"component2\">\n" " <map_variables variable_1=\"A1\" variable_2=\"A2\"/>\n" " </connection>\n" "</model>\n"; const std::string math1 = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C1</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A1</ci>\n" " <ci>B1</ci>\n" " </apply>\n" " </apply>\n" "</math>\n"; const std::string math2 = "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <eq/>\n" " <ci>C2</ci>\n" " <apply>\n" " <plus/>\n" " <ci>A2</ci>\n" " <ci>B2</ci>\n" " </apply>\n" " </apply>\n" "</math>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr comp1 = libcellml::Component::create(); libcellml::ComponentPtr comp2 = libcellml::Component::create(); libcellml::VariablePtr v11 = libcellml::Variable::create(); libcellml::VariablePtr v12 = libcellml::Variable::create(); libcellml::VariablePtr v21 = libcellml::Variable::create(); libcellml::VariablePtr v22 = libcellml::Variable::create(); comp1->setName("component1"); comp2->setName("component2"); v11->setName("A1"); v12->setName("B1"); v21->setName("A2"); v22->setName("B2"); comp1->addVariable(v11); comp1->addVariable(v12); comp2->addVariable(v21); comp2->addVariable(v22); comp1->appendMath(math1); comp2->appendMath(math2); m->addComponent(comp1); m->addComponent(comp2); libcellml::Variable::addEquivalence(v11, v21); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(e, a); // Parse libcellml::ParserPtr parser = libcellml::Parser::create(); libcellml::ModelPtr model = parser->parseModel(e); a = printer->printModel(model); EXPECT_EQ(e, a); } TEST(Maths, addingMathMLAsACompleteDocument) { const std::string errorMessage = "LibXml2 error: XML declaration allowed only at the start of the document."; const std::string math = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <divide/>\n" " <ci> eff </ci>\n" " <ci> t_ave </ci>\n" " </apply>\n" "</math>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr comp = libcellml::Component::create(); comp->setName("parameters"); comp->appendMath(math); m->addComponent(comp); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(size_t(1), printer->issueCount()); EXPECT_EQ(errorMessage, printer->issue(0)->description()); EXPECT_EQ("", a); } <|endoftext|>
<commit_before>#include "rgw_cache.h" #include <errno.h> #define DOUT_SUBSYS rgw using namespace std; int ObjectCache::get(string& name, ObjectCacheInfo& info, uint32_t mask) { Mutex::Locker l(lock); map<string, ObjectCacheEntry>::iterator iter = cache_map.find(name); if (iter == cache_map.end()) { dout(10) << "cache get: name=" << name << " : miss" << dendl; perfcounter->inc(l_rgw_cache_miss); return -ENOENT; } touch_lru(name, iter->second.lru_iter); ObjectCacheInfo& src = iter->second.info; if ((src.flags & mask) != mask) { dout(10) << "cache get: name=" << name << " : type miss (requested=" << mask << ", cached=" << src.flags << dendl; perfcounter->inc(l_rgw_cache_miss); return -ENOENT; } dout(10) << "cache get: name=" << name << " : hit" << dendl; info = src; perfcounter->inc(l_rgw_cache_hit); return 0; } void ObjectCache::put(string& name, ObjectCacheInfo& info) { Mutex::Locker l(lock); dout(10) << "cache put: name=" << name << dendl; map<string, ObjectCacheEntry>::iterator iter = cache_map.find(name); if (iter == cache_map.end()) { ObjectCacheEntry entry; entry.lru_iter = lru.end(); cache_map.insert(pair<string, ObjectCacheEntry>(name, entry)); iter = cache_map.find(name); } ObjectCacheEntry& entry = iter->second; ObjectCacheInfo& target = entry.info; touch_lru(name, entry.lru_iter); target.status = info.status; if (info.status < 0) { target.flags = 0; target.xattrs.clear(); target.data.clear(); return; } target.flags |= info.flags; if (info.flags & CACHE_FLAG_META) target.meta = info.meta; else target.flags &= ~CACHE_FLAG_META; // any non-meta change should reset meta if (info.flags & CACHE_FLAG_XATTRS) { target.xattrs = info.xattrs; map<string, bufferlist>::iterator iter; for (iter = target.xattrs.begin(); iter != target.xattrs.end(); ++iter) { dout(0) << "updating xattr: name=" << iter->first << " bl.length()=" << iter->second.length() << dendl; } } else if (info.flags & CACHE_FLAG_APPEND_XATTRS) { map<string, bufferlist>::iterator iter; for (iter = info.xattrs.begin(); iter != info.xattrs.end(); ++iter) { dout(0) << "appending xattr: name=" << iter->first << " bl.length()=" << iter->second.length() << dendl; target.xattrs[iter->first] = iter->second; } } if (info.flags & CACHE_FLAG_DATA) target.data = info.data; } void ObjectCache::remove(string& name) { Mutex::Locker l(lock); map<string, ObjectCacheEntry>::iterator iter = cache_map.find(name); if (iter == cache_map.end()) return; dout(10) << "removing " << name << " from cache" << dendl; remove_lru(name, iter->second.lru_iter); cache_map.erase(iter); } void ObjectCache::touch_lru(string& name, std::list<string>::iterator& lru_iter) { while (lru.size() > (size_t)g_conf->rgw_cache_lru_size) { list<string>::iterator iter = lru.begin(); map<string, ObjectCacheEntry>::iterator map_iter = cache_map.find(*iter); dout(10) << "removing entry: name=" << *iter << " from cache LRU" << dendl; if (map_iter != cache_map.end()) cache_map.erase(map_iter); lru.pop_front(); } if (lru_iter == lru.end()) { lru.push_back(name); lru_iter--; dout(10) << "adding " << name << " to cache LRU end" << dendl; } else { dout(10) << "moving " << name << " to cache LRU end" << dendl; lru.erase(lru_iter); lru.push_back(name); lru_iter = lru.end(); --lru_iter; } } void ObjectCache::remove_lru(string& name, std::list<string>::iterator& lru_iter) { if (lru_iter == lru.end()) return; lru.erase(lru_iter); lru_iter = lru.end(); } <commit_msg>rgw: guard perfcounter accesses in rgw_cache.<commit_after>#include "rgw_cache.h" #include <errno.h> #define DOUT_SUBSYS rgw using namespace std; int ObjectCache::get(string& name, ObjectCacheInfo& info, uint32_t mask) { Mutex::Locker l(lock); map<string, ObjectCacheEntry>::iterator iter = cache_map.find(name); if (iter == cache_map.end()) { dout(10) << "cache get: name=" << name << " : miss" << dendl; if(perfcounter) perfcounter->inc(l_rgw_cache_miss); return -ENOENT; } touch_lru(name, iter->second.lru_iter); ObjectCacheInfo& src = iter->second.info; if ((src.flags & mask) != mask) { dout(10) << "cache get: name=" << name << " : type miss (requested=" << mask << ", cached=" << src.flags << dendl; if(perfcounter) perfcounter->inc(l_rgw_cache_miss); return -ENOENT; } dout(10) << "cache get: name=" << name << " : hit" << dendl; info = src; if(perfcounter) perfcounter->inc(l_rgw_cache_hit); return 0; } void ObjectCache::put(string& name, ObjectCacheInfo& info) { Mutex::Locker l(lock); dout(10) << "cache put: name=" << name << dendl; map<string, ObjectCacheEntry>::iterator iter = cache_map.find(name); if (iter == cache_map.end()) { ObjectCacheEntry entry; entry.lru_iter = lru.end(); cache_map.insert(pair<string, ObjectCacheEntry>(name, entry)); iter = cache_map.find(name); } ObjectCacheEntry& entry = iter->second; ObjectCacheInfo& target = entry.info; touch_lru(name, entry.lru_iter); target.status = info.status; if (info.status < 0) { target.flags = 0; target.xattrs.clear(); target.data.clear(); return; } target.flags |= info.flags; if (info.flags & CACHE_FLAG_META) target.meta = info.meta; else target.flags &= ~CACHE_FLAG_META; // any non-meta change should reset meta if (info.flags & CACHE_FLAG_XATTRS) { target.xattrs = info.xattrs; map<string, bufferlist>::iterator iter; for (iter = target.xattrs.begin(); iter != target.xattrs.end(); ++iter) { dout(0) << "updating xattr: name=" << iter->first << " bl.length()=" << iter->second.length() << dendl; } } else if (info.flags & CACHE_FLAG_APPEND_XATTRS) { map<string, bufferlist>::iterator iter; for (iter = info.xattrs.begin(); iter != info.xattrs.end(); ++iter) { dout(0) << "appending xattr: name=" << iter->first << " bl.length()=" << iter->second.length() << dendl; target.xattrs[iter->first] = iter->second; } } if (info.flags & CACHE_FLAG_DATA) target.data = info.data; } void ObjectCache::remove(string& name) { Mutex::Locker l(lock); map<string, ObjectCacheEntry>::iterator iter = cache_map.find(name); if (iter == cache_map.end()) return; dout(10) << "removing " << name << " from cache" << dendl; remove_lru(name, iter->second.lru_iter); cache_map.erase(iter); } void ObjectCache::touch_lru(string& name, std::list<string>::iterator& lru_iter) { while (lru.size() > (size_t)g_conf->rgw_cache_lru_size) { list<string>::iterator iter = lru.begin(); map<string, ObjectCacheEntry>::iterator map_iter = cache_map.find(*iter); dout(10) << "removing entry: name=" << *iter << " from cache LRU" << dendl; if (map_iter != cache_map.end()) cache_map.erase(map_iter); lru.pop_front(); } if (lru_iter == lru.end()) { lru.push_back(name); lru_iter--; dout(10) << "adding " << name << " to cache LRU end" << dendl; } else { dout(10) << "moving " << name << " to cache LRU end" << dendl; lru.erase(lru_iter); lru.push_back(name); lru_iter = lru.end(); --lru_iter; } } void ObjectCache::remove_lru(string& name, std::list<string>::iterator& lru_iter) { if (lru_iter == lru.end()) return; lru.erase(lru_iter); lru_iter = lru.end(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: combtransition.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-01-21 17:08:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <canvas/debug.hxx> #include <combtransition.hxx> #include <basegfx/polygon/b2dpolygontools.hxx> #include <basegfx/polygon/b2dpolypolygontools.hxx> namespace presentation { namespace internal { namespace { ::basegfx::B2DPolyPolygon createClipPolygon( const ::basegfx::B2DVector& rDirection, const ::basegfx::B2DSize& rSlideSize, int nNumStrips, int nOffset ) { // create clip polygon in standard orientation (will later // be rotated to match direction vector) ::basegfx::B2DPolyPolygon aClipPoly; // create nNumStrips/2 vertical strips for( int i=nOffset; i<nNumStrips; i+=2 ) { aClipPoly.append( ::basegfx::tools::createPolygonFromRect( ::basegfx::B2DRectangle( (double)i/nNumStrips, 0.0, (double)(i+1)/nNumStrips, 1.0) ) ); } // rotate polygons, such that the strips are parallel to // the given direction vector const ::basegfx::B2DVector aUpVec(0.0, 1.0); ::basegfx::B2DHomMatrix aMatrix; aMatrix.translate( -0.5, -0.5 ); aMatrix.rotate( aUpVec.angle( rDirection ) ); aMatrix.translate( 0.5, 0.5 ); // blow up clip polygon to slide size aMatrix.scale( rSlideSize.getX(), rSlideSize.getY() ); aClipPoly.transform( aMatrix ); return aClipPoly; } } CombTransition::CombTransition( const SlideBitmapSharedPtr& rLeavingBitmap, const SlideBitmapSharedPtr& rEnteringBitmap, const ::basegfx::B2DVector& rPushDirection, sal_Int32 nNumStripes, const SoundPlayerSharedPtr& rSoundPlayer ) : maViews(), mpLeavingBitmap( rLeavingBitmap ), mpEnteringBitmap( rEnteringBitmap ), maBitmapSize( getBitmapSize() ), maClipPolygon1( createClipPolygon( rPushDirection, maBitmapSize, nNumStripes, 0 ) ), maClipPolygon2( createClipPolygon( rPushDirection, maBitmapSize, nNumStripes, 1 ) ), maPushDirection( maBitmapSize * rPushDirection ), mpSoundPlayer( rSoundPlayer ) { ENSURE_AND_THROW( rEnteringBitmap.get(), "CombTransition::CombTransition(): Invalid entering bitmap" ); } ::basegfx::B2DSize CombTransition::getBitmapSize() const { return ::basegfx::B2DSize( ::basegfx::B2DTuple( mpEnteringBitmap->getSize() ) ); } void CombTransition::start( const AnimatableShapeSharedPtr&, const ShapeAttributeLayerSharedPtr& ) { // TODO(F1): Maybe we've got to create separate bitmaps // for every view, should the canvas not allow for // cross-canvas bitmap rendering if( mpSoundPlayer.get() ) mpSoundPlayer->startPlayback(); } void CombTransition::end() { if( mpSoundPlayer.get() ) mpSoundPlayer->stopPlayback(); // drop all references mpLeavingBitmap.reset(); mpEnteringBitmap.reset(); maViews.clear(); } bool CombTransition::operator()( double t ) { if( !mpEnteringBitmap.get() ) { return false; } for( ::std::size_t i=0, nEntries=maViews.size(); i<nEntries; ++i ) { // calc bitmap offsets. The enter/leaving bitmaps are only // as large as the actual slides. For scaled-down // presentations, we have to move the left, top edge of // those bitmaps to the actual position, governed by the // given view transform. The aBitmapPosPixel local // variable is already in device coordinate space // (i.e. pixel). ::cppcanvas::CanvasSharedPtr pCanvas( maViews[i]->getCanvas() ); ENSURE_AND_THROW( pCanvas.get(), "CombTransition::operator(): Invalid canvas" ); // TODO(F2): Properly respect clip here. Might have to be transformed, too. const ::basegfx::B2DHomMatrix aViewTransform( pCanvas->getTransformation() ); const ::basegfx::B2DPoint aPageOrigin( aViewTransform * ::basegfx::B2DPoint() ); // change transformation on cloned canvas to be in // device pixel pCanvas = pCanvas->clone(); pCanvas->setTransformation( ::basegfx::B2DHomMatrix() ); // TODO(Q2): Use basegfx bitmaps here // TODO(F1): SlideBitmap is not fully portable between different canvases! if( mpLeavingBitmap.get() ) { // render odd strips mpLeavingBitmap->move( aPageOrigin + t*maPushDirection ); mpLeavingBitmap->clip( maClipPolygon1 ); mpLeavingBitmap->draw( pCanvas ); // render even strips mpLeavingBitmap->move( aPageOrigin - t*maPushDirection ); mpLeavingBitmap->clip( maClipPolygon2 ); mpLeavingBitmap->draw( pCanvas ); } // TODO(Q2): Use basegfx bitmaps here // TODO(F1): SlideBitmap is not fully portable between different canvases! // render odd strips mpEnteringBitmap->move( aPageOrigin + (t-1.0)*maPushDirection ); mpEnteringBitmap->clip( maClipPolygon1 ); mpEnteringBitmap->draw( pCanvas ); // render even strips mpEnteringBitmap->move( aPageOrigin + (1.0-t)*maPushDirection ); mpEnteringBitmap->clip( maClipPolygon2 ); mpEnteringBitmap->draw( pCanvas ); } return true; } double CombTransition::getUnderlyingValue() const { return 0.0; // though this should be used in concert with // ActivitiesFactory::createSimpleActivity, better // explicitely name our start value. // Permissible range for operator() above is [0,1] } void CombTransition::addView( const ViewSharedPtr& rView ) { // TODO(Q2): Try to use UnoViewContainer here. maViews.push_back( rView ); } bool CombTransition::removeView( const ViewSharedPtr& rView ) { // remove locally const ViewVector::iterator aEnd( maViews.end() ); ViewVector::iterator aIter; if( (aIter=::std::remove( maViews.begin(), aEnd, rView)) == aEnd ) { // view seemingly was not added, failed return false; } // actually erase from container maViews.erase( aIter, aEnd ); return true; } } } <commit_msg>INTEGRATION: CWS presfixes01 (1.3.2); FILE MERGED 2005/02/15 23:51:00 thb 1.3.2.3: #i42440# Moved sprite-growing code to slideshow, some minor issues with size calculations for empty slides (when a 'leaving' slide is needed, but there's no previous one, an empty bitmap is generated) 2005/01/30 15:54:42 dbo 1.3.2.2: #i39787# correct bitmap dimensions Issue number: Submitted by: Reviewed by: 2005/01/26 11:18:31 dbo 1.3.2.1: #i39787# slide transition revision: recalc bitmaps/sprites in case of view changes Issue number: Submitted by: Reviewed by:<commit_after>/************************************************************************* * * $RCSfile: combtransition.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2005-03-10 13:51:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "combtransition.hxx" #include "canvas/debug.hxx" #include "basegfx/polygon/b2dpolygontools.hxx" #include "basegfx/polygon/b2dpolypolygontools.hxx" namespace presentation { namespace internal { namespace { basegfx::B2DPolyPolygon createClipPolygon( const ::basegfx::B2DVector& rDirection, const ::basegfx::B2DSize& rSlideSize, int nNumStrips, int nOffset ) { // create clip polygon in standard orientation (will later // be rotated to match direction vector) ::basegfx::B2DPolyPolygon aClipPoly; // create nNumStrips/2 vertical strips for( int i=nOffset; i<nNumStrips; i+=2 ) { aClipPoly.append( ::basegfx::tools::createPolygonFromRect( ::basegfx::B2DRectangle( (double)i/nNumStrips, 0.0, (double)(i+1)/nNumStrips, 1.0) ) ); } // rotate polygons, such that the strips are parallel to // the given direction vector const ::basegfx::B2DVector aUpVec(0.0, 1.0); ::basegfx::B2DHomMatrix aMatrix; aMatrix.translate( -0.5, -0.5 ); aMatrix.rotate( aUpVec.angle( rDirection ) ); aMatrix.translate( 0.5, 0.5 ); // blow up clip polygon to slide size aMatrix.scale( rSlideSize.getX(), rSlideSize.getY() ); aClipPoly.transform( aMatrix ); return aClipPoly; } } CombTransition::CombTransition( boost::optional<SlideSharedPtr> const & leavingSlide, const SlideSharedPtr& pEnteringSlide, const SoundPlayerSharedPtr& pSoundPlayer, const ::basegfx::B2DVector& rPushDirection, sal_Int32 nNumStripes ) : SlideChangeBase( leavingSlide, pEnteringSlide, pSoundPlayer, false /* no leaving sprite */, false /* no entering sprite */ ), maPushDirectionUnit( rPushDirection ), mnNumStripes( nNumStripes ) { } void CombTransition::renderComb( double t, UnoViewSharedPtr const & pView ) const { const cppcanvas::CanvasSharedPtr pCanvas_ = pView->getCanvas(); // calc bitmap offsets. The enter/leaving bitmaps are only // as large as the actual slides. For scaled-down // presentations, we have to move the left, top edge of // those bitmaps to the actual position, governed by the // given view transform. The aBitmapPosPixel local // variable is already in device coordinate space // (i.e. pixel). ENSURE_AND_THROW( pCanvas_.get(), "CombTransition::renderComb(): Invalid canvas" ); // TODO(F2): Properly respect clip here. Might have to be transformed, too. const basegfx::B2DHomMatrix viewTransform( pCanvas_->getTransformation() ); const basegfx::B2DPoint pageOrigin( viewTransform * basegfx::B2DPoint() ); // change transformation on cloned canvas to be in // device pixel cppcanvas::CanvasSharedPtr pCanvas( pCanvas_->clone() ); basegfx::B2DHomMatrix transform; basegfx::B2DPoint p; // TODO(Q2): Use basegfx bitmaps here // TODO(F1): SlideBitmap is not fully portable between different canvases! const basegfx::B2DSize enteringSizePixel( getEnteringSizePixel(pView) ); const basegfx::B2DVector aPushDirection = basegfx::B2DVector( enteringSizePixel * maPushDirectionUnit ); const basegfx::B2DPolyPolygon aClipPolygon1 = basegfx::B2DPolyPolygon( createClipPolygon( maPushDirectionUnit, enteringSizePixel, mnNumStripes, 0 ) ); const basegfx::B2DPolyPolygon aClipPolygon2 = basegfx::B2DPolyPolygon( createClipPolygon( maPushDirectionUnit, enteringSizePixel, mnNumStripes, 1 ) ); SlideBitmapSharedPtr const & pLeavingBitmap = getLeavingBitmap(); if (pLeavingBitmap.get() != 0) { // render odd strips: pLeavingBitmap->clip( aClipPolygon1 ); // don't modify bitmap object (no move!): p = basegfx::B2DPoint( pageOrigin + (t * aPushDirection) ); transform.translate( p.getX(), p.getY() ); pCanvas->setTransformation( transform ); pLeavingBitmap->draw( pCanvas ); // render even strips: pLeavingBitmap->clip( aClipPolygon2 ); // don't modify bitmap object (no move!): transform.identity(); p = basegfx::B2DPoint( pageOrigin - (t * aPushDirection) ); transform.translate( p.getX(), p.getY() ); pCanvas->setTransformation( transform ); pLeavingBitmap->draw( pCanvas ); } // TODO(Q2): Use basegfx bitmaps here // TODO(F1): SlideBitmap is not fully portable between different canvases! // render odd strips: SlideBitmapSharedPtr const & pEnteringBitmap = getEnteringBitmap(); pEnteringBitmap->clip( aClipPolygon1 ); // don't modify bitmap object (no move!): transform.identity(); p = basegfx::B2DPoint( pageOrigin + ((t - 1.0) * aPushDirection) ); transform.translate( p.getX(), p.getY() ); pCanvas->setTransformation( transform ); pEnteringBitmap->draw( pCanvas ); // render even strips: pEnteringBitmap->clip( aClipPolygon2 ); // don't modify bitmap object (no move!): transform.identity(); p = basegfx::B2DPoint( pageOrigin + ((1.0 - t) * aPushDirection) ); transform.translate( p.getX(), p.getY() ); pCanvas->setTransformation( transform ); pEnteringBitmap->draw( pCanvas ); } bool CombTransition::operator()( double t ) { SlideBitmapSharedPtr const & pSlideBitmap = getEnteringBitmap(); if (pSlideBitmap.get() == 0) return false; for_each_view( boost::bind( &CombTransition::renderComb, this, t, _1 ) ); return true; } } // namespace internal } // namespace presentation <|endoftext|>
<commit_before>#include "utils.hpp" #include "libdnf/dnf-sack-private.hpp" #include "libdnf/sack/advisorymodule.hpp" #include <tinyformat/tinyformat.hpp> #include <algorithm> #include <sys/stat.h> #include <dirent.h> #include <cstring> #include <stdexcept> extern "C" { #include <solv/solv_xfopen.h> }; #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <random> namespace libdnf { bool isAdvisoryApplicable(libdnf::Advisory & advisory, DnfSack * sack) { auto moduleContainer = dnf_sack_get_module_container(sack); if (!moduleContainer) { return true; } auto moduleAdvisories = advisory.getModules(); if (moduleAdvisories.empty()) { return true; } for (auto & moduleAdvisory: moduleAdvisories) { if (const char * name = moduleAdvisory.getName()) { if (const char * stream = moduleAdvisory.getStream()) { if (moduleContainer->isEnabled(name, stream)) { return true; } } } } return false; } namespace string { std::vector<std::string> split(const std::string &source, const char *delimiter, int maxSplit) { if (source.empty()) throw std::runtime_error{"Source cannot be empty"}; std::string::size_type tokenBeginIndex = 0; std::vector<std::string> container; while ((tokenBeginIndex = source.find_first_not_of(delimiter, tokenBeginIndex)) != source.npos) { if (maxSplit != -1 && ((int) (container.size() + 1 )) == maxSplit) { container.emplace_back(source.substr(tokenBeginIndex)); break; } auto tokenEndIndex = source.find_first_of(delimiter, tokenBeginIndex); container.emplace_back(source.substr(tokenBeginIndex, tokenEndIndex - tokenBeginIndex)); tokenBeginIndex = tokenEndIndex; } if (container.empty()) { throw std::runtime_error{"No delimiter found in source: " + source}; } return container; } std::vector<std::string> rsplit(const std::string &source, const char *delimiter, int maxSplit) { if (source.empty()) throw std::runtime_error{"Source cannot be empty"}; std::string sequence = source; std::string::size_type tokenBeginIndex = 0; std::vector<std::string> container; while ((tokenBeginIndex = sequence.find_last_of(delimiter)) != sequence.npos) { if (maxSplit != -1 && ((int) (container.size() + 1 )) == maxSplit) { container.emplace_back(source.substr(0, tokenBeginIndex)); break; } container.emplace(container.begin(), source.substr(tokenBeginIndex + 1)); sequence = sequence.substr(0, tokenBeginIndex); } if (container.empty()) { throw std::runtime_error{"No delimiter found in source: " + source}; } return container; } std::string trimSuffix(const std::string &source, const std::string &suffix) { if (source.length() < suffix.length()) throw std::runtime_error{"Suffix cannot be longer than source"}; if (endsWith(source, suffix)) return source.substr(0, source.length() - suffix.length()); throw std::runtime_error{"Suffix '" + suffix + "' not found"}; } std::string trimPrefix(const std::string &source, const std::string &prefix) { if (source.length() < prefix.length()) throw std::runtime_error{"Prefix cannot be longer than source"}; if (startsWith(source, prefix)) return source.substr(prefix.length() - 1); throw std::runtime_error{"Prefix '" + prefix + "' not found"}; } std::string trim(const std::string &source) { size_t first = source.find_first_not_of(" \t"); if (first == source.npos) return ""; size_t last = source.find_last_not_of(" \t"); return source.substr(first, (last - first + 1)); } bool startsWith(const std::string & source, const std::string & toMatch) { return source.compare(0, toMatch.size(), toMatch) == 0; } bool endsWith(const std::string & source, const std::string & toMatch) { auto toMatchSize = toMatch.size(); return source.size() >= toMatchSize && source.compare( source.size() - toMatchSize, toMatchSize, toMatch) == 0; } } bool haveFilesSameContent(const char * filePath1, const char * filePath2) { static constexpr int BLOCK_SIZE = 4096; bool ret = false; int fd1 = -1; int fd2 = -1; do { if ((fd1 = open(filePath1, 0)) == -1) break; if ((fd2 = open(filePath2, 0)) == -1) break; auto len1 = lseek(fd1, 0, SEEK_END); auto len2 = lseek(fd2, 0, SEEK_END); if (len1 != len2) break; ret = true; if (len1 == 0) break; lseek(fd1, 0, SEEK_SET); lseek(fd2, 0, SEEK_SET); char buf1[BLOCK_SIZE], buf2[BLOCK_SIZE]; ssize_t readed; do { readed = read(fd1, buf1, BLOCK_SIZE); auto readed2 = read(fd2, buf2, BLOCK_SIZE); if (readed2 != readed || memcmp(buf1, buf2, readed) != 0) { ret = false; break; } } while (readed == BLOCK_SIZE); } while (false); if (fd1 != -1) close(fd1); if (fd2 != -1) close(fd2); return ret; } static bool saveFile(const char * filePath, const char * newFileContent, unsigned long newFileContentLen) { int fd = -1; if ((fd = open(filePath, O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1) return false; auto writtenSize = write(fd, newFileContent, newFileContentLen); close(fd); return (static_cast<unsigned long>(writtenSize) == newFileContentLen); } bool updateFile(const char * filePath, const char * newFileContent) { static constexpr int BLOCK_SIZE = 4096; int fd = -1; const char * tmpFileContent = newFileContent; auto newFileContentLen = strlen(newFileContent); if ((fd = open(filePath, O_RDONLY)) == -1) return saveFile(filePath, newFileContent, newFileContentLen); auto len = lseek(fd, 0, SEEK_END); if (len < 0 || (unsigned long)len != newFileContentLen) { close(fd); return saveFile(filePath, newFileContent, newFileContentLen); } // No need to update file when newFileContentLen and len of file == 0 if (newFileContentLen > 0) { lseek(fd, 0, SEEK_SET); char buf1[BLOCK_SIZE]; ssize_t readed; do { readed = read(fd, buf1, BLOCK_SIZE); if (readed < 0 && errno == EINTR) continue; if (readed < 0 || memcmp(buf1, tmpFileContent, readed) != 0) { close(fd); return saveFile(filePath, newFileContent, newFileContentLen); } tmpFileContent = tmpFileContent + BLOCK_SIZE; } while (readed == BLOCK_SIZE); } if (fd != -1) close(fd); return true; } namespace filesystem { bool exists(const std::string &name) { struct stat buffer; return stat(name.c_str(), &buffer) == 0; } bool isDIR(const std::string& dirPath) { struct stat buf; lstat(dirPath.c_str(), &buf); return S_ISDIR(buf.st_mode); } std::vector<std::string> getDirContent(const std::string &dirPath) { std::vector<std::string> content{}; struct dirent *ent; DIR *dir = opendir(dirPath.c_str()); if (dir != nullptr) { while ((ent = readdir(dir)) != nullptr) { if (strcmp(ent->d_name, "..") == 0 || strcmp(ent->d_name, ".") == 0 ) continue; auto fullPath = dirPath; if (!string::endsWith(fullPath, "/")) fullPath += "/"; fullPath += ent->d_name; content.emplace_back(fullPath); } closedir (dir); } return content; } void decompress(const char * inPath, const char * outPath, mode_t outMode, const char * compressType) { auto inFd = open(inPath, O_RDONLY); if (inFd == -1) throw std::runtime_error(tfm::format("open: %s", strerror(errno))); if (!compressType) compressType = inPath; auto inFile = solv_xfopen_fd(compressType, inFd, "r"); if (inFile == NULL) { close(inFd); throw std::runtime_error("solv_xfopen_fd: Can't open stream"); } auto outFd = open(outPath, O_WRONLY | O_CREAT | O_TRUNC, outMode); if (outFd == -1) { int err = errno; fclose(inFile); throw std::runtime_error(tfm::format("open: %s", strerror(err))); } char buf[4096]; while (auto readBytes = fread(buf, 1, sizeof(buf), inFile)) { auto writtenBytes = write(outFd, buf, readBytes); if (writtenBytes == -1) { int err = errno; close(outFd); fclose(inFile); throw std::runtime_error(tfm::format("write: %s", strerror(err))); } if (writtenBytes != static_cast<int>(readBytes)) { close(outFd); fclose(inFile); throw std::runtime_error("write: Problem during writing data"); } } if (!feof(inFile)) { close(outFd); fclose(inFile); throw std::runtime_error("fread: Problem during reading data"); } close(outFd); fclose(inFile); } } namespace numeric { int random(const int min, const int max) { std::random_device rd; std::default_random_engine gen(rd()); std::uniform_int_distribution<int> dist(min, max); return dist(gen); } } } <commit_msg>utils/decompress: add filename to error messages<commit_after>#include "utils.hpp" #include "libdnf/dnf-sack-private.hpp" #include "libdnf/sack/advisorymodule.hpp" #include <tinyformat/tinyformat.hpp> #include <algorithm> #include <sys/stat.h> #include <dirent.h> #include <cstring> #include <stdexcept> extern "C" { #include <solv/solv_xfopen.h> }; #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <random> namespace libdnf { bool isAdvisoryApplicable(libdnf::Advisory & advisory, DnfSack * sack) { auto moduleContainer = dnf_sack_get_module_container(sack); if (!moduleContainer) { return true; } auto moduleAdvisories = advisory.getModules(); if (moduleAdvisories.empty()) { return true; } for (auto & moduleAdvisory: moduleAdvisories) { if (const char * name = moduleAdvisory.getName()) { if (const char * stream = moduleAdvisory.getStream()) { if (moduleContainer->isEnabled(name, stream)) { return true; } } } } return false; } namespace string { std::vector<std::string> split(const std::string &source, const char *delimiter, int maxSplit) { if (source.empty()) throw std::runtime_error{"Source cannot be empty"}; std::string::size_type tokenBeginIndex = 0; std::vector<std::string> container; while ((tokenBeginIndex = source.find_first_not_of(delimiter, tokenBeginIndex)) != source.npos) { if (maxSplit != -1 && ((int) (container.size() + 1 )) == maxSplit) { container.emplace_back(source.substr(tokenBeginIndex)); break; } auto tokenEndIndex = source.find_first_of(delimiter, tokenBeginIndex); container.emplace_back(source.substr(tokenBeginIndex, tokenEndIndex - tokenBeginIndex)); tokenBeginIndex = tokenEndIndex; } if (container.empty()) { throw std::runtime_error{"No delimiter found in source: " + source}; } return container; } std::vector<std::string> rsplit(const std::string &source, const char *delimiter, int maxSplit) { if (source.empty()) throw std::runtime_error{"Source cannot be empty"}; std::string sequence = source; std::string::size_type tokenBeginIndex = 0; std::vector<std::string> container; while ((tokenBeginIndex = sequence.find_last_of(delimiter)) != sequence.npos) { if (maxSplit != -1 && ((int) (container.size() + 1 )) == maxSplit) { container.emplace_back(source.substr(0, tokenBeginIndex)); break; } container.emplace(container.begin(), source.substr(tokenBeginIndex + 1)); sequence = sequence.substr(0, tokenBeginIndex); } if (container.empty()) { throw std::runtime_error{"No delimiter found in source: " + source}; } return container; } std::string trimSuffix(const std::string &source, const std::string &suffix) { if (source.length() < suffix.length()) throw std::runtime_error{"Suffix cannot be longer than source"}; if (endsWith(source, suffix)) return source.substr(0, source.length() - suffix.length()); throw std::runtime_error{"Suffix '" + suffix + "' not found"}; } std::string trimPrefix(const std::string &source, const std::string &prefix) { if (source.length() < prefix.length()) throw std::runtime_error{"Prefix cannot be longer than source"}; if (startsWith(source, prefix)) return source.substr(prefix.length() - 1); throw std::runtime_error{"Prefix '" + prefix + "' not found"}; } std::string trim(const std::string &source) { size_t first = source.find_first_not_of(" \t"); if (first == source.npos) return ""; size_t last = source.find_last_not_of(" \t"); return source.substr(first, (last - first + 1)); } bool startsWith(const std::string & source, const std::string & toMatch) { return source.compare(0, toMatch.size(), toMatch) == 0; } bool endsWith(const std::string & source, const std::string & toMatch) { auto toMatchSize = toMatch.size(); return source.size() >= toMatchSize && source.compare( source.size() - toMatchSize, toMatchSize, toMatch) == 0; } } bool haveFilesSameContent(const char * filePath1, const char * filePath2) { static constexpr int BLOCK_SIZE = 4096; bool ret = false; int fd1 = -1; int fd2 = -1; do { if ((fd1 = open(filePath1, 0)) == -1) break; if ((fd2 = open(filePath2, 0)) == -1) break; auto len1 = lseek(fd1, 0, SEEK_END); auto len2 = lseek(fd2, 0, SEEK_END); if (len1 != len2) break; ret = true; if (len1 == 0) break; lseek(fd1, 0, SEEK_SET); lseek(fd2, 0, SEEK_SET); char buf1[BLOCK_SIZE], buf2[BLOCK_SIZE]; ssize_t readed; do { readed = read(fd1, buf1, BLOCK_SIZE); auto readed2 = read(fd2, buf2, BLOCK_SIZE); if (readed2 != readed || memcmp(buf1, buf2, readed) != 0) { ret = false; break; } } while (readed == BLOCK_SIZE); } while (false); if (fd1 != -1) close(fd1); if (fd2 != -1) close(fd2); return ret; } static bool saveFile(const char * filePath, const char * newFileContent, unsigned long newFileContentLen) { int fd = -1; if ((fd = open(filePath, O_WRONLY | O_CREAT | O_TRUNC, 0644)) == -1) return false; auto writtenSize = write(fd, newFileContent, newFileContentLen); close(fd); return (static_cast<unsigned long>(writtenSize) == newFileContentLen); } bool updateFile(const char * filePath, const char * newFileContent) { static constexpr int BLOCK_SIZE = 4096; int fd = -1; const char * tmpFileContent = newFileContent; auto newFileContentLen = strlen(newFileContent); if ((fd = open(filePath, O_RDONLY)) == -1) return saveFile(filePath, newFileContent, newFileContentLen); auto len = lseek(fd, 0, SEEK_END); if (len < 0 || (unsigned long)len != newFileContentLen) { close(fd); return saveFile(filePath, newFileContent, newFileContentLen); } // No need to update file when newFileContentLen and len of file == 0 if (newFileContentLen > 0) { lseek(fd, 0, SEEK_SET); char buf1[BLOCK_SIZE]; ssize_t readed; do { readed = read(fd, buf1, BLOCK_SIZE); if (readed < 0 && errno == EINTR) continue; if (readed < 0 || memcmp(buf1, tmpFileContent, readed) != 0) { close(fd); return saveFile(filePath, newFileContent, newFileContentLen); } tmpFileContent = tmpFileContent + BLOCK_SIZE; } while (readed == BLOCK_SIZE); } if (fd != -1) close(fd); return true; } namespace filesystem { bool exists(const std::string &name) { struct stat buffer; return stat(name.c_str(), &buffer) == 0; } bool isDIR(const std::string& dirPath) { struct stat buf; lstat(dirPath.c_str(), &buf); return S_ISDIR(buf.st_mode); } std::vector<std::string> getDirContent(const std::string &dirPath) { std::vector<std::string> content{}; struct dirent *ent; DIR *dir = opendir(dirPath.c_str()); if (dir != nullptr) { while ((ent = readdir(dir)) != nullptr) { if (strcmp(ent->d_name, "..") == 0 || strcmp(ent->d_name, ".") == 0 ) continue; auto fullPath = dirPath; if (!string::endsWith(fullPath, "/")) fullPath += "/"; fullPath += ent->d_name; content.emplace_back(fullPath); } closedir (dir); } return content; } void decompress(const char * inPath, const char * outPath, mode_t outMode, const char * compressType) { auto inFd = open(inPath, O_RDONLY); if (inFd == -1) throw std::runtime_error(tfm::format("Error opening %s: %s", inPath, strerror(errno))); if (!compressType) compressType = inPath; auto inFile = solv_xfopen_fd(compressType, inFd, "r"); if (inFile == NULL) { close(inFd); throw std::runtime_error(tfm::format("solv_xfopen_fd: Can't open stream for %s", inPath)); } auto outFd = open(outPath, O_WRONLY | O_CREAT | O_TRUNC, outMode); if (outFd == -1) { int err = errno; fclose(inFile); throw std::runtime_error(tfm::format("Error opening %s: %s", outPath, strerror(err))); } char buf[4096]; while (auto readBytes = fread(buf, 1, sizeof(buf), inFile)) { auto writtenBytes = write(outFd, buf, readBytes); if (writtenBytes == -1) { int err = errno; close(outFd); fclose(inFile); throw std::runtime_error(tfm::format("Error writing to %s: %s", outPath, strerror(err))); } if (writtenBytes != static_cast<int>(readBytes)) { close(outFd); fclose(inFile); throw std::runtime_error(tfm::format("Unknown error while writing to %s", outPath)); } } if (!feof(inFile)) { close(outFd); fclose(inFile); throw std::runtime_error(tfm::format("Unknown error while reading %s", inPath)); } close(outFd); fclose(inFile); } } namespace numeric { int random(const int min, const int max) { std::random_device rd; std::default_random_engine gen(rd()); std::uniform_int_distribution<int> dist(min, max); return dist(gen); } } } <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ // utils.cpp // Functions for creating Handles and tables // #include <utils.h> #include <PField.h> #include <stdlib.h> #include <assert.h> Handle createPFieldHandle(PField *pfield) { Handle handle = (Handle) malloc(sizeof(struct _handle)); if (handle) { handle->type = PFieldType; handle->ptr = (void *) pfield; #ifdef DEBUG printf("\tcreated Handle %p\n", handle); printf("\t\trefing PField %p\n", pfield); #endif pfield->ref(); handle->refcount = 0; } return handle; } Handle createInstHandle(Instrument *inst) { Handle handle = (Handle) malloc(sizeof(struct _handle)); if (handle) { handle->type = InstrumentPtrType; handle->ptr = (void *) inst; handle->refcount = 0; } return handle; } void unrefHandle(Handle h) { assert(h->refcount >= 0); #ifdef DEBUG printf("unrefHandle(%p): %d -> ", h, h->refcount); #endif --h->refcount; #ifdef DEBUG printf("%d\n", h->refcount); #endif if (h->refcount == 0 && h->type == PFieldType) { #ifdef DEBUG printf("\tfreeing Handle %p\n", h); h->refcount = 0xdeaddead; // for debugging printf("\tunrefing PField %p\n", h->ptr); #endif RefCounted::unref((PField *)h->ptr); free(h); } } <commit_msg>Moved assert after printf<commit_after>/* RTcmix - Copyright (C) 2004 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ // utils.cpp // Functions for creating Handles and tables // #include <utils.h> #include <PField.h> #include <stdlib.h> #include <assert.h> Handle createPFieldHandle(PField *pfield) { Handle handle = (Handle) malloc(sizeof(struct _handle)); if (handle) { handle->type = PFieldType; handle->ptr = (void *) pfield; #ifdef DEBUG printf("\tcreated Handle %p\n", handle); printf("\t\trefing PField %p\n", pfield); #endif pfield->ref(); handle->refcount = 0; } return handle; } Handle createInstHandle(Instrument *inst) { Handle handle = (Handle) malloc(sizeof(struct _handle)); if (handle) { handle->type = InstrumentPtrType; handle->ptr = (void *) inst; handle->refcount = 0; } return handle; } void unrefHandle(Handle h) { #ifdef DEBUG printf("unrefHandle(%p): %d -> ", h, h->refcount); #endif assert(h->refcount >= 0); --h->refcount; #ifdef DEBUG printf("%d\n", h->refcount); #endif if (h->refcount == 0 && h->type == PFieldType) { #ifdef DEBUG printf("\tfreeing Handle %p\n", h); h->refcount = 0xdeaddead; // for debugging printf("\tunrefing PField %p\n", h->ptr); #endif RefCounted::unref((PField *)h->ptr); free(h); } } <|endoftext|>
<commit_before>#include "data-course.hpp" using namespace std; void Course::init(string identifier) { copy(getCourse(identifier)); } void Course::copy(const Course& c) { id = c.id; number = c.number; title = c.title; description = c.description; section = c.section; majors = c.majors; department = c.department; concentrations = c.concentrations; conversations = c.conversations; professor = c.professor; half_semester = c.half_semester; pass_fail = c.pass_fail; credits = c.credits; location = c.location; lab = c.lab; geneds = c.geneds; for (int i = 0; i < 7; ++i){ days[i] = c.days[i]; time[i] = c.time[i]; } } Course::Course() { } Course::Course(string str) { init(str); } Course::Course(const Course& c) { copy(c); } Course& Course::operator = (const Course &c) { copy(c); return *this; } Course::Course(istream &is) { if (!is) return; string tmpLine; getline(is, tmpLine); // read in so we can do things with it. vector<string> record = split(tmpLine, ','); for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) { *i = removeAllQuotes(*i); *i = removeTrailingSlashes(*i); } /* cout << record.at(0) << ", "; cout << record.at(1) << ", "; cout << record.at(2) << ", "; cout << record.at(3) << ", "; cout << record.at(4) << ", "; cout << record.at(5) << ", "; cout << record.at(6) << ", "; cout << record.at(7) << ", "; cout << record.at(8) << ", "; cout << record.at(9) << ", "; cout << record.at(10) << ", "; cout << record.at(11) << ", "; if (record.size() == 13) cout << record.at(12) << endl; */ // Ignore the first column; // record.at(0); // so, the *first* column (that we care about) has the course id, id = record.at(1); parseID(id); // Second column has the section, // note that this breaks if it is a string. // it breaks after PHYS 125 lab. // it also doesn't output on anything. section = record.at(2)[0]; // Third holds the lab boolean, if (record.at(3).empty()) lab = false; else lab = true; // while Fourth contains the title of the course; title = record.at(4); cleanTitle(); // Fifth hands over the length (half semester or not) // it's actually an int that tells us how many times the course is offered per semester. half_semester = stringToInt(record.at(5)); if (half_semester != 0 && half_semester != 1 && half_semester != 2) half_semester = 0; // Sixth tells us the number of credits, credits = stringToFloat(record.at(6)); // Seventh shows us if it can be taken pass/no-pass, if (record.at(7) == "Y") pass_fail = true; else pass_fail = false; // while Eighth gives us the GEs of the course, // GEreqs = record.at(8); // and Nine spits out the days and times; // Times = record.at(9); // Ten holds the location, location = record.at(10); location = deDoubleString(location); // and Eleven knows who teaches. if (record.size() == 13) { string profLastName = record.at(11); string profFirstName = record.at(12); profFirstName.erase(0, 1); // remove the extra space from the start of the name professor = profFirstName + " " + profLastName; } else { professor = record.at(11); } } void Course::cleanTitle() { // TODO: Refactor this to work on strings. vector<string> badEndings, badBeginnings; badEndings.push_back("Prerequisite"); badEndings.push_back("Prerequsiite"); badEndings.push_back("This course has class"); badEndings.push_back("This course is open to "); badEndings.push_back("First-Year Students may register only"); badEndings.push_back("Open to "); badEndings.push_back("Especially for "); badEndings.push_back("Registration by permission of instructor only."); badEndings.push_back("Permission of instructor required."); badEndings.push_back("Not open to first-year students."); badEndings.push_back("Film screenings"); badEndings.push_back("Open only to "); badEndings.push_back("This course has been canceled."); badEndings.push_back("This course has been cancelled."); badEndings.push_back("Open only to seniors"); badEndings.push_back("Closed during web registration."); badEndings.push_back("During course submission process"); badEndings.push_back("Taught in English."); badEndings.push_back("Closed to First-Year Students."); badEndings.push_back("Closed to first-year students."); badEndings.push_back("New course"); badEndings.push_back("This course does"); badEndings.push_back("This course open to seniors only."); badEndings.push_back("This lab has been canceled."); badEndings.push_back("Permission of the instructor"); badEndings.push_back("Registration restricted"); badEndings.push_back("Students in " + department[0].getFullName() + " " + tostring(number)); badEndings.push_back("Students in " + department[0].getName() + " " + tostring(number)); badBeginnings.push_back("Top: "); badBeginnings.push_back("Sem: "); badBeginnings.push_back("Res: "); for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i) title = removeTrailingText(title, *i); for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i) title = removeStartingText(title, *i); } void Course::parseID(string str) { // Get the number of the course, aka the last three slots. stringstream(str.substr(str.size() - 3)) >> number; // Check if it's one of those dastardly "split courses". string dept = str.substr(0,str.size()-3); if (str.find('/') != string::npos) { department.push_back(Department(dept.substr(0,2))); department.push_back(Department(dept.substr(3,2))); } else { department.push_back(Department(dept)); } updateID(); } void Course::updateID() { string dept; for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) { dept += i->getName(); if (department.size() > 1) dept += "/"; } id = dept + " " + tostring(number) + section; } string Course::getID() { return id; } ostream& Course::getData(ostream &os) { os << id << " - "; os << title << " | "; if (professor.length() > 0 && professor != " ") os << professor; return os; } void Course::showAll() { cout << id << section << endl; cout << "Title: " << title << endl; cout << "Professor: " << professor << endl; cout << "Lab? " << lab << endl; cout << "Half-semester? " << half_semester << endl; cout << "Credits: " << credits << endl; cout << "Pass/Fail? " << pass_fail << endl; cout << "Location: " << location << endl; cout << endl; } ostream &operator<<(ostream &os, Course &item) { return item.getData(os); } void Course::display() { if (this == 0) cout << *this << endl; } Course getCourse(string id) { for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i) { if (i->getID() == id) { return *i; } } return Course(); } <commit_msg>Finish implementing operator= for Course<commit_after>#include "data-course.hpp" using namespace std; void Course::init(string identifier) { copy(getCourse(identifier)); } void Course::copy(const Course& c) { id = c.id; number = c.number; title = c.title; description = c.description; section = c.section; majors = c.majors; department = c.department; concentrations = c.concentrations; conversations = c.conversations; professor = c.professor; half_semester = c.half_semester; pass_fail = c.pass_fail; credits = c.credits; location = c.location; lab = c.lab; geneds = c.geneds; for (int i = 0; i < 7; ++i){ days[i] = c.days[i]; time[i] = c.time[i]; } } Course::Course() { } Course::Course(string str) { init(str); } Course::Course(const Course& c) { copy(c); } Course& Course::operator = (const Course &c) { if (this == &c) return *this; copy(c); return *this; } Course::Course(istream &is) { if (!is) return; string tmpLine; getline(is, tmpLine); // read in so we can do things with it. vector<string> record = split(tmpLine, ','); for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) { *i = removeAllQuotes(*i); *i = removeTrailingSlashes(*i); } /* cout << record.at(0) << ", "; cout << record.at(1) << ", "; cout << record.at(2) << ", "; cout << record.at(3) << ", "; cout << record.at(4) << ", "; cout << record.at(5) << ", "; cout << record.at(6) << ", "; cout << record.at(7) << ", "; cout << record.at(8) << ", "; cout << record.at(9) << ", "; cout << record.at(10) << ", "; cout << record.at(11) << ", "; if (record.size() == 13) cout << record.at(12) << endl; */ // Ignore the first column; // record.at(0); // so, the *first* column (that we care about) has the course id, id = record.at(1); parseID(id); // Second column has the section, // note that this breaks if it is a string. // it breaks after PHYS 125 lab. // it also doesn't output on anything. section = record.at(2)[0]; // Third holds the lab boolean, if (record.at(3).empty()) lab = false; else lab = true; // while Fourth contains the title of the course; title = record.at(4); cleanTitle(); // Fifth hands over the length (half semester or not) // it's actually an int that tells us how many times the course is offered per semester. half_semester = stringToInt(record.at(5)); if (half_semester != 0 && half_semester != 1 && half_semester != 2) half_semester = 0; // Sixth tells us the number of credits, credits = stringToFloat(record.at(6)); // Seventh shows us if it can be taken pass/no-pass, if (record.at(7) == "Y") pass_fail = true; else pass_fail = false; // while Eighth gives us the GEs of the course, // GEreqs = record.at(8); // and Nine spits out the days and times; // Times = record.at(9); // Ten holds the location, location = record.at(10); location = deDoubleString(location); // and Eleven knows who teaches. if (record.size() == 13) { string profLastName = record.at(11); string profFirstName = record.at(12); profFirstName.erase(0, 1); // remove the extra space from the start of the name professor = profFirstName + " " + profLastName; } else { professor = record.at(11); } } void Course::cleanTitle() { // TODO: Refactor this to work on strings. vector<string> badEndings, badBeginnings; badEndings.push_back("Prerequisite"); badEndings.push_back("Prerequsiite"); badEndings.push_back("This course has class"); badEndings.push_back("This course is open to "); badEndings.push_back("First-Year Students may register only"); badEndings.push_back("Open to "); badEndings.push_back("Especially for "); badEndings.push_back("Registration by permission of instructor only."); badEndings.push_back("Permission of instructor required."); badEndings.push_back("Not open to first-year students."); badEndings.push_back("Film screenings"); badEndings.push_back("Open only to "); badEndings.push_back("This course has been canceled."); badEndings.push_back("This course has been cancelled."); badEndings.push_back("Open only to seniors"); badEndings.push_back("Closed during web registration."); badEndings.push_back("During course submission process"); badEndings.push_back("Taught in English."); badEndings.push_back("Closed to First-Year Students."); badEndings.push_back("Closed to first-year students."); badEndings.push_back("New course"); badEndings.push_back("This course does"); badEndings.push_back("This course open to seniors only."); badEndings.push_back("This lab has been canceled."); badEndings.push_back("Permission of the instructor"); badEndings.push_back("Registration restricted"); badEndings.push_back("Students in " + department[0].getFullName() + " " + tostring(number)); badEndings.push_back("Students in " + department[0].getName() + " " + tostring(number)); badBeginnings.push_back("Top: "); badBeginnings.push_back("Sem: "); badBeginnings.push_back("Res: "); for (vector<string>::iterator i=badEndings.begin(); i != badEndings.end(); ++i) title = removeTrailingText(title, *i); for (vector<string>::iterator i=badBeginnings.begin(); i != badBeginnings.end(); ++i) title = removeStartingText(title, *i); } void Course::parseID(string str) { // Get the number of the course, aka the last three slots. stringstream(str.substr(str.size() - 3)) >> number; // Check if it's one of those dastardly "split courses". string dept = str.substr(0,str.size()-3); if (str.find('/') != string::npos) { department.push_back(Department(dept.substr(0,2))); department.push_back(Department(dept.substr(3,2))); } else { department.push_back(Department(dept)); } updateID(); } void Course::updateID() { string dept; for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) { dept += i->getName(); if (department.size() > 1) dept += "/"; } id = dept + " " + tostring(number) + section; } string Course::getID() { return id; } ostream& Course::getData(ostream &os) { os << id << " - "; os << title << " | "; if (professor.length() > 0 && professor != " ") os << professor; return os; } void Course::showAll() { cout << id << section << endl; cout << "Title: " << title << endl; cout << "Professor: " << professor << endl; cout << "Lab? " << lab << endl; cout << "Half-semester? " << half_semester << endl; cout << "Credits: " << credits << endl; cout << "Pass/Fail? " << pass_fail << endl; cout << "Location: " << location << endl; cout << endl; } ostream &operator<<(ostream &os, Course &item) { return item.getData(os); } void Course::display() { if (this == 0) cout << *this << endl; } Course getCourse(string id) { for (vector<Course>::iterator i = all_courses.begin(); i != all_courses.end(); ++i) { if (i->getID() == id) { return *i; } } return Course(); } <|endoftext|>
<commit_before>#ifndef __Data_course__ #define __Data_course__ #include "data-general.hpp" #include "data-major.hpp" #include "data-department.hpp" using namespace std; class Course { protected: string ID; int number; string title; string description; char section; vector<Major> majors; Department* department; string concentrations; string conversations; string professor; int half_semester; bool pass_fail; float credits; string location; bool lab; GenEd* geneds; bool days[7]; float time[7]; public: Course(istream &is) { if (!is) return; string tmpLine; getline(is, tmpLine); vector<string> record = split(tmpLine, ','); for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) *i=removeAllQuotes(*i); // Ignore the first column; record.at(0); // Second column has the course ID, //number = stringToInt(record.at(1)); ID = record.at(1); number = parseID(ID); // Third column has the section, section = record.at(2)[0]; // Fourth holds the lab boolean, if (record.at(3).empty()) lab = false; else lab = true; // while Fifth contains the title of the course; title = record.at(4); // Sixth hands over the length (half semester or not) // it's actually an int that tells us how many times the course is offered per semester. half_semester = stringToInt(record.at(5)); // Seventh tells us the number of credits, credits = stringToFloat(record.at(6)); // Eighth shows us if it can be taken pass/no-pass, if (record.at(7) == "Y") pass_fail = true; else pass_fail = false; // while Nine gives us the GEs of the course, // GEreqs = record.at(9); // and Ten spits out the days and times; // Times = record.at(10); // Eleven holds the location, location = record.at(11); // and Twelve knows who teaches. professor = record.at(12); } int parseID(string s) { // return stringToInt(s.substr(s.find(' ')+1,3)); // Xandra, what is this? string tempDept; unsigned int found = tempDept.find('/'); tempDept = s.substr(0,s.find(' ')-1); if (found != s.npos) { department = new Department[2]; string tmp = tempDept.substr(0,2); if ( tmp == "AS" ) department[0] = ASIAN; else if ( tmp == "BI" ) department[0] = BIO; else if ( tmp == "CH" ) department[0] = CHEM; else if ( tmp == "ES" ) department[0] = ENVST; else if ( tmp == "HI" ) department[0] = HIST; else if ( tmp == "RE" ) department[0] = REL; tmp = tempDept.substr(3,2); if ( tmp == "AS" ) department[1] = ASIAN; else if ( tmp == "BI" ) department[1] = BIO; else if ( tmp == "CH" ) department[1] = CHEM; else if ( tmp == "ES" ) department[1] = ENVST; else if ( tmp == "HI" ) department[1] = HIST; else if ( tmp == "RE" ) department[1] = REL; } else { if ( tempDept == "AFAM" ) department = AFAM; else if ( tempDept == "ALSO" ) department = ALSO; else if ( tempDept == "AMCON" ) department = AMCON; else if ( tempDept == "AMST" ) department = AMST; else if ( tempDept == "ARMS" ) department = ARMS; else if ( tempDept == "ART" ) department = ART; else if ( tempDept == "ASIAN" ) department = ASIAN; else if ( tempDept == "BIO" ) department = BIO; else if ( tempDept == "BMOLS" ) department = BMOLS; else if ( tempDept == "CHEM" ) department = CHEM; else if ( tempDept == "CHIN" ) department = CHIN; else if ( tempDept == "CLASS" ) department = CLASS; else if ( tempDept == "CSCI" ) department = CSCI; else if ( tempDept == "DANCE" ) department = DANCE; else if ( tempDept == "ECON" ) department = ECON; else if ( tempDept == "EDUC" ) department = EDUC; else if ( tempDept == "ENGL" ) department = ENGL; else if ( tempDept == "ENVST" ) department = ENVST; else if ( tempDept == "ESAC" ) department = ESAC; else if ( tempDept == "ESTH" ) department = ESTH; else if ( tempDept == "FAMST" ) department = FAMST; else if ( tempDept == "FILM" ) department = FILM; else if ( tempDept == "FREN" ) department = FREN; else if ( tempDept == "GCON" ) department = GCON; else if ( tempDept == "GERM" ) department = GERM; else if ( tempDept == "GREEK" ) department = GREEK; else if ( tempDept == "HIST" ) department = HIST; else if ( tempDept == "HSPST" ) department = HSPST; else if ( tempDept == "ID" ) department = ID; else if ( tempDept == "IDFA" ) department = IDFA; else if ( tempDept == "INTD" ) department = INTD; else if ( tempDept == "IS" ) department = IS; else if ( tempDept == "JAPAN" ) department = JAPAN; else if ( tempDept == "LATIN" ) department = LATIN; else if ( tempDept == "MATH" ) department = MATH; else if ( tempDept == "MEDIA" ) department = MEDIA; else if ( tempDept == "MEDVL" ) department = MEDVL; else if ( tempDept == "MGMT" ) department = MGMT; else if ( tempDept == "MUSIC" ) department = MUSIC; else if ( tempDept == "MUSPF" ) department = MUSPF; else if ( tempDept == "NEURO" ) department = NEURO; else if ( tempDept == "NORW" ) department = NORW; else if ( tempDept == "NURS" ) department = NURS; else if ( tempDept == "PHIL" ) department = PHIL; else if ( tempDept == "PHYS" ) department = PHYS; else if ( tempDept == "PSCI" ) department = PSCI; else if ( tempDept == "PSYCH" ) department = PSYCH; else if ( tempDept == "REL" ) department = REL; else if ( tempDept == "RUSSN" ) department = RUSSN; else if ( tempDept == "SCICN" ) department = SCICN; else if ( tempDept == "SOAN" ) department = SOAN; else if ( tempDept == "SPAN" ) department = SPAN; else if ( tempDept == "STAT" ) department = STAT; else if ( tempDept == "SWRK" ) department = SWRK; else if ( tempDept == "THEAT" ) department = THEAT; else if ( tempDept == "WMGST" ) department = WMGST; else if ( tempDept == "WRIT" ) department = WRIT; } } void updateID() { string dept; for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) dept += i->getName(); ID = dept + tostring(number) + section; } string getID() { return ID; } ostream& getData(ostream &os) { os << ID << section << " "; os << title << "/"; /*for (vector<Instructor>::iterator i = professor.begin(); i != professor.end(); ++i) { os << i->name << " "; }*/ return os; } void display(); }; ostream &operator<<(ostream &os, Course &item) { return item.getData(os); } void Course::display() { if(this==0) cout << *this << endl; } #endif <commit_msg>Add a line break in data-course<commit_after>#ifndef __Data_course__ #define __Data_course__ #include "data-general.hpp" #include "data-major.hpp" #include "data-department.hpp" using namespace std; class Course { protected: string ID; int number; string title; string description; char section; vector<Major> majors; Department* department; string concentrations; string conversations; string professor; int half_semester; bool pass_fail; float credits; string location; bool lab; GenEd* geneds; bool days[7]; float time[7]; public: Course(istream &is) { if (!is) return; string tmpLine; getline(is, tmpLine); vector<string> record = split(tmpLine, ','); for (vector<string>::iterator i=record.begin(); i != record.end(); ++i) *i=removeAllQuotes(*i); // Ignore the first column; record.at(0); // Second column has the course ID, //number = stringToInt(record.at(1)); ID = record.at(1); number = parseID(ID); // Third column has the section, section = record.at(2)[0]; // Fourth holds the lab boolean, if (record.at(3).empty()) lab = false; else lab = true; // while Fifth contains the title of the course; title = record.at(4); // Sixth hands over the length (half semester or not) // it's actually an int that tells us how many times the course is offered per semester. half_semester = stringToInt(record.at(5)); // Seventh tells us the number of credits, credits = stringToFloat(record.at(6)); // Eighth shows us if it can be taken pass/no-pass, if (record.at(7) == "Y") pass_fail = true; else pass_fail = false; // while Nine gives us the GEs of the course, // GEreqs = record.at(9); // and Ten spits out the days and times; // Times = record.at(10); // Eleven holds the location, location = record.at(11); // and Twelve knows who teaches. professor = record.at(12); } int parseID(string s) { // return stringToInt(s.substr(s.find(' ')+1,3)); // Xandra, what is this? string tempDept; unsigned int found = tempDept.find('/'); tempDept = s.substr(0,s.find(' ')-1); if (found != s.npos) { department = new Department[2]; string tmp = tempDept.substr(0,2); if ( tmp == "AS" ) department[0] = ASIAN; else if ( tmp == "BI" ) department[0] = BIO; else if ( tmp == "CH" ) department[0] = CHEM; else if ( tmp == "ES" ) department[0] = ENVST; else if ( tmp == "HI" ) department[0] = HIST; else if ( tmp == "RE" ) department[0] = REL; tmp = tempDept.substr(3,2); if ( tmp == "AS" ) department[1] = ASIAN; else if ( tmp == "BI" ) department[1] = BIO; else if ( tmp == "CH" ) department[1] = CHEM; else if ( tmp == "ES" ) department[1] = ENVST; else if ( tmp == "HI" ) department[1] = HIST; else if ( tmp == "RE" ) department[1] = REL; } else { if ( tempDept == "AFAM" ) department = AFAM; else if ( tempDept == "ALSO" ) department = ALSO; else if ( tempDept == "AMCON" ) department = AMCON; else if ( tempDept == "AMST" ) department = AMST; else if ( tempDept == "ARMS" ) department = ARMS; else if ( tempDept == "ART" ) department = ART; else if ( tempDept == "ASIAN" ) department = ASIAN; else if ( tempDept == "BIO" ) department = BIO; else if ( tempDept == "BMOLS" ) department = BMOLS; else if ( tempDept == "CHEM" ) department = CHEM; else if ( tempDept == "CHIN" ) department = CHIN; else if ( tempDept == "CLASS" ) department = CLASS; else if ( tempDept == "CSCI" ) department = CSCI; else if ( tempDept == "DANCE" ) department = DANCE; else if ( tempDept == "ECON" ) department = ECON; else if ( tempDept == "EDUC" ) department = EDUC; else if ( tempDept == "ENGL" ) department = ENGL; else if ( tempDept == "ENVST" ) department = ENVST; else if ( tempDept == "ESAC" ) department = ESAC; else if ( tempDept == "ESTH" ) department = ESTH; else if ( tempDept == "FAMST" ) department = FAMST; else if ( tempDept == "FILM" ) department = FILM; else if ( tempDept == "FREN" ) department = FREN; else if ( tempDept == "GCON" ) department = GCON; else if ( tempDept == "GERM" ) department = GERM; else if ( tempDept == "GREEK" ) department = GREEK; else if ( tempDept == "HIST" ) department = HIST; else if ( tempDept == "HSPST" ) department = HSPST; else if ( tempDept == "ID" ) department = ID; else if ( tempDept == "IDFA" ) department = IDFA; else if ( tempDept == "INTD" ) department = INTD; else if ( tempDept == "IS" ) department = IS; else if ( tempDept == "JAPAN" ) department = JAPAN; else if ( tempDept == "LATIN" ) department = LATIN; else if ( tempDept == "MATH" ) department = MATH; else if ( tempDept == "MEDIA" ) department = MEDIA; else if ( tempDept == "MEDVL" ) department = MEDVL; else if ( tempDept == "MGMT" ) department = MGMT; else if ( tempDept == "MUSIC" ) department = MUSIC; else if ( tempDept == "MUSPF" ) department = MUSPF; else if ( tempDept == "NEURO" ) department = NEURO; else if ( tempDept == "NORW" ) department = NORW; else if ( tempDept == "NURS" ) department = NURS; else if ( tempDept == "PHIL" ) department = PHIL; else if ( tempDept == "PHYS" ) department = PHYS; else if ( tempDept == "PSCI" ) department = PSCI; else if ( tempDept == "PSYCH" ) department = PSYCH; else if ( tempDept == "REL" ) department = REL; else if ( tempDept == "RUSSN" ) department = RUSSN; else if ( tempDept == "SCICN" ) department = SCICN; else if ( tempDept == "SOAN" ) department = SOAN; else if ( tempDept == "SPAN" ) department = SPAN; else if ( tempDept == "STAT" ) department = STAT; else if ( tempDept == "SWRK" ) department = SWRK; else if ( tempDept == "THEAT" ) department = THEAT; else if ( tempDept == "WMGST" ) department = WMGST; else if ( tempDept == "WRIT" ) department = WRIT; } } void updateID() { string dept; for (std::vector<Department>::iterator i = department.begin(); i != department.end(); ++i) dept += i->getName(); ID = dept + tostring(number) + section; } string getID() { return ID; } ostream& getData(ostream &os) { os << ID << section << " "; os << title << "/"; /*for (vector<Instructor>::iterator i = professor.begin(); i != professor.end(); ++i) { os << i->name << " "; }*/ return os; } void display(); }; ostream &operator<<(ostream &os, Course &item) { return item.getData(os); } void Course::display() { if(this==0) cout << *this << endl; } #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkImporter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImporter.h" #include "vtkRendererCollection.h" #include "vtkRenderWindow.h" vtkCxxSetObjectMacro(vtkImporter,RenderWindow,vtkRenderWindow); vtkImporter::vtkImporter () { this->Renderer = NULL; this->RenderWindow = NULL; } vtkImporter::~vtkImporter () { this->SetRenderWindow(NULL); if (this->Renderer) { this->Renderer->UnRegister( NULL ); this->Renderer = NULL; } } void vtkImporter::ReadData() { // this->Import actors, cameras, lights and properties this->ImportActors (this->Renderer); this->ImportCameras (this->Renderer); this->ImportLights (this->Renderer); this->ImportProperties (this->Renderer); } void vtkImporter::Read () { vtkRenderer *renderer; // if there is no render window, create one if (this->RenderWindow == NULL) { vtkDebugMacro( <<"Creating a RenderWindow\n"); this->RenderWindow = vtkRenderWindow::New (); } // Get the first renderer in the render window renderer = this->RenderWindow->GetRenderers()->GetFirstRenderer(); if (renderer == NULL) { vtkDebugMacro( <<"Creating a Renderer\n"); this->Renderer = vtkRenderer::New (); renderer = this->Renderer; this->RenderWindow->AddRenderer (renderer); } else { this->Renderer = renderer; this->Renderer->Register( this ); } if (this->ImportBegin ()) { this->ReadData(); this->ImportEnd(); } } void vtkImporter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Render Window: "; if ( this->RenderWindow ) { os << this->RenderWindow << "\n"; } else { os << "(none)\n"; } os << indent << "Renderer: "; if ( this->Renderer ) { os << this->Renderer << "\n"; } else { os << "(none)\n"; } } <commit_msg>BUG: Memory leak.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkImporter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkImporter.h" #include "vtkRendererCollection.h" #include "vtkRenderWindow.h" vtkCxxSetObjectMacro(vtkImporter,RenderWindow,vtkRenderWindow); vtkImporter::vtkImporter () { this->Renderer = NULL; this->RenderWindow = NULL; } vtkImporter::~vtkImporter () { this->SetRenderWindow(NULL); if (this->Renderer) { this->Renderer->UnRegister( NULL ); this->Renderer = NULL; } } void vtkImporter::ReadData() { // this->Import actors, cameras, lights and properties this->ImportActors (this->Renderer); this->ImportCameras (this->Renderer); this->ImportLights (this->Renderer); this->ImportProperties (this->Renderer); } void vtkImporter::Read () { vtkRenderer *renderer; // if there is no render window, create one if (this->RenderWindow == NULL) { vtkDebugMacro( <<"Creating a RenderWindow\n"); this->RenderWindow = vtkRenderWindow::New (); } // Get the first renderer in the render window renderer = this->RenderWindow->GetRenderers()->GetFirstRenderer(); if (renderer == NULL) { vtkDebugMacro( <<"Creating a Renderer\n"); this->Renderer = vtkRenderer::New (); renderer = this->Renderer; this->RenderWindow->AddRenderer (renderer); this->Renderer->UnRegister(NULL); } else { this->Renderer = renderer; this->Renderer->Register( this ); } if (this->ImportBegin ()) { this->ReadData(); this->ImportEnd(); } } void vtkImporter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "Render Window: "; if ( this->RenderWindow ) { os << this->RenderWindow << "\n"; } else { os << "(none)\n"; } os << indent << "Renderer: "; if ( this->Renderer ) { os << this->Renderer << "\n"; } else { os << "(none)\n"; } } <|endoftext|>
<commit_before>/* * Shared memory for sharing data between worker processes. * * author: Max Kellermann <[email protected]> */ #include "shm.hxx" #include "system/Error.hxx" #include "util/RefCount.hxx" #include <inline/poison.h> #include <inline/list.h> #include <daemon/log.h> #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <assert.h> #include <stdint.h> #include <sys/mman.h> #include <errno.h> #include <string.h> struct page { struct list_head siblings; unsigned num_pages; uint8_t *data; }; struct shm { RefCount ref; const size_t page_size; const unsigned num_pages; /** this lock protects the linked list */ boost::interprocess::interprocess_mutex mutex; struct list_head available; struct page pages[1]; shm(size_t _page_size, unsigned _num_pages) :page_size(_page_size), num_pages(_num_pages) { ref.Init(); list_init(&available); list_add(&pages[0].siblings, &available); pages[0].num_pages = num_pages; pages[0].data = GetData(); } static unsigned CalcHeaderPages(size_t page_size, unsigned num_pages) { size_t header_size = sizeof(struct shm) + (num_pages - 1) * sizeof(struct page); return (header_size + page_size - 1) / page_size; } unsigned CalcHeaderPages() const { return CalcHeaderPages(page_size, num_pages); } uint8_t *At(size_t offset) { return (uint8_t *)this + offset; } uint8_t *GetData() { return At(page_size * CalcHeaderPages()); } }; struct shm * shm_new(size_t page_size, unsigned num_pages) { assert(page_size >= sizeof(size_t)); assert(num_pages > 0); const unsigned header_pages = shm::CalcHeaderPages(page_size, num_pages); void *p = mmap(nullptr, page_size * (header_pages + num_pages), PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0); if (p == (void *)-1) throw MakeErrno("mmap() failed"); return ::new(p) struct shm(page_size, num_pages); } void shm_ref(struct shm *shm) { assert(shm != nullptr); shm->ref.Get(); } void shm_close(struct shm *shm) { unsigned header_pages; int ret; assert(shm != nullptr); if (shm->ref.Put()) shm->~shm(); header_pages = shm->CalcHeaderPages(); ret = munmap(shm, shm->page_size * (header_pages + shm->num_pages)); if (ret < 0) daemon_log(1, "munmap() failed: %s\n", strerror(errno)); } size_t shm_page_size(const struct shm *shm) { return shm->page_size; } static struct page * shm_find_available(struct shm *shm, unsigned num_pages) { for (struct page *page = (struct page *)shm->available.next; &page->siblings != &shm->available; page = (struct page *)page->siblings.next) if (page->num_pages >= num_pages) return page; return nullptr; } static struct page * shm_split_page(const struct shm *shm, struct page *page, unsigned num_pages) { assert(page->num_pages > num_pages); page->num_pages -= num_pages; page[page->num_pages].data = page->data + shm->page_size * page->num_pages; page += page->num_pages; page->num_pages = num_pages; return page; } void * shm_alloc(struct shm *shm, unsigned num_pages) { assert(num_pages > 0); boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(shm->mutex); struct page *page = shm_find_available(shm, num_pages); if (page == nullptr) { return nullptr; } assert(page->num_pages >= num_pages); page = (struct page *)shm->available.next; if (page->num_pages == num_pages) { list_remove(&page->siblings); lock.unlock(); poison_undefined(page->data, shm->page_size * num_pages); return page->data; } else { page = shm_split_page(shm, page, num_pages); lock.unlock(); poison_undefined(page->data, shm->page_size * num_pages); return page->data; } } static unsigned shm_page_number(struct shm *shm, const void *p) { ptrdiff_t difference = (const uint8_t *)p - shm->GetData(); unsigned page_number = difference / shm->page_size; assert(difference % shm->page_size == 0); assert(page_number < shm->num_pages); return page_number; } /** merge this page with its adjacent pages if possible, to create bigger "available" areas */ static void shm_merge(struct shm *shm, struct page *page) { unsigned page_number = shm_page_number(shm, page->data); /* merge with previous page? */ struct page *other = (struct page *)page->siblings.prev; if (&other->siblings != &shm->available && shm_page_number(shm, other->data) + other->num_pages == page_number) { other->num_pages += page->num_pages; list_remove(&page->siblings); page = other; } /* merge with next page? */ other = (struct page *)page->siblings.next; if (&other->siblings != &shm->available && page_number + page->num_pages == shm_page_number(shm, other->data)) { page->num_pages += other->num_pages; list_remove(&other->siblings); } } void shm_free(struct shm *shm, const void *p) { unsigned page_number = shm_page_number(shm, p); struct page *page = &shm->pages[page_number]; struct page *prev; poison_noaccess(page->data, shm->page_size * page->num_pages); boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(shm->mutex); for (prev = (struct page *)&shm->available; prev->siblings.next != &shm->available; prev = (struct page *)prev->siblings.next) { } list_add(&page->siblings, &prev->siblings); shm_merge(shm, page); } <commit_msg>shm/shm: move more code into the struct<commit_after>/* * Shared memory for sharing data between worker processes. * * author: Max Kellermann <[email protected]> */ #include "shm.hxx" #include "system/Error.hxx" #include "util/RefCount.hxx" #include <inline/poison.h> #include <inline/list.h> #include <daemon/log.h> #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <assert.h> #include <stdint.h> #include <sys/mman.h> #include <errno.h> #include <string.h> struct page { struct list_head siblings; unsigned num_pages; uint8_t *data; }; struct shm { RefCount ref; const size_t page_size; const unsigned num_pages; /** this lock protects the linked list */ boost::interprocess::interprocess_mutex mutex; struct list_head available; struct page pages[1]; shm(size_t _page_size, unsigned _num_pages) :page_size(_page_size), num_pages(_num_pages) { ref.Init(); list_init(&available); list_add(&pages[0].siblings, &available); pages[0].num_pages = num_pages; pages[0].data = GetData(); } static unsigned CalcHeaderPages(size_t page_size, unsigned num_pages) { size_t header_size = sizeof(struct shm) + (num_pages - 1) * sizeof(struct page); return (header_size + page_size - 1) / page_size; } unsigned CalcHeaderPages() const { return CalcHeaderPages(page_size, num_pages); } uint8_t *At(size_t offset) { return (uint8_t *)this + offset; } const uint8_t *At(size_t offset) const { return (const uint8_t *)this + offset; } uint8_t *GetData() { return At(page_size * CalcHeaderPages()); } const uint8_t *GetData() const { return At(page_size * CalcHeaderPages()); } unsigned PageNumber(const void *p) const { ptrdiff_t difference = (const uint8_t *)p - GetData(); unsigned page_number = difference / page_size; assert(difference % page_size == 0); assert(page_number < num_pages); return page_number; } struct page *FindAvailable(unsigned want_pages); struct page *SplitPage(struct page *page, unsigned want_pages); /** * Merge this page with its adjacent pages if possible, to create * bigger "available" areas. */ void Merge(struct page *page); void *Allocate(unsigned want_pages); void Free(const void *p); }; struct shm * shm_new(size_t page_size, unsigned num_pages) { assert(page_size >= sizeof(size_t)); assert(num_pages > 0); const unsigned header_pages = shm::CalcHeaderPages(page_size, num_pages); void *p = mmap(nullptr, page_size * (header_pages + num_pages), PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0); if (p == (void *)-1) throw MakeErrno("mmap() failed"); return ::new(p) struct shm(page_size, num_pages); } void shm_ref(struct shm *shm) { assert(shm != nullptr); shm->ref.Get(); } void shm_close(struct shm *shm) { unsigned header_pages; int ret; assert(shm != nullptr); if (shm->ref.Put()) shm->~shm(); header_pages = shm->CalcHeaderPages(); ret = munmap(shm, shm->page_size * (header_pages + shm->num_pages)); if (ret < 0) daemon_log(1, "munmap() failed: %s\n", strerror(errno)); } size_t shm_page_size(const struct shm *shm) { return shm->page_size; } struct page * shm::FindAvailable(unsigned want_pages) { for (struct page *page = (struct page *)available.next; &page->siblings != &available; page = (struct page *)page->siblings.next) if (page->num_pages >= want_pages) return page; return nullptr; } struct page * shm::SplitPage(struct page *page, unsigned want_pages) { assert(page->num_pages > want_pages); page->num_pages -= want_pages; page[page->num_pages].data = page->data + page_size * page->num_pages; page += page->num_pages; page->num_pages = want_pages; return page; } void * shm::Allocate(unsigned want_pages) { assert(want_pages > 0); boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(mutex); struct page *page = FindAvailable(want_pages); if (page == nullptr) { return nullptr; } assert(page->num_pages >= want_pages); page = (struct page *)available.next; if (page->num_pages == want_pages) { list_remove(&page->siblings); lock.unlock(); poison_undefined(page->data, page_size * want_pages); return page->data; } else { page = SplitPage(page, want_pages); lock.unlock(); poison_undefined(page->data, page_size * want_pages); return page->data; } } void * shm_alloc(struct shm *shm, unsigned want_pages) { return shm->Allocate(want_pages); } /** merge this page with its adjacent pages if possible, to create bigger "available" areas */ void shm::Merge(struct page *page) { unsigned page_number = PageNumber(page->data); /* merge with previous page? */ struct page *other = (struct page *)page->siblings.prev; if (&other->siblings != &available && PageNumber(other->data) + other->num_pages == page_number) { other->num_pages += page->num_pages; list_remove(&page->siblings); page = other; } /* merge with next page? */ other = (struct page *)page->siblings.next; if (&other->siblings != &available && page_number + page->num_pages == PageNumber(other->data)) { page->num_pages += other->num_pages; list_remove(&other->siblings); } } void shm::Free(const void *p) { unsigned page_number = PageNumber(p); struct page *page = &pages[page_number]; struct page *prev; poison_noaccess(page->data, page_size * page->num_pages); boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(mutex); for (prev = (struct page *)&available; prev->siblings.next != &available; prev = (struct page *)prev->siblings.next) { } list_add(&page->siblings, &prev->siblings); Merge(page); } void shm_free(struct shm *shm, const void *p) { shm->Free(p); } <|endoftext|>
<commit_before>// sota.cpp : Defines the entry point for the console application. // #include <regex> #include "stdafx.h" #include "utils.h" #include "lexer.h" #include "token.h" #include "stream.hpp" #include <array> using namespace sota; std::vector<char> load(std::string filename) { std::vector<char> chars; std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate); if (!file.eof() && !file.fail() ) { file.seekg(0, std::ios_base::end); auto size = (unsigned int)file.tellg(); chars.resize(size); file.seekg(0, std::ios_base::beg); file.read(&chars[0], (long int)size); } return chars; } int main(int argc, char* argv[]) { auto chars = load("example1.sota"); auto lexer = SotaLexer(chars); while(auto token = lexer.Scan()) { std::cout << lexer.Pretty(token); if (TokenType::EndOfLine == token.Type) std::cout << std::endl; else std::cout << " "; } return 0; } <commit_msg>reworked sota to take the path to the file to parse as the first arg... -sai<commit_after>// sota.cpp : Defines the entry point for the console application. // #include <regex> #include "stdafx.h" #include "utils.h" #include "lexer.h" #include "token.h" #include "stream.hpp" #include <array> using namespace sota; std::vector<char> load(std::string filename) { std::vector<char> chars; std::ifstream file(filename, std::ios::in | std::ios::binary | std::ios::ate); if (!file.eof() && !file.fail() ) { file.seekg(0, std::ios_base::end); auto size = (unsigned int)file.tellg(); chars.resize(size); file.seekg(0, std::ios_base::beg); file.read(&chars[0], (long int)size); } return chars; } int main(int argc, char* argv[]) { if (argc < 2) return 1; const char *filename = argv[1]; auto chars = load(filename); auto lexer = SotaLexer(chars); while(auto token = lexer.Scan()) { switch (token.Type) { case TokenType::EndOfLine: std::cout << lexer.Pretty(token) << std::endl; break; case TokenType::WhiteSpace: break; default: std::cout << lexer.Pretty(token) << " "; break; } } return 0; } <|endoftext|>