text
string
size
int64
token_count
int64
#include <iostream> #include "Pixel.h" #define LION_DIV 256 LionPixel::LionPixel() { r = 0; g= 0; b = 0; } LionPixel::LionPixel(int red, int green, int blue) { r = red; g = green; b = blue; } LionPixel::LionPixel(int red, int green, int blue, double alpha) { r = red; g = green; b = blue; a= alpha; updateCss(); } double LionPixel::intensity() { intensityV = (r + g + b) * a; return intensityV; } std::ostream & operator<<(std::ostream & os, const LionPixel & t){ os << "[ r => " << t.r << ", g => " << t.g << ", b => " << t.b << ", a => " << t.a << " ]"; return os; };
653
274
#include "thread.hpp" #include "fpage.hpp" #include "schd.hpp" #include "ktimer.hpp" #include "ipc.hpp" #include "irq.hpp" namespace f9 { __attribute__((weak)) void root_thread(); __attribute__((weak)) void root_thread() { while(1); } DECLARE_KTABLE(tcb_t, thread_table, CONFIG_MAX_THREADS); //volatile tcb_t *current = nullptr; /* Currently on CPU */ volatile tcb_t *current = nullptr; /* Currently on CPU */ void *current_utcb __USER_DATA; extern tcb_t *caller; tcb_t *thread_map[CONFIG_MAX_THREADS]; int thread_count; static tcb_t *thread_sched(sched_slot_t *); void thread_init_subsys() { // don't worry about kept #if 0 fpage_t *last = nullptr; ktable_init(&thread_table); kip.thread_info.s.system_base = THREAD_SYS; kip.thread_info.s.user_base = THREAD_USER; /* Create KIP fpages * last is ignored, because kip fpages is aligned */ fpage_t::assign_ext(-1, (memptr_t) &kip, sizeof(kip_t), &kip_fpage, &last); fpage_t::assign_ext(-1, (memptr_t) kip_extra, CONFIG_KIP_EXTRA_SIZE, &kip_extra_fpage, &last); #endif sched_slot_set_handler(SSI::NORMAL_THREAD, thread_sched); } /* * Return upper_bound using binary search */ static int thread_map_search(thread_id_t globalid, int from, int to) { int tid = GLOBALID_TO_TID(globalid); /* Upper bound if beginning of array */ if (to == from || (int)GLOBALID_TO_TID(thread_map[from]->t_globalid) >= tid) return from; while (from <= to) { if ((to - from) <= 1) return to; int mid = from + (to - from) / 2; if ((int)GLOBALID_TO_TID(thread_map[mid]->t_globalid) > tid) to = mid; else if ((int)GLOBALID_TO_TID(thread_map[mid]->t_globalid) < tid) from = mid; else return mid; } /* not reached */ return -1; } /* * Insert thread into thread map */ static void thread_map_insert(thread_id_t globalid, tcb_t *thr) { if (thread_count == 0) { thread_map[thread_count++] = thr; } else { int i = thread_map_search(globalid, 0, thread_count); int j = thread_count; /* Move forward * Don't check if count is out of range, * because we will fail on ktable_alloc */ for (; j > i; --j) thread_map[j] = thread_map[j - 1]; thread_map[i] = thr; ++thread_count; } } static void thread_map_delete(thread_id_t globalid) { if (thread_count == 1) { thread_count = 0; } else { int i = thread_map_search(globalid, 0, thread_count); --thread_count; for (; i < thread_count; i++) thread_map[i] = thread_map[i + 1]; } } tcb_t::tcb_t(thread_id_t globalid, utcb_t *utcb) : t_globalid(globalid) , t_localid(0) , state(TSTATE::INACTIVE) , stack_base(0) , stack_size(0) , ctx() #ifdef CONFIG_ENABLE_FPAGE , as(nullptr) #endif , utcb(utcb) , ipc_from(0) , t_sibling(nullptr) , t_parent(nullptr) , t_child(nullptr) , timeout_event(0) { thread_map_insert(globalid, this); if (utcb) utcb->t_globalid = globalid; dbg::print(dbg::DL_THREAD, "T: New thread: %t @[%p] \n", globalid, this); } volatile tcb_t* tcb_t::current() { return f9::current; } tcb_t* tcb_t::create(thread_id_t globalid, utcb_t *utcb){ int id = GLOBALID_TO_TID(globalid); assert(caller != nullptr); if (id < static_cast<int>(THREAD::SYS) || globalid == ANYTHREAD || globalid == ANYLOCALTHREAD) { set_caller_error(UE::TC_NOT_AVAILABLE); return nullptr; } tcb_t *thr = new tcb_t(globalid, utcb); if (!thr) { set_caller_error(UE::OUT_OF_MEM); return nullptr; } thr->t_parent = caller; /* Place under */ if (caller->t_child) { tcb_t *t = caller->t_child; while (t->t_sibling != 0) t = t->t_sibling; t->t_sibling = thr; thr->t_localid = t->t_localid + (1 << 6); } else { /* That is first thread in child chain */ caller->t_child = thr; thr->t_localid = (1 << 6); } return thr; } tcb_t::~tcb_t() { tcb_t *parent, *child, *prev_child; /* remove thr from its parent and its siblings */ parent = this->t_parent; if (parent->t_child == this) { parent->t_child = this->t_sibling; } else { child = parent->t_child; while (child != this) { prev_child = child; child = child->t_sibling; } prev_child->t_sibling = child->t_sibling; } /* move thr's children to caller */ child = this->t_child; if (child) { child->t_parent = caller; while (child->t_sibling) { child = child->t_sibling; child->t_parent = caller; } /* connect thr's children to caller's children */ child->t_sibling = caller->t_child; caller->t_child = this->t_child; } thread_map_delete(t_globalid); } void tcb_t::free_space(){ #ifdef CONFIG_ENABLE_FPAGE this->as.reset(); #endif } void tcb_t::space(thread_id_t spaceid, utcb_t *utcb){ #ifdef CONFIG_ENABLE_FPAGE /* If spaceid == dest than create new address space * else share address space between threads */ if (GLOBALID_TO_TID(this->t_globalid) == GLOBALID_TO_TID(spaceid)) { this->as = std::make_shared<as_t>(this->t_globalid); /* Grant kip_fpage & kip_ext_fpage only to new AS */ //this->as->map(kip_fpage, GRANT); //this->as->map(kip_extra_fpage, GRANT); dbg::print(dbg::DL_THREAD, "\tNew space: as: %p, utcb: %p \n", this->as, utcb); } else { tcb_t *space = thread_by_globalid(spaceid); this->as = space->as; } /* If no caller, than it is mapping from kernel to root thread * (some special case for root_utcb) */ if (caller) map_area(caller->as, this->as, (memptr_t) utcb, sizeof(utcb_t), GRANT, caller->ispriviliged()); else map_area(this->as, this->as, (memptr_t) utcb, sizeof(utcb_t), GRANT, true); #endif } void tcb_t::_init_ctx(uintptr_t spi, uintptr_t pc, uintptr_t regsi){ /* Reserve 8 words for fake context */ //sp -= RESERVED_STACK; uint32_t* sp = reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(spi)-RESERVED_STACK); ctx.sp = reinterpret_cast<uint32_t>(sp); /* Set EXC_RETURN and CONTROL for thread and create initial stack for it * When thread is dispatched, on first context switch */ if (GLOBALID_TO_TID(t_globalid) >= static_cast<uint32_t>(THREAD::ROOT)) { ctx.ret = 0xFFFFFFFD; ctx.ctl = 0x3; } else { ctx.ret = 0xFFFFFFF9; ctx.ctl = 0x0; } //uint32_t* spa = reinterpret_cast<uint32_t*>(sp); if (regsi == 0) { sp[REG_R0] = 0x0; sp[REG_R1] = 0x0; sp[REG_R2] = 0x0; sp[REG_R3] = 0x0; } else { uint32_t* regs = reinterpret_cast<uint32_t*>(regsi); sp[REG_R0] = regs[0]; sp[REG_R1] = regs[1]; sp[REG_R2] = regs[2]; sp[REG_R3] = regs[3]; } sp[REG_R12] = 0x0; sp[REG_LR] = 0xFFFFFFFF; sp[REG_PC] = pc; sp[REG_xPSR] = 0x1000000; /* Thumb bit on */ } void tcb_t::_init_kernel_ctx(uintptr_t spi) { uint32_t* sp = reinterpret_cast<uint32_t*>(reinterpret_cast<uint8_t*>(spi)-RESERVED_STACK); ctx.sp = reinterpret_cast<uint32_t>(sp); ctx.ret = 0xFFFFFFF9; ctx.ctl = 0x0; } /* * Search thread by its global id */ tcb_t *thread_by_globalid(thread_id_t globalid) { int idx = thread_map_search(globalid, 0, thread_count); if (GLOBALID_TO_TID(thread_map[idx]->t_globalid) != GLOBALID_TO_TID(globalid)) return nullptr; return thread_map[idx]; } void tcb_t::switch_to() { assert(isrunnable()); f9::current = this; current_utcb =utcb; #if 0 if (current->as) current->setup_mpu(current->as, current->ctx.sp, ((uint32_t *) current->ctx.sp)[REG_PC], current->stack_base, current->stack_size); #endif } /* Select normal thread to run * * NOTE: all threads are derived from root */ static tcb_t *thread_select(tcb_t *parent) { tcb_t *thr = parent->t_child; if (thr == NULL) return NULL; while (1) { if (thr->isrunnable()) return thr; if (thr->t_child != nullptr) { thr = thr->t_child; continue; } if (thr->t_sibling != nullptr) { thr = thr->t_sibling; continue; } do { if (thr->t_parent == parent) return nullptr; thr = thr->t_parent; } while (thr->t_sibling == nullptr); thr = thr->t_sibling; } } // systhread tcb_t *idle; tcb_t *kernel; tcb_t *root; static tcb_t *thread_sched(sched_slot_t *slot) { return thread_select(root); } utcb_t root_utcb __KIP; extern void root_thread(void); static void kernel_thread(void); static void idle_thread(void) { while (1) #ifdef CONFIG_KTIMER_TICKLESS ktimer_enter_tickless(); #else ARM::wfi(); //wait_for_interrupt(); #endif /* CONFIG_KTIMER_TICKLESS */ } static void kernel_thread(void) { while (1) { /* If all softirqs processed, call SVC to * switch context immediately */ softirq_t::execute(); irq_svc(); } } void tcb_t::create_root_thread(void) { root = new tcb_t(TID_TO_GLOBALID(THREAD::ROOT), &root_utcb); #ifdef CONFIG_ENABLE_FPAGE root->space(TID_TO_GLOBALID(THREAD::ROOT), &root_utcb); root->as->map_user(); #endif uint32_t regs[4] ={ #if 0 [REG_R0] = (uint32_t) &kip, #else [REG_R0] = 0, // no kip #endif [REG_R1] = ptr_to_int(root->utcb), [REG_R2] = 0, [REG_R3] = 0 }; root->init_ctx((void *) &root_stack_end, &root_thread, regs); root->stack_base = (memptr_t) &root_stack_start; root->stack_size = (uint32_t) &root_stack_end - (uint32_t) &root_stack_start; sched_slot_dispatch(SSI::ROOT_THREAD, root); root->state = TSTATE::RUNNABLE; } void tcb_t::create_kernel_thread(void){ kernel = new tcb_t(TID_TO_GLOBALID(THREAD::KERNEL), nullptr); kernel->init_kernel_ctx(&kernel_stack_end); /* This will prevent running other threads * than kernel until it will be initialized */ sched_slot_dispatch(SSI::SOFTIRQ, kernel); kernel->state = TSTATE::RUNNABLE; } void tcb_t::create_idle_thread(void){ idle = new tcb_t(TID_TO_GLOBALID(THREAD::KERNEL), nullptr); idle->init_ctx( &idle_stack_end, idle_thread, nullptr); sched_slot_dispatch(SSI::IDLE, idle); idle->state = TSTATE::RUNNABLE; } void tcb_t::switch_to_kernel(void){ // startup? create_kernel_thread(); f9::current = kernel; init_ctx_switch(&kernel->ctx, kernel_thread); } void set_kernel_state(TSTATE state) { kernel->state = state; } void set_user_error(tcb_t *thread, UE error) { assert(thread && thread->utcb); thread->utcb->error_code = static_cast<uint32_t>(error); } void set_caller_error(UE error) { if (caller) set_user_error((tcb_t *) caller, error); else panic("User-level error %d during in-kernel call!", error); } void user_log(tcb_t *from) { char *format = (char *) from->ctx.regs[1]; va_list *va = (va_list *) from->ctx.regs[2]; dbg::print(dbg::DL_KDB, format, *va); } void tcb_t::startup(){ trace_printf("tcb_t::startup()\r\n"); create_idle_thread(); create_root_thread(); ktimer_event_init(); assert(ktimer_event_t::create(64, ipc_deliver, nullptr)); switch_to_kernel(); } }; void PendSV_Handler(void) __NAKED; void PendSV_Handler(void) { irq_enter(); schedule_in_irq(); irq_return(); }
11,112
5,233
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include "config.h" #include "timings.h" #include <memcached/protocol_binary.h> #include <stdlib.h> #include <string.h> #include <sstream> #ifdef HAVE_ATOMIC #include <atomic> #else #include <cstdatomic> #endif typedef struct timings_st { /* We collect timings for <=1 us */ std::atomic<uint32_t> ns; /* We collect timings per 10usec */ std::atomic<uint32_t> usec[100]; /* we collect timings from 0-49 ms (entry 0 is never used!) */ std::atomic<uint32_t> msec[50]; std::atomic<uint32_t> halfsec[10]; std::atomic<uint32_t> wayout; std::atomic<uint64_t> total; } timings_t; timings_t timings[0x100]; void collect_timing(uint8_t cmd, hrtime_t nsec) { timings_t *t = &timings[cmd]; hrtime_t usec = nsec / 1000; hrtime_t msec = usec / 1000; hrtime_t hsec = msec / 500; if (usec == 0) { t->ns++; } else if (usec < 1000) { t->usec[usec / 10]++; } else if (msec < 50) { t->msec[msec]++; } else if (hsec < 10) { t->halfsec[hsec]++; } else { t->wayout++; } t->total++; } void initialize_timings(void) { int ii, jj; for (ii = 0; ii < 0x100; ++ii) { timings[ii].ns.store(0); for (jj = 0; jj < 100; ++jj) { timings[ii].usec[jj].store(0); } for (jj = 0; jj < 50; ++jj) { timings[ii].msec[jj].store(0); } for (jj = 0; jj < 10; ++jj) { timings[ii].halfsec[jj].store(0); } timings[ii].wayout.store(0); timings[ii].total.store(0); } } void generate_timings(uint8_t opcode, const void *cookie) { std::stringstream ss; timings_t *t = &timings[opcode]; ss << "{\"ns\":" << t->ns.load() << ",\"us\":["; for (int ii = 0; ii < 99; ++ii) { ss << t->usec[ii].load() << ","; } ss << t->usec[99].load() << "],\"ms\":["; for (int ii = 1; ii < 49; ++ii) { ss << t->msec[ii].load() << ","; } ss << t->msec[49].load() << "],\"500ms\":["; for (int ii = 0; ii < 9; ++ii) { ss << t->halfsec[ii].load() << ","; } ss << t->halfsec[9].load() << "],\"wayout\":" << t->wayout.load() << "}"; std::string str = ss.str(); binary_response_handler(NULL, 0, NULL, 0, str.data(), str.length(), PROTOCOL_BINARY_RAW_BYTES, PROTOCOL_BINARY_RESPONSE_SUCCESS, 0, cookie); } uint64_t get_aggregated_cmd_stats(cmd_stat_t type) { uint64_t ret = 0; static uint8_t mutations[] = { PROTOCOL_BINARY_CMD_ADD, PROTOCOL_BINARY_CMD_ADDQ, PROTOCOL_BINARY_CMD_APPEND, PROTOCOL_BINARY_CMD_APPENDQ, PROTOCOL_BINARY_CMD_DECREMENT, PROTOCOL_BINARY_CMD_DECREMENTQ, PROTOCOL_BINARY_CMD_DELETE, PROTOCOL_BINARY_CMD_DELETEQ, PROTOCOL_BINARY_CMD_GAT, PROTOCOL_BINARY_CMD_GATQ, PROTOCOL_BINARY_CMD_INCREMENT, PROTOCOL_BINARY_CMD_INCREMENTQ, PROTOCOL_BINARY_CMD_PREPEND, PROTOCOL_BINARY_CMD_PREPENDQ, PROTOCOL_BINARY_CMD_REPLACE, PROTOCOL_BINARY_CMD_REPLACEQ, PROTOCOL_BINARY_CMD_SET, PROTOCOL_BINARY_CMD_SETQ, PROTOCOL_BINARY_CMD_TOUCH, PROTOCOL_BINARY_CMD_INVALID}; static uint8_t retrival[] = { PROTOCOL_BINARY_CMD_GAT, PROTOCOL_BINARY_CMD_GATQ, PROTOCOL_BINARY_CMD_GET, PROTOCOL_BINARY_CMD_GETK, PROTOCOL_BINARY_CMD_GETKQ, PROTOCOL_BINARY_CMD_GETQ, PROTOCOL_BINARY_CMD_GET_LOCKED, PROTOCOL_BINARY_CMD_GET_RANDOM_KEY, PROTOCOL_BINARY_CMD_GET_REPLICA, PROTOCOL_BINARY_CMD_INVALID }; static uint8_t total[] = { PROTOCOL_BINARY_CMD_ADD, PROTOCOL_BINARY_CMD_ADDQ, PROTOCOL_BINARY_CMD_APPEND, PROTOCOL_BINARY_CMD_APPENDQ, PROTOCOL_BINARY_CMD_DECREMENT, PROTOCOL_BINARY_CMD_DECREMENTQ, PROTOCOL_BINARY_CMD_DELETE, PROTOCOL_BINARY_CMD_DELETEQ, PROTOCOL_BINARY_CMD_GAT, PROTOCOL_BINARY_CMD_GATQ, PROTOCOL_BINARY_CMD_GET, PROTOCOL_BINARY_CMD_GETK, PROTOCOL_BINARY_CMD_GETKQ, PROTOCOL_BINARY_CMD_GETQ, PROTOCOL_BINARY_CMD_GET_LOCKED, PROTOCOL_BINARY_CMD_GET_RANDOM_KEY, PROTOCOL_BINARY_CMD_GET_REPLICA, PROTOCOL_BINARY_CMD_INCREMENT, PROTOCOL_BINARY_CMD_INCREMENTQ, PROTOCOL_BINARY_CMD_PREPEND, PROTOCOL_BINARY_CMD_PREPENDQ, PROTOCOL_BINARY_CMD_REPLACE, PROTOCOL_BINARY_CMD_REPLACEQ, PROTOCOL_BINARY_CMD_SET, PROTOCOL_BINARY_CMD_SETQ, PROTOCOL_BINARY_CMD_TOUCH, PROTOCOL_BINARY_CMD_INVALID }; uint8_t *ids; switch (type) { case CMD_TOTAL_MUTATION: ids = mutations; break; case CMD_TOTAL_RETRIVAL: ids = retrival; break; case CMD_TOTAL: ids = total; break; default: abort(); } while (*ids != PROTOCOL_BINARY_CMD_INVALID) { ret += timings[*ids].total.load(); ++ids; } return ret; }
5,187
2,281
/* MANGO Multimedia Development Platform Copyright (C) 2012-2021 Twilight Finland 3D Oy Ltd. All rights reserved. */ #include <cmath> #include <mango/core/pointer.hpp> #include <mango/core/buffer.hpp> #include <mango/core/system.hpp> #include <mango/image/image.hpp> namespace { using namespace mango; using namespace mango::image; // ------------------------------------------------------------ // tokenizer // ------------------------------------------------------------ std::string readline(const u8*& data, const u8* end) { const u8* p = data; int endsize = 1; // scan for endline for ( ; data < end; ) { u8 v = *p++; // Unix ("\n") if (v == '\n') break; // MacOS ("\r") if (v == '\r') { // Windows ("\r\n") if (*p == '\n') { ++endsize; ++p; } break; } } int size = int(p - data) - endsize; std::string msg(reinterpret_cast<const char*>(data), size); data = p; return msg; } inline bool whitespace(char v) { return v == ' ' || v == '\t' || v == '='; } void insert_token(std::vector<std::string>& tokens, const char* text, int size) { if (size > 0) { std::string msg(text, size); tokens.push_back(msg); } } std::vector<std::string> tokenize(const std::string& line) { std::vector<std::string> tokens; const char* p = line.c_str(); const char* endline = p + line.length(); for ( ; p < endline;) { // skip whitespaces for ( ;; ++p) { char v = *p; if (!v) return tokens; if (!whitespace(v)) break; } const char* begin = p; // seek next whitespace for ( ;; ++p) { char v = *p; if (!v) { int size = int(p - begin); insert_token(tokens, begin, size); return tokens; } if (whitespace(v)) break; } int size = int(p - begin); insert_token(tokens, begin, size); } return tokens; } // ------------------------------------------------------------ // encoder // ------------------------------------------------------------ struct rgbe { u8 r, g, b, e; }; /* rgbe create_rgbe(float r, float g, float b) { float maxf = r > g ? r : g; maxf = maxf > b ? maxf : b; rgbe color; if (maxf <= 1e-32f) { color.r = 0; color.g = 0; color.b = 0; color.e = 0; } else { int exponent; std::frexpf(maxf, &exponent); float scale = std::ldexpf(1.0f, 8 - exponent); color.r = u8(r * scale); color.g = u8(g * scale); color.b = u8(b * scale); color.e = u8(exponent + 128); } return color; } */ // ------------------------------------------------------------ // decoder // ------------------------------------------------------------ void write_rgbe(float* buffer, rgbe color) { float scale = color.e ? std::ldexp(1.0f, color.e - 136) : 0; buffer[0] = color.r * scale; buffer[1] = color.g * scale; buffer[2] = color.b * scale; buffer[3] = 1.0f; } struct HeaderRAD { enum rad_format { rad_rle_rgbe, rad_unsupported } format = rad_unsupported; int width = 0; int height = 0; float exposure = 1.0f; bool xflip = false; bool yflip = false; ImageHeader header; const u8* parse(ConstMemory memory) { const u8* data = memory.address; const u8* end = memory.address + memory.size; std::string id = readline(data, end); if (id != "#?RADIANCE") { header.setError("[ImageDecoder.HDR] Incorrect radiance header."); return nullptr; } for ( ;; ) { std::string ln = readline(data, end); if (ln.empty()) break; std::vector<std::string> tokens = tokenize(ln); if (tokens[0] == "FORMAT") { if (tokens.size() != 2) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (format)."); return nullptr; } if (tokens[1] == "32-bit_rle_rgbe") format = rad_rle_rgbe; } else if (tokens[1] == "EXPOSURE") { if (tokens.size() != 2) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (exposure)."); return nullptr; } exposure = float(std::atof(tokens[1].c_str())); } } if (format == rad_unsupported) { header.setError("[ImageDecoder.HDR] Incorrect or unsupported format."); return nullptr; } std::string dims = readline(data, end); std::vector<std::string> tokens = tokenize(dims); if (tokens.size() != 4) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } for (int i = 0; i < 2; ++i) { int index = i * 2; if (tokens[index] == "+Y") { yflip = false; height = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "-Y") { yflip = true; height = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "+X") { xflip = false; width = std::atoi(tokens[index + 1].c_str()); } else if (tokens[index] == "-X") { xflip = true; width = std::atoi(tokens[index + 1].c_str()); } else { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } } if (!width || !height) { header.setError("[ImageDecoder.HDR] Incorrect radiance header (dimensions)."); return nullptr; } header.width = width; header.height = height; header.depth = 0; header.levels = 0; header.faces = 0; header.palette = false; header.format = Format(128, Format::FLOAT32, Format::RGBA, 32, 32, 32, 32); header.compression = TextureCompression::NONE; return data; } }; void hdr_decode(ImageDecodeStatus& status, const Surface& surface, const u8* data) { Buffer buffer(surface.width * 4); for (int y = 0; y < surface.height; ++y) { if (data[0] != 2 || data[1] != 2 || data[2] & 0x80) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (wrong header)."); return; } if (((data[2] << 8) | data[3]) != surface.width) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (wrong scan)."); return; } data += 4; for (int channel = 0; channel < 4; ++channel) { u8* dest = buffer + surface.width * channel; u8* end = dest + surface.width; while (dest < end) { int count = *data++; if (count > 128) { count -= 128; if (!count || dest + count > end) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (rle count)."); return; } u8 value = *data++; std::memset(dest, value, count); dest += count; } else { if (!count || dest + count > end) { status.setError("[ImageDecoder.HDR] Incorrect rle_rgbe stream (rle count)."); return; } std::memcpy(dest, data, count); dest += count; data += count; } } } float* image = surface.address<float>(0, y); for (int x = 0; x < surface.width; ++x) { rgbe color; color.r = buffer[x + surface.width * 0]; color.g = buffer[x + surface.width * 1]; color.b = buffer[x + surface.width * 2]; color.e = buffer[x + surface.width * 3]; write_rgbe(image, color); image += 4; } } } // ------------------------------------------------------------ // ImageDecoder // ------------------------------------------------------------ struct Interface : ImageDecoderInterface { HeaderRAD m_rad_header; const u8* m_data; Interface(ConstMemory memory) { m_data = m_rad_header.parse(memory); } ~Interface() { } ImageHeader header() override { return m_rad_header.header; } ImageDecodeStatus decode(const Surface& dest, const ImageDecodeOptions& options, int level, int depth, int face) override { MANGO_UNREFERENCED(options); MANGO_UNREFERENCED(level); MANGO_UNREFERENCED(depth); MANGO_UNREFERENCED(face); ImageDecodeStatus status; const ImageHeader& header = m_rad_header.header; if (!header.success) { status.setError(header.info); return status; } status.direct = dest.format == header.format && dest.width == header.width && dest.height == header.height; if (status.direct) { hdr_decode(status, dest, m_data); } else { Bitmap temp(header.width, header.height, header.format); hdr_decode(status, temp, m_data); if (status) { dest.blit(0, 0, temp); } } return status; } }; ImageDecoderInterface* createInterface(ConstMemory memory) { ImageDecoderInterface* x = new Interface(memory); return x; } } // namespace namespace mango::image { void registerImageDecoderHDR() { registerImageDecoder(createInterface, ".hdr"); } } // namespace mango::image
12,039
3,384
// swap QMultiMaps #include <iostream> #include <QMultiMap> #include <cassert> using namespace std; int main () { QMultiMap<char,int> foo; QMultiMap<char,int> bar; QMultiMap<char,int>::iterator it; foo['x']=100; foo['y']=200; bar['a']=11; bar['b']=22; bar['c']=33; foo.swap(bar); cout << "foo contains:\n"; for ( it=foo.begin() ; it != foo.end(); it++ ) cout << it.key() << " => " << it.value() << endl; cout << "bar contains:\n"; for ( it=bar.begin() ; it != bar.end(); it++ ) cout << it.key() << " => " << it.value() << endl; assert(bar['x']==100); assert(bar['y']==200); assert(foo['a']==11); assert(foo['b']==22); assert(foo['c']==33); return 0; }
711
317
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/browser/api/api_resource_manager.h" #include "extensions/browser/api/runtime/runtime_api.h" #include "extensions/browser/api/socket/socket.h" #include "extensions/browser/api/socket/tcp_socket.h" #include "extensions/browser/api/socket/udp_socket.h" #include "extensions/browser/api/sockets_tcp/tcp_socket_event_dispatcher.h" #include "extensions/browser/api/sockets_tcp_server/tcp_server_socket_event_dispatcher.h" #include "extensions/browser/api/sockets_udp/udp_socket_event_dispatcher.h" #include "extensions/browser/api/storage/storage_frontend.h" #include "extensions/browser/extension_prefs_factory.h" #include "extensions/browser/renderer_startup_helper.h" namespace extensions { void EnsureBrowserContextKeyedServiceFactoriesBuilt() { ApiResourceManager< extensions::ResumableTCPServerSocket>::GetFactoryInstance(); ApiResourceManager<extensions::ResumableTCPSocket>::GetFactoryInstance(); ApiResourceManager<extensions::ResumableUDPSocket>::GetFactoryInstance(); ApiResourceManager<extensions::Socket>::GetFactoryInstance(); core_api::TCPServerSocketEventDispatcher::GetFactoryInstance(); core_api::TCPSocketEventDispatcher::GetFactoryInstance(); core_api::UDPSocketEventDispatcher::GetFactoryInstance(); ExtensionPrefsFactory::GetInstance(); RendererStartupHelperFactory::GetInstance(); RuntimeAPI::GetFactoryInstance(); StorageFrontend::GetFactoryInstance(); } } // namespace extensions
1,691
498
// Fixation target abstract class // Written by Tim Murphy <tim@murphy.org> 2021 #include "FixationTarget.h" #include "CircleTarget.h" #include "CrosshairBullseyeTarget.h" #include <stdexcept> FixationTarget::FixationTarget(unsigned int diameter) :diameter(diameter) { } unsigned int FixationTarget::getDiameter(void) const { return diameter; } FixationTarget *FixationTarget::create(const std::string &type, unsigned int diameter) { if (type == "circle") { return new CircleTarget(diameter); } else if (type == "crosshairbullseye" || type == "cbe") { return new CrosshairBullseyeTarget(diameter); } else { std::string err("Unknown fixation target type: " + type); throw std::runtime_error(err.c_str()); } }
828
280
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: vector<ListNode*> splitListToParts(ListNode* root, int k) { int d=depth(root); vector<int> ls; while(k>0){ ls.push_back(d/k); d-=d/k; k--; } vector<ListNode*> ans; ListNode* prev=root; while(ls.size() && root){ while(ls.back()>1){ root=root->next; ls.back()--; } ListNode* tmp=root; root=root->next; tmp->next=NULL; ans.push_back(prev); prev=root; ls.pop_back(); } while(ls.size()){ ans.push_back(NULL); ls.pop_back(); } return ans; } int depth(ListNode* root){ if(!root) return 0; return 1+depth(root->next); } };
1,007
329
//***************************************************************** // Copyright 2015 MIT Lincoln Laboratory // Project: SPAR // Authors: OMD // Description: Implmentation of OrderedFunctionRegistry // // Modifications: // Date Name Modification // ---- ---- ------------ // 21 May 2012 omd Original Version //***************************************************************** #include "ordered-function-registry.h" #include "common/topological-iterator.h" // Can't use CHECK as logging is intializied via OrderedFunctionRegistry! #include <cassert> using std::string; using std::map; using std::list; using std::pair; void OrderedFunctionRegistry::OrderConstraint(const string& before, const string& after) { // We have no way to know if before or after have already been registered as // statics are not initialized in any deterministic order (which is exactly // the problem this class is supposed to solve) so we just store the string // and check for existence when we get to RunFunctions(). function_order_constraints_.push_back(make_pair(before, after)); } void OrderedFunctionRegistry::RunFunctions() { TopologicalIterator<NamedFunction> function_ordering; map<string, VoidFunction>::iterator i; for (i = functions_to_run_.begin(); i != functions_to_run_.end(); ++i) { function_ordering.Add(*i); } list<pair<string, string> >::iterator j; for (j = function_order_constraints_.begin(); j != function_order_constraints_.end(); ++j) { assert(functions_to_run_.find(j->first) != functions_to_run_.end()); assert(functions_to_run_.find(j->second) != functions_to_run_.end()); function_ordering.OrderConstraint(*functions_to_run_.find(j->first), *functions_to_run_.find(j->second)); } // Now the ordering is set up so iterate through the functions in topological // order and run them. while(function_ordering.HasNext()) { function_ordering.Next().function_(); } }
2,099
574
/* * Copyright (c) 2014 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // EXTERNAL INCLUDES #include <dali/public-api/object/type-registry-helper.h> #include <dali/public-api/object/type-registry.h> #include <cstring> // for strcmp // INTERNAL INCLUDES #include <dali-toolkit/internal/controls/control/control-data-impl.h> #include <dali-toolkit/internal/controls/scrollable/scrollable-impl.h> using namespace Dali; namespace Dali { namespace Toolkit { namespace Internal { namespace { BaseHandle Create() { // empty handle as we cannot create Scrollable (but type registered for scroll signal) return BaseHandle(); } // Setup properties, signals and actions using the type-registry. DALI_TYPE_REGISTRATION_BEGIN(Toolkit::Scrollable, Toolkit::Control, Create); DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEffectColor", VECTOR4, OVERSHOOT_EFFECT_COLOR) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootAnimationSpeed", FLOAT, OVERSHOOT_ANIMATION_SPEED) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootEnabled", BOOLEAN, OVERSHOOT_ENABLED) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "overshootSize", VECTOR2, OVERSHOOT_SIZE) DALI_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollToAlphaFunction", INTEGER, SCROLL_TO_ALPHA_FUNCTION) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollRelativePosition", VECTOR2, SCROLL_RELATIVE_POSITION) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMin", VECTOR2, SCROLL_POSITION_MIN) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinX", SCROLL_POSITION_MIN_X, SCROLL_POSITION_MIN, 0) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMinY", SCROLL_POSITION_MIN_Y, SCROLL_POSITION_MIN, 1) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "scrollPositionMax", VECTOR2, SCROLL_POSITION_MAX) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxX", SCROLL_POSITION_MAX_X, SCROLL_POSITION_MAX, 0) DALI_ANIMATABLE_PROPERTY_COMPONENT_REGISTRATION(Toolkit, Scrollable, "scrollPositionMaxY", SCROLL_POSITION_MAX_Y, SCROLL_POSITION_MAX, 1) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollVertical", BOOLEAN, CAN_SCROLL_VERTICAL) DALI_ANIMATABLE_PROPERTY_REGISTRATION(Toolkit, Scrollable, "canScrollHorizontal", BOOLEAN, CAN_SCROLL_HORIZONTAL) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollStarted", SIGNAL_SCROLL_STARTED) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollCompleted", SIGNAL_SCROLL_COMPLETED) DALI_SIGNAL_REGISTRATION(Toolkit, Scrollable, "scrollUpdated", SIGNAL_SCROLL_UPDATED) DALI_TYPE_REGISTRATION_END() const Vector4 DEFAULT_OVERSHOOT_COLOUR(0.0f, 0.64f, 0.85f, 0.25f); const float DEFAULT_OVERSHOOT_ANIMATION_SPEED(120.0f); // 120 pixels per second const Vector2 OVERSHOOT_DEFAULT_SIZE(720.0f, 42.0f); } // namespace /////////////////////////////////////////////////////////////////////////////////////////////////// // Scrollable /////////////////////////////////////////////////////////////////////////////////////////////////// Scrollable::Scrollable(ControlBehaviour behaviourFlags) : Control(ControlBehaviour(behaviourFlags)), mOvershootEffectColor(DEFAULT_OVERSHOOT_COLOUR), mOvershootAnimationSpeed(DEFAULT_OVERSHOOT_ANIMATION_SPEED), mOvershootSize(OVERSHOOT_DEFAULT_SIZE), mScrollToAlphaFunction(AlphaFunction::EASE_OUT), mScrollStartedSignal(), mScrollUpdatedSignal(), mScrollCompletedSignal(), mOvershootEnabled(true) { } Scrollable::~Scrollable() { } bool Scrollable::AccessibleImpl::IsScrollable() { return true; } void Scrollable::OnInitialize() { DevelControl::SetAccessibilityConstructor(Self(), [](Dali::Actor actor) { return std::unique_ptr<Dali::Accessibility::Accessible>( new AccessibleImpl(actor, Dali::Accessibility::Role::SCROLL_PANE)); }); } bool Scrollable::IsOvershootEnabled() const { return mOvershootEnabled; } void Scrollable::SetOvershootEnabled(bool enable) { EnableScrollOvershoot(enable); mOvershootEnabled = enable; } Vector4 Scrollable::GetOvershootEffectColor() const { return mOvershootEffectColor; }; void Scrollable::SetOvershootAnimationSpeed(float pixelsPerSecond) { mOvershootAnimationSpeed = pixelsPerSecond; } float Scrollable::GetOvershootAnimationSpeed() const { return mOvershootAnimationSpeed; }; const Vector2& Scrollable::GetOvershootSize() const { return mOvershootSize; } Toolkit::Scrollable::ScrollStartedSignalType& Scrollable::ScrollStartedSignal() { return mScrollStartedSignal; } Toolkit::Scrollable::ScrollUpdatedSignalType& Scrollable::ScrollUpdatedSignal() { return mScrollUpdatedSignal; } Toolkit::Scrollable::ScrollCompletedSignalType& Scrollable::ScrollCompletedSignal() { return mScrollCompletedSignal; } bool Scrollable::DoConnectSignal(BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor) { Dali::BaseHandle handle(object); bool connected(true); Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(handle); if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_STARTED)) { scrollable.ScrollStartedSignal().Connect(tracker, functor); } else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_UPDATED)) { scrollable.ScrollUpdatedSignal().Connect(tracker, functor); } else if(0 == strcmp(signalName.c_str(), SIGNAL_SCROLL_COMPLETED)) { scrollable.ScrollCompletedSignal().Connect(tracker, functor); } else { // signalName does not match any signal connected = false; } return connected; } void Scrollable::SetProperty(BaseObject* object, Property::Index index, const Property::Value& value) { Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object)); if(scrollable) { Scrollable& scrollableImpl(GetImpl(scrollable)); switch(index) { case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR: { scrollableImpl.SetOvershootEffectColor(value.Get<Vector4>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED: { scrollableImpl.SetOvershootAnimationSpeed(value.Get<float>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ENABLED: { scrollableImpl.SetOvershootEnabled(value.Get<bool>()); break; } case Toolkit::Scrollable::Property::OVERSHOOT_SIZE: { scrollableImpl.SetOvershootSize(value.Get<Vector2>()); break; } case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION: { int alphaFunction = value.Get<int>(); if(alphaFunction >= AlphaFunction::DEFAULT && alphaFunction < AlphaFunction::COUNT) { scrollableImpl.mScrollToAlphaFunction = static_cast<AlphaFunction::BuiltinFunction>(alphaFunction); } break; } } } } Property::Value Scrollable::GetProperty(BaseObject* object, Property::Index index) { Property::Value value; Toolkit::Scrollable scrollable = Toolkit::Scrollable::DownCast(Dali::BaseHandle(object)); if(scrollable) { Scrollable& scrollableImpl(GetImpl(scrollable)); switch(index) { case Toolkit::Scrollable::Property::OVERSHOOT_EFFECT_COLOR: { value = scrollableImpl.GetOvershootEffectColor(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ANIMATION_SPEED: { value = scrollableImpl.GetOvershootAnimationSpeed(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_ENABLED: { value = scrollableImpl.IsOvershootEnabled(); break; } case Toolkit::Scrollable::Property::OVERSHOOT_SIZE: { value = scrollableImpl.mOvershootSize; break; } case Toolkit::Scrollable::Property::SCROLL_TO_ALPHA_FUNCTION: { value = static_cast<int>(scrollableImpl.mScrollToAlphaFunction); break; } } } return value; } } // namespace Internal } // namespace Toolkit } // namespace Dali
8,694
2,965
// Fill out your copyright notice in the Description page of Project Settings. #include "BuildingEscape.h" IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, BuildingEscape, "BuildingEscape" );
200
64
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SD_ANIMOBJS_HXX #define SD_ANIMOBJS_HXX #include <sfx2/dockwin.hxx> #include <vcl/fixed.hxx> #include <svtools/stdctrl.hxx> #include <vcl/group.hxx> #include <sfx2/ctrlitem.hxx> #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #include <vcl/field.hxx> #include <svx/dlgctrl.hxx> #include <sfx2/progress.hxx> #include <vcl/lstbox.hxx> #ifndef _SD_SDRESID_HXX #include "sdresid.hxx" #endif #include "misc/scopelock.hxx" class SdDrawDocument; class BitmapEx; namespace sd { class AnimationControllerItem; class View; //------------------------------------------------------------------------ enum BitmapAdjustment { BA_LEFT_UP, BA_LEFT, BA_LEFT_DOWN, BA_UP, BA_CENTER, BA_DOWN, BA_RIGHT_UP, BA_RIGHT, BA_RIGHT_DOWN }; //------------------------------------------------------------------------ class SdDisplay : public Control { private: BitmapEx aBitmapEx; Fraction aScale; public: SdDisplay( ::Window* pWin, SdResId Id ); ~SdDisplay(); virtual void Paint( const Rectangle& rRect ); void SetBitmapEx( BitmapEx* pBmpEx ); void SetScale( const Fraction& rFrac ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); }; //------------------------------------------------------------------------ class AnimationWindow : public SfxDockingWindow { friend class AnimationChildWindow; friend class AnimationControllerItem; public: AnimationWindow( SfxBindings* pBindings, SfxChildWindow *pCW, ::Window* pParent, const SdResId& rSdResId ); virtual ~AnimationWindow(); void AddObj( ::sd::View& rView ); void CreateAnimObj( ::sd::View& rView ); virtual void DataChanged( const DataChangedEvent& rDCEvt ); protected: virtual sal_Bool Close(); virtual void Resize(); virtual void FillInfo( SfxChildWinInfo& ) const; private: SdDisplay aCtlDisplay; ImageButton aBtnFirst; ImageButton aBtnReverse; ImageButton aBtnStop; ImageButton aBtnPlay; ImageButton aBtnLast; NumericField aNumFldBitmap; TimeField aTimeField; ListBox aLbLoopCount; FixedLine aGrpBitmap; ImageButton aBtnGetOneObject; ImageButton aBtnGetAllObjects; ImageButton aBtnRemoveBitmap; ImageButton aBtnRemoveAll; FixedText aFtCount; FixedInfo aFiCount; FixedLine aGrpAnimation; RadioButton aRbtGroup; RadioButton aRbtBitmap; FixedText aFtAdjustment; ListBox aLbAdjustment; PushButton aBtnCreateGroup; ::Window* pWin; List aBmpExList; List aTimeList; SdDrawDocument* pMyDoc; BitmapEx* pBitmapEx; Size aSize; Size aFltWinSize; Size aDisplaySize; Size aBmpSize; sal_Bool bMovie; sal_Bool bAllObjects; SfxBindings* pBindings; AnimationControllerItem* pControllerItem; ScopeLock maPlayLock; //------------------------------------ DECL_LINK( ClickFirstHdl, void * ); DECL_LINK( ClickStopHdl, void * ); DECL_LINK( ClickPlayHdl, void * ); DECL_LINK( ClickLastHdl, void * ); DECL_LINK( ClickGetObjectHdl, void * ); DECL_LINK( ClickRemoveBitmapHdl, void * ); DECL_LINK( ClickRbtHdl, void * ); DECL_LINK( ClickCreateGroupHdl, void * ); DECL_LINK( ModifyBitmapHdl, void * ); DECL_LINK( ModifyTimeHdl, void * ); void UpdateControl( sal_uLong nPos, sal_Bool bDisableCtrls = sal_False ); void ResetAttrs(); void WaitInEffect( sal_uLong nMilliSeconds, sal_uLong nTime, SfxProgress* pStbMgr ) const; Fraction GetScale(); }; /************************************************************************* |* |* ControllerItem fuer Animator |* \************************************************************************/ class AnimationControllerItem : public SfxControllerItem { public: AnimationControllerItem( sal_uInt16, AnimationWindow*, SfxBindings* ); protected: virtual void StateChanged( sal_uInt16 nSId, SfxItemState eState, const SfxPoolItem* pState ); private: AnimationWindow* pAnimationWin; }; } // end of namespace sd #endif
4,838
1,729
#include "gpuCgSpiritGadget.h" #include "cuNDArray_operators.h" #include "cuNDArray_elemwise.h" #include "cuNDArray_blas.h" #include "cuNDArray_utils.h" #include "cuNDArray_reductions.h" #include "GadgetMRIHeaders.h" #include "b1_map.h" #include "GPUTimer.h" #include "vector_td_utilities.h" #include "hoNDArray_fileio.h" #include "ismrmrd/xml.h" #include "gpuSenseGadget.h" namespace Gadgetron{ gpuCgSpiritGadget::gpuCgSpiritGadget() : is_configured_(false) , matrix_size_reported_(0), gpuSenseGadget() { } gpuCgSpiritGadget::~gpuCgSpiritGadget() {} int gpuCgSpiritGadget::process_config( ACE_Message_Block* mb ) { gpuSenseGadget::process_config(mb); number_of_iterations_ = number_of_iterations.value(); cg_limit_ = cg_limit.value(); kappa_ = kappa.value(); // Get the Ismrmrd header // ISMRMRD::IsmrmrdHeader h; ISMRMRD::deserialize(mb->rd_ptr(),h); if (h.encoding.size() != 1) { GDEBUG("This Gadget only supports one encoding space\n"); return GADGET_FAIL; } // Get the encoding space and trajectory description ISMRMRD::EncodingSpace e_space = h.encoding[0].encodedSpace; ISMRMRD::EncodingSpace r_space = h.encoding[0].reconSpace; ISMRMRD::EncodingLimits e_limits = h.encoding[0].encodingLimits; matrix_size_seq_ = uint64d2( r_space.matrixSize.x, r_space.matrixSize.y ); if (!is_configured_) { if (h.acquisitionSystemInformation) { channels_ = h.acquisitionSystemInformation->receiverChannels ? *h.acquisitionSystemInformation->receiverChannels : 1; } else { channels_ = 1; } // Allocate Spirit operators E_ = boost::make_shared< NFFTOperator<cuNDArray,float,2> >(); S_ = boost::make_shared< cuSpirit2DOperator<float> >(); S_->set_weight( kappa_ ); // Allocate preconditioner //D_ = boost::shared_ptr< cuCgPreconditioner<float_complext> >( new cuCgPreconditioner<float_complext>() ); // Allocate regularization image operator //R_ = boost::shared_ptr< cuImageOperator<float_complext> >( new cuImageOperator<float_complext>() ); //R_->set_weight( kappa_ ); // Setup solver cg_.set_encoding_operator( E_ ); // encoding matrix if( kappa_ > 0.0f ) cg_.add_regularization_operator( S_ ); // regularization matrix //cg_.add_regularization_operator( R_ ); // regularization matrix //cg_.set_preconditioner( D_ ); // preconditioning matrix cg_.set_max_iterations( number_of_iterations_ ); cg_.set_tc_tolerance( cg_limit_ ); cg_.set_output_mode( (this->output_convergence_) ? cuCgSolver<float_complext>::OUTPUT_VERBOSE : cuCgSolver<float_complext>::OUTPUT_SILENT); is_configured_ = true; } return GADGET_OK; } int gpuCgSpiritGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader> *m1, GadgetContainerMessage<GenericReconJob> *m2) { // Is this data for this gadget's set/slice? // if( m1->getObjectPtr()->set != set_number_ || m1->getObjectPtr()->slice != slice_number_ ) { // No, pass it downstream... return this->next()->putq(m1); } //GDEBUG("gpuCgSpiritGadget::process\n"); boost::shared_ptr<GPUTimer> process_timer; if( output_timing_ ) process_timer = boost::shared_ptr<GPUTimer>( new GPUTimer("gpuCgSpiritGadget::process()") ); if (!is_configured_) { GDEBUG("Data received before configuration was completed\n"); return GADGET_FAIL; } GenericReconJob* j = m2->getObjectPtr(); // Some basic validation of the incoming Spirit job if (!j->csm_host_.get() || !j->dat_host_.get() || !j->tra_host_.get() || !j->dcw_host_.get() || !j->reg_host_.get()) { GDEBUG("Received an incomplete Spirit job\n"); return GADGET_FAIL; } unsigned int samples = j->dat_host_->get_size(0); unsigned int channels = j->dat_host_->get_size(1); unsigned int rotations = samples / j->tra_host_->get_number_of_elements(); unsigned int frames = j->tra_host_->get_size(1)*rotations; if( samples%j->tra_host_->get_number_of_elements() ) { GDEBUG("Mismatch between number of samples (%d) and number of k-space coordinates (%d).\nThe first should be a multiplum of the latter.\n", samples, j->tra_host_->get_number_of_elements()); return GADGET_FAIL; } boost::shared_ptr< cuNDArray<floatd2> > traj(new cuNDArray<floatd2> (j->tra_host_.get())); boost::shared_ptr< cuNDArray<float> > dcw(new cuNDArray<float> (j->dcw_host_.get())); sqrt_inplace(dcw.get()); //Take square root to use for weighting boost::shared_ptr< cuNDArray<float_complext> > csm(new cuNDArray<float_complext> (j->csm_host_.get())); boost::shared_ptr< cuNDArray<float_complext> > device_samples(new cuNDArray<float_complext> (j->dat_host_.get())); cudaDeviceProp deviceProp; if( cudaGetDeviceProperties( &deviceProp, device_number_ ) != cudaSuccess) { GDEBUG( "Error: unable to query device properties.\n" ); return GADGET_FAIL; } unsigned int warp_size = deviceProp.warpSize; matrix_size_ = uint64d2( j->reg_host_->get_size(0), j->reg_host_->get_size(1) ); matrix_size_os_ = uint64d2(((static_cast<unsigned int>(std::ceil(matrix_size_[0]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size, ((static_cast<unsigned int>(std::ceil(matrix_size_[1]*oversampling_factor_))+warp_size-1)/warp_size)*warp_size); if( !matrix_size_reported_ ) { GDEBUG("Matrix size : [%d,%d] \n", matrix_size_[0], matrix_size_[1]); GDEBUG("Matrix size OS : [%d,%d] \n", matrix_size_os_[0], matrix_size_os_[1]); matrix_size_reported_ = true; } std::vector<size_t> image_dims = to_std_vector(matrix_size_); image_dims.push_back(frames); image_dims.push_back(channels); GDEBUG("Number of coils: %d %d \n",channels,image_dims.size()); E_->set_domain_dimensions(&image_dims); E_->set_codomain_dimensions(device_samples->get_dimensions().get()); E_->set_dcw(dcw); E_->setup( matrix_size_, matrix_size_os_, static_cast<float>(kernel_width_) ); E_->preprocess(traj.get()); boost::shared_ptr< cuNDArray<float_complext> > csm_device( new cuNDArray<float_complext>( csm.get() )); S_->set_calibration_kernels(csm_device); S_->set_domain_dimensions(&image_dims); S_->set_codomain_dimensions(&image_dims); /* boost::shared_ptr< cuNDArray<float_complext> > reg_image(new cuNDArray<float_complext> (j->reg_host_.get())); R_->compute(reg_image.get()); // Define preconditioning weights boost::shared_ptr< cuNDArray<float> > _precon_weights = sum(abs_square(csm.get()).get(), 2); boost::shared_ptr<cuNDArray<float> > R_diag = R_->get(); *R_diag *= float(kappa_); *_precon_weights += *R_diag; R_diag.reset(); reciprocal_sqrt_inplace(_precon_weights.get()); boost::shared_ptr< cuNDArray<float_complext> > precon_weights = real_to_complex<float_complext>( _precon_weights.get() ); _precon_weights.reset(); D_->set_weights( precon_weights ); */ /*{ static int counter = 0; char filename[256]; sprintf((char*)filename, "_traj_%d.real", counter); write_nd_array<floatd2>( traj->to_host().get(), filename ); sprintf((char*)filename, "_dcw_%d.real", counter); write_nd_array<float>( dcw->to_host().get(), filename ); sprintf((char*)filename, "_csm_%d.cplx", counter); write_nd_array<float_complext>( csm->to_host().get(), filename ); sprintf((char*)filename, "_samples_%d.cplx", counter); write_nd_array<float_complext>( device_samples->to_host().get(), filename ); sprintf((char*)filename, "_reg_%d.cplx", counter); write_nd_array<float_complext>( reg_image->to_host().get(), filename ); counter++; }*/ // Invoke solver // boost::shared_ptr< cuNDArray<float_complext> > cgresult; { boost::shared_ptr<GPUTimer> solve_timer; if( output_timing_ ) solve_timer = boost::shared_ptr<GPUTimer>( new GPUTimer("gpuCgSpiritGadget::solve()") ); cgresult = cg_.solve(device_samples.get()); if( output_timing_ ) solve_timer.reset(); } if (!cgresult.get()) { GDEBUG("Iterative_spirit_compute failed\n"); return GADGET_FAIL; } /* static int counter = 0; char filename[256]; sprintf((char*)filename, "recon_%d.real", counter); write_nd_array<float>( abs(cgresult.get())->to_host().get(), filename ); counter++; */ // If the recon matrix size exceeds the sequence matrix size then crop if( matrix_size_seq_ != matrix_size_ ) *cgresult = crop<float_complext,2>( (matrix_size_-matrix_size_seq_)>>1, matrix_size_seq_, *cgresult ); // Combine coil images // cgresult = real_to_complex<float_complext>(sqrt(sum(abs_square(cgresult.get()).get(), 3).get()).get()); // RSS //cgresult = sum(cgresult.get(), 2); // Pass on the reconstructed images // put_frames_on_que(frames,rotations,j,cgresult.get()); frame_counter_ += frames; if( output_timing_ ) process_timer.reset(); m1->release(); return GADGET_OK; } GADGET_FACTORY_DECLARE(gpuCgSpiritGadget) }
9,353
3,437
#include <algorithm> #include <cmath> #include <iostream> #include <iomanip> #include <string> #include <vector> #include "lambda.hpp" using namespace std; bool lessLength(const string &f, const string &s) { return f.length() < s.length(); } void lambda() { vector<string> myStrVec = {"12345", "123456", "1234", "1", "12", "123", "12345"}; cout << "\n\nSortieren mit lessLength():\n"; sort(myStrVec.begin(), myStrVec.end(), lessLength); for (auto v : myStrVec) cout << v << " "; cout << "\n\nSortieren mit einer lambda Funktion:\n"; sort(myStrVec.begin(), myStrVec.end(), [](const string &f, const string &s) { return f.length() < s.length(); }); for (auto v : myStrVec) cout << v << " "; cout << "\n\nSortieren mit einer lambda Funktion:\n"; sort(myStrVec.begin(), myStrVec.end(), [](const string &f, const string &s) { return f.length() > s.length(); }); for (auto v : myStrVec) cout << v << " "; cout << "\n"; // for_each läuft durch alle Elemte des Vektors und wendet die Funktion auf jedes Element an for_each(myStrVec.begin(), myStrVec.end(), [](const string &s) { cout << s << ", "; }); cout << "\n\nAusgeben (foreach) mit einer lambda Funktion:\n"; vector<int> myVec1{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; cout << "i->i*i: "; for_each(myVec1.begin(), myVec1.end(), [](int &i) { i = i * i; }); for (auto v : myVec1) cout << v << " "; cout << endl; vector<double> myVec2{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; for_each(myVec2.begin(), myVec2.end(), [](double &i) { i = sqrt(i); }); cout << "i->sqrt(i): "; for (auto v : myVec2) cout << fixed << setprecision(2) << v << " "; // fixed verhindert exponentialschreibweise (z.B. 1.0e-10) // Nachkommastellen auf 2 begrenzt mit setprecision cout << "\n\n"; } void lambda_captures() { cout << endl; string copy = "original"; string ref = "original"; auto lambda = [copy, &ref] { cout << copy << " " << ref << endl; }; lambda(); copy = "changed"; ref = "changed"; lambda(); copy = "changed again"; ref = "changed again"; lambda(); cout << endl; } void lambda_params() { auto addTwoNumbers = [](int a, int b){ return a + b; }; cout << endl; cout << "addTwoNumbers(2000, 17): " << addTwoNumbers(2000, 17) << endl; cout << "addTwoNumbers(2000, 21): " << addTwoNumbers(2000, 21) << endl; }
2,441
949
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <gtest/gtest.h> #include <seqan3/alphabet/mask/mask.hpp> #include "../semi_alphabet_test_template.hpp" #include "../semi_alphabet_constexpr_test_template.hpp" INSTANTIATE_TYPED_TEST_SUITE_P(mask, semi_alphabet_test, seqan3::mask, ); INSTANTIATE_TYPED_TEST_SUITE_P(mask, semi_alphabet_constexpr, seqan3::mask, ); TEST(mask, assign_rank) { // l-value seqan3::mask lmask; EXPECT_EQ(lmask.assign_rank(1), seqan3::mask::masked); EXPECT_TRUE(lmask.to_rank()); EXPECT_EQ(lmask.assign_rank(0), seqan3::mask::unmasked); EXPECT_FALSE(lmask.to_rank()); EXPECT_EQ(lmask.assign_rank(true), seqan3::mask::masked); EXPECT_EQ(lmask.assign_rank(false), seqan3::mask::unmasked); // const l-value lmask.assign_rank(1); seqan3::mask const clmask{lmask}; EXPECT_TRUE(clmask.to_rank()); // r-value seqan3::mask rmask{lmask}; EXPECT_EQ(std::move(rmask).to_rank(), lmask.to_rank()); EXPECT_TRUE((std::is_same_v<decltype(std::move(rmask)), seqan3::mask &&>)); EXPECT_EQ(std::move(rmask).assign_rank(1), seqan3::mask::masked); EXPECT_TRUE(std::move(rmask).to_rank()); EXPECT_EQ(std::move(rmask).assign_rank(0), seqan3::mask::unmasked); EXPECT_FALSE(std::move(rmask).to_rank()); EXPECT_EQ(std::move(rmask).assign_rank(true), seqan3::mask::masked); EXPECT_EQ(std::move(rmask).assign_rank(false), seqan3::mask::unmasked); // const r-value seqan3::mask const crmask{lmask}; EXPECT_EQ(std::move(crmask).to_rank(), lmask.to_rank()); EXPECT_TRUE((std::is_same_v<decltype(std::move(crmask)), seqan3::mask const &&>)); }
2,159
823
/******************************************************************************* * File: Key_name_from_public_data.cpp * Description: Calculate the key's name from its public data (TPMT_PUBLIC) * * Author: Chris Newton * * Created: Tueday 29 May 2018 * * (C) Copyright 2018, University of Surrey. * *******************************************************************************/ /******************************************************************************* * * * (C) Copyright 2019 University of Surrey * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright notice, * * this list of conditions and the following disclaimer in the documentation * * and/or other materials provided with the distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * *******************************************************************************/ #include <iostream> #include "Marshal_public_data.h" #include "Byte_buffer.h" #include "Sha.h" Byte_buffer get_key_name( TPMT_PUBLIC* public_data ) { Byte_buffer marshalled_public_area=marshal_public_data_T(public_data); // std::cout << "Marshalled area: size: " << marshalled_public_area.size() << '\n'; // std::cout << "Marshalled area: data: " << marshalled_public_area.to_hex_string() << '\n'; Byte_buffer sha256_ma=sha256_bb(marshalled_public_area); // std::cout << "SHA256 of marshalled area: " << sha256_ma.to_hex_string() << '\n'; Byte_buffer name{0x00,0x0b}; // nameAlg (0x0b for sha256) name+=sha256_ma; // std::cout << " Key name: size: " << name.size() << '\n'; // std::cout << " Key name: data: " << name.to_hex_string() << '\n'; return name; } Byte_buffer get_key_name_bb( Byte_buffer key_pd ) { Byte_buffer name; TPM2B_PUBLIC tpm2b_pub; TPM_RC rc=unmarshal_public_data_B(key_pd, &tpm2b_pub); if (rc!=0) { return name; // Leave it to others to sort out } return get_key_name(&tpm2b_pub.publicArea); }
3,685
1,149
Matrix4i m = Matrix4i::Random(); cout << "Here is the matrix m:" << endl << m << endl; cout << "Here is m.block<2,2>(1,1):" << endl << m.block<2,2>(1,1) << endl; m.block<2,2>(1,1).setZero(); cout << "Now the matrix m is:" << endl << m << endl;
249
100
#include "CppUnitLite/TestHarness.h" #include "Stack.h" #include <string> SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } TEST( Stack, creation ) { Stack s; LONGS_EQUAL(0, s.size()); std::string b = "asa"; CHECK_EQUAL("asa", b); }
288
120
#include "korean/core/chars/distance.h" #include <gmock/gmock.h> #include <gtest/gtest.h> using namespace korean::chars; TEST(distance, calculateLevenshtein) { ASSERT_EQ(calculateLevenshteinDistance(L"abcdef", L"abdef"), 1); ASSERT_EQ(calculateLevenshteinDistance(L"안녕", L"안하세요"), 3); ASSERT_EQ(calculateLevenshteinDistance(L"에어팟", L"에앞ㅏㅅ"), 3); } TEST(distance, calculateDecomposedLevenshtein) { ASSERT_EQ(calculateDecomposedLevenshteinDistance(L"에어팟", L"에앞ㅏㅅ"), 1); ASSERT_EQ(calculateDecomposedLevenshteinDistance(L"에어팟", L"에어팟"), 0); ASSERT_EQ(calculateDecomposedLevenshteinDistance(L"에어팟", L"에아팟"), 1); } TEST(distance, getLongestCommonSubstring) { ASSERT_EQ(getLongestCommonSubstring(L"안녕하세요~", L"네 안녕하세요"), std::make_pair((size_t)0, (size_t)5)); ASSERT_EQ(getLongestCommonSubstring(L"커피치과의원", L"커피치과 가보세요"), std::make_pair((size_t)0, (size_t)4)); ASSERT_EQ(getLongestCommonSubstring( L"korean이라는 라이브러리를 계속 업데이트하려고 하는데, 이게 잘 될까요? 일단 열심히 해보려고요. 형태소 분석기도 곧 넣어보고요.", L"형태소분석기"), std::make_pair((size_t)57, (size_t)3)); }
1,091
633
// // Buffer.cpp // ASAE // // Created by Benjamin G Fields on 4/2/18. // Copyright © 2018 Benjamin G Fields. All rights reserved. // // Description: defines the implementatin of the buffer object #include "Buffer.hpp" //Description:return the state of the buffer by saying if it is full,empty or still has space int Buffer::getState(){ if (queue.size() == capacity) { return FULL; } else if(queue.size()== 0){ return EMPTY; } else{ return SPACE_LEFT; } } int Buffer::getNumInQueue(){ return (int)queue.size(); } //Description:return the next event in the queue Event Buffer::GetNext(){ Event E = queue.front(); queue.pop(); return E; } //Description: put the event in the buffer queue void Buffer::placeInBuffer(Event E){ queue.push(E); }
784
267
#include "basic/talker.h" #include <gtest/gtest.h> class MyTestSuite : public ::testing::Test { public: MyTestSuite(){} ~MyTestSuite(){} }; TEST_F(MyTestSuite, lowValue){ Talker rt; int initial_value = 3; int value = rt.doSomeMath(initial_value); ASSERT_EQ(value, initial_value+5) << "Value should be its initial value plus 5"; } TEST_F(MyTestSuite, highValue){ Talker rt; int initial_value = 49; int value = rt.doSomeMath(initial_value); ASSERT_EQ(value, 0) << "Value should be 0"; } //int main(int argc, char **argv) { // testing::InitGoogleTest(&argc, argv); // ros::init(argc, argv, "TestNode"); // return RUN_ALL_TESTS(); //}
650
275
// Boost.Signals2 library // Copyright Douglas Gregor 2001-2004. // Copyright Frank Mori Hess 2007-2008. // Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // For more information, see http://www.boost.org #ifndef BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP #define BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP #include <boost/assert.hpp> #include <boost/aligned_storage.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/optional.hpp> #include <boost/scoped_ptr.hpp> #include <boost/signals2/connection.hpp> #include <boost/signals2/slot_base.hpp> #include <boost/signals2/detail/auto_buffer.hpp> #include <boost/signals2/detail/unique_lock.hpp> #include <boost/weak_ptr.hpp> namespace boost { namespace signals2 { namespace detail { template<typename ResultType, typename Function> class slot_call_iterator_cache { public: slot_call_iterator_cache(const Function &f): f(f), connected_slot_count(0), disconnected_slot_count(0) {} optional<ResultType> result; typedef auto_buffer<boost::shared_ptr<void>, store_n_objects<10> > tracked_ptrs_type; tracked_ptrs_type tracked_ptrs; Function f; unsigned connected_slot_count; unsigned disconnected_slot_count; }; // Generates a slot call iterator. Essentially, this is an iterator that: // - skips over disconnected slots in the underlying list // - calls the connected slots when dereferenced // - caches the result of calling the slots template<typename Function, typename Iterator, typename ConnectionBody> class slot_call_iterator_t : public boost::iterator_facade<slot_call_iterator_t<Function, Iterator, ConnectionBody>, typename Function::result_type, boost::single_pass_traversal_tag, typename Function::result_type const&> { typedef boost::iterator_facade<slot_call_iterator_t<Function, Iterator, ConnectionBody>, typename Function::result_type, boost::single_pass_traversal_tag, typename Function::result_type const&> inherited; typedef typename Function::result_type result_type; friend class boost::iterator_core_access; public: slot_call_iterator_t(Iterator iter_in, Iterator end_in, slot_call_iterator_cache<result_type, Function> &c): iter(iter_in), end(end_in), cache(&c), callable_iter(end_in) { lock_next_callable(); } typename inherited::reference dereference() const { if (!cache->result) { try { cache->result.reset(cache->f(*iter)); } catch(expired_slot &) { (*iter)->disconnect(); throw; } } return cache->result.get(); } void increment() { ++iter; lock_next_callable(); cache->result.reset(); } bool equal(const slot_call_iterator_t& other) const { return iter == other.iter; } private: typedef unique_lock<connection_body_base> lock_type; void lock_next_callable() const { if(iter == callable_iter) { return; } for(;iter != end; ++iter) { lock_type lock(**iter); cache->tracked_ptrs.clear(); (*iter)->nolock_grab_tracked_objects(std::back_inserter(cache->tracked_ptrs)); if((*iter)->nolock_nograb_connected()) { ++cache->connected_slot_count; }else { ++cache->disconnected_slot_count; } if((*iter)->nolock_nograb_blocked() == false) { callable_iter = iter; break; } } if(iter == end) { callable_iter = end; } } mutable Iterator iter; Iterator end; slot_call_iterator_cache<result_type, Function> *cache; mutable Iterator callable_iter; }; } // end namespace detail } // end namespace BOOST_SIGNALS_NAMESPACE } // end namespace boost #endif // BOOST_SIGNALS2_SLOT_CALL_ITERATOR_HPP
4,648
1,410
#include "pch.h" #include "process.h" std::vector<ProcessInfo> GetProcessInfo() { STARTUPINFO st; PROCESS_INFORMATION pi; PROCESSENTRY32 ps; HANDLE hSnapshot; HANDLE processHandle = NULL; std::vector<ProcessInfo> PInfo; ZeroMemory(&st, sizeof(STARTUPINFO)); ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); st.cb = sizeof(STARTUPINFO); ZeroMemory(&ps, sizeof(PROCESSENTRY32)); ps.dwSize = sizeof(PROCESSENTRY32); hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnapshot == INVALID_HANDLE_VALUE) { return PInfo; } if (!Process32First(hSnapshot, &ps)) { return PInfo; } do { processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ps.th32ProcessID); TCHAR filename[MAX_PATH]; if (processHandle != NULL) { if (GetModuleFileNameEx(processHandle, NULL, filename, MAX_PATH) == 0) { _tcscpy_s(filename, MAX_PATH, _T("NULL_Module")); } CloseHandle(processHandle); } else { _tcscpy_s(filename, MAX_PATH, _T("NULL_Process")); } PInfo.emplace_back(ps.th32ProcessID, WCHAR2String(ps.szExeFile), WCHAR2String(filename)); } while (Process32Next(hSnapshot, &ps)); CloseHandle(hSnapshot); std::sort(PInfo.begin(), PInfo.end()); return PInfo; } std::set<std::string> get_process_name() { STARTUPINFO st; PROCESS_INFORMATION pi; PROCESSENTRY32 ps; HANDLE hSnapshot; std::vector<ProcessInfo> PInfo; ZeroMemory(&st, sizeof(STARTUPINFO)); ZeroMemory(&pi, sizeof(PROCESS_INFORMATION)); st.cb = sizeof(STARTUPINFO); ZeroMemory(&ps, sizeof(PROCESSENTRY32)); ps.dwSize = sizeof(PROCESSENTRY32); hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); std::set<std::string> process_name; if (hSnapshot == INVALID_HANDLE_VALUE) { return process_name; } if (!Process32First(hSnapshot, &ps)) { return process_name; } do { process_name.insert(WCHAR2String(ps.szExeFile)); } while (Process32Next(hSnapshot, &ps)); CloseHandle(hSnapshot); return process_name; }
2,074
852
/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * 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 <qmdnsengine/abstractserver.h> #include <qmdnsengine/dns.h> #include <qmdnsengine/message.h> #include <qmdnsengine/prober.h> #include <qmdnsengine/query.h> #include "prober_p.h" using namespace QMdnsEngine; ProberPrivate::ProberPrivate(Prober *prober, AbstractServer *server, const Record &record) : QObject(prober), server(server), confirmed(false), proposedRecord(record), suffix(1), q(prober) { // All records should contain at least one "." int index = record.name().indexOf('.'); name = record.name().left(index); type = record.name().mid(index); connect(server, &AbstractServer::messageReceived, this, &ProberPrivate::onMessageReceived); connect(&timer, &QTimer::timeout, this, &ProberPrivate::onTimeout); timer.setSingleShot(true); assertRecord(); } void ProberPrivate::assertRecord() { // Use the current suffix to set the name of the proposed record proposedRecord.setName(suffix == 1 ? name + type : name + "-" + QByteArray::number(suffix) + type); // Broadcast a query for the proposed name (using an ANY query) and // include the proposed record in the query Query query; query.setName(proposedRecord.name()); query.setType(ANY); Message message; message.addQuery(query); message.addRecord(proposedRecord); server->sendMessageToAll(message); // Wait two seconds to confirm it is unique timer.stop(); timer.start(2 * 1000); } void ProberPrivate::onMessageReceived(const Message &message) { // If the response matches the proposed record, increment the suffix and // try with the new name if (confirmed || !message.isResponse()) { return; } const auto records = message.records(); for (const Record &record : records) { if (record.name() == proposedRecord.name() && record.type() == proposedRecord.type()) { ++suffix; assertRecord(); } } } void ProberPrivate::onTimeout() { confirmed = true; emit q->nameConfirmed(proposedRecord.name()); } Prober::Prober(AbstractServer *server, const Record &record, QObject *parent) : QObject(parent), d(new ProberPrivate(this, server, record)) { }
3,386
1,058
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/extensions/update_manifest.h" #include <algorithm> #include "base/memory/scoped_ptr.h" #include "base/stl_util.h" #include "base/string_util.h" #include "base/string_number_conversions.h" #include "base/stringprintf.h" #include "base/version.h" #include "chrome/common/libxml_utils.h" #include "libxml/tree.h" static const char* kExpectedGupdateProtocol = "2.0"; static const char* kExpectedGupdateXmlns = "http://www.google.com/update2/response"; UpdateManifest::Result::Result() {} UpdateManifest::Result::~Result() {} UpdateManifest::Results::Results() : daystart_elapsed_seconds(kNoDaystart) {} UpdateManifest::Results::~Results() {} UpdateManifest::UpdateManifest() { } UpdateManifest::~UpdateManifest() {} void UpdateManifest::ParseError(const char* details, ...) { va_list args; va_start(args, details); if (errors_.length() > 0) { // TODO(asargent) make a platform abstracted newline? errors_ += "\r\n"; } base::StringAppendV(&errors_, details, args); va_end(args); } // Checks whether a given node's name matches |expected_name| and // |expected_namespace|. static bool TagNameEquals(const xmlNode* node, const char* expected_name, const xmlNs* expected_namespace) { if (node->ns != expected_namespace) { return false; } return 0 == strcmp(expected_name, reinterpret_cast<const char*>(node->name)); } // Returns child nodes of |root| with name |name| in namespace |xml_namespace|. static std::vector<xmlNode*> GetChildren(xmlNode* root, xmlNs* xml_namespace, const char* name) { std::vector<xmlNode*> result; for (xmlNode* child = root->children; child != NULL; child = child->next) { if (!TagNameEquals(child, name, xml_namespace)) { continue; } result.push_back(child); } return result; } // Returns the value of a named attribute, or the empty string. static std::string GetAttribute(xmlNode* node, const char* attribute_name) { const xmlChar* name = reinterpret_cast<const xmlChar*>(attribute_name); for (xmlAttr* attr = node->properties; attr != NULL; attr = attr->next) { if (!xmlStrcmp(attr->name, name) && attr->children && attr->children->content) { return std::string(reinterpret_cast<const char*>( attr->children->content)); } } return std::string(); } // This is used for the xml parser to report errors. This assumes the context // is a pointer to a std::string where the error message should be appended. static void XmlErrorFunc(void *context, const char *message, ...) { va_list args; va_start(args, message); std::string* error = static_cast<std::string*>(context); base::StringAppendV(error, message, args); va_end(args); } // Utility class for cleaning up the xml document when leaving a scope. class ScopedXmlDocument { public: explicit ScopedXmlDocument(xmlDocPtr document) : document_(document) {} ~ScopedXmlDocument() { if (document_) xmlFreeDoc(document_); } xmlDocPtr get() { return document_; } private: xmlDocPtr document_; }; // Returns a pointer to the xmlNs on |node| with the |expected_href|, or // NULL if there isn't one with that href. static xmlNs* GetNamespace(xmlNode* node, const char* expected_href) { const xmlChar* href = reinterpret_cast<const xmlChar*>(expected_href); for (xmlNs* ns = node->ns; ns != NULL; ns = ns->next) { if (ns->href && !xmlStrcmp(ns->href, href)) { return ns; } } return NULL; } // Helper function that reads in values for a single <app> tag. It returns a // boolean indicating success or failure. On failure, it writes a error message // into |error_detail|. static bool ParseSingleAppTag(xmlNode* app_node, xmlNs* xml_namespace, UpdateManifest::Result* result, std::string *error_detail) { // Read the extension id. result->extension_id = GetAttribute(app_node, "appid"); if (result->extension_id.length() == 0) { *error_detail = "Missing appid on app node"; return false; } // Get the updatecheck node. std::vector<xmlNode*> updates = GetChildren(app_node, xml_namespace, "updatecheck"); if (updates.size() > 1) { *error_detail = "Too many updatecheck tags on app (expecting only 1)."; return false; } if (updates.empty()) { *error_detail = "Missing updatecheck on app."; return false; } xmlNode *updatecheck = updates[0]; if (GetAttribute(updatecheck, "status") == "noupdate") { return true; } // Find the url to the crx file. result->crx_url = GURL(GetAttribute(updatecheck, "codebase")); if (!result->crx_url.is_valid()) { *error_detail = "Invalid codebase url: '"; *error_detail += GetAttribute(updatecheck, "codebase"); *error_detail += "'."; return false; } // Get the version. result->version = GetAttribute(updatecheck, "version"); if (result->version.length() == 0) { *error_detail = "Missing version for updatecheck."; return false; } scoped_ptr<Version> version(Version::GetVersionFromString(result->version)); if (!version.get()) { *error_detail = "Invalid version: '"; *error_detail += result->version; *error_detail += "'."; return false; } // Get the minimum browser version (not required). result->browser_min_version = GetAttribute(updatecheck, "prodversionmin"); if (result->browser_min_version.length()) { scoped_ptr<Version> browser_min_version( Version::GetVersionFromString(result->browser_min_version)); if (!browser_min_version.get()) { *error_detail = "Invalid prodversionmin: '"; *error_detail += result->browser_min_version; *error_detail += "'."; return false; } } // package_hash is optional. It is only required for blacklist. It is a // sha256 hash of the package in hex format. result->package_hash = GetAttribute(updatecheck, "hash"); return true; } bool UpdateManifest::Parse(const std::string& manifest_xml) { results_.list.resize(0); results_.daystart_elapsed_seconds = kNoDaystart; errors_ = ""; if (manifest_xml.length() < 1) { ParseError("Empty xml"); return false; } std::string xml_errors; ScopedXmlErrorFunc error_func(&xml_errors, &XmlErrorFunc); // Start up the xml parser with the manifest_xml contents. ScopedXmlDocument document(xmlParseDoc( reinterpret_cast<const xmlChar*>(manifest_xml.c_str()))); if (!document.get()) { ParseError("%s", xml_errors.c_str()); return false; } xmlNode *root = xmlDocGetRootElement(document.get()); if (!root) { ParseError("Missing root node"); return false; } // Look for the required namespace declaration. xmlNs* gupdate_ns = GetNamespace(root, kExpectedGupdateXmlns); if (!gupdate_ns) { ParseError("Missing or incorrect xmlns on gupdate tag"); return false; } if (!TagNameEquals(root, "gupdate", gupdate_ns)) { ParseError("Missing gupdate tag"); return false; } // Check for the gupdate "protocol" attribute. if (GetAttribute(root, "protocol") != kExpectedGupdateProtocol) { ParseError("Missing/incorrect protocol on gupdate tag " "(expected '%s')", kExpectedGupdateProtocol); return false; } // Parse the first <daystart> if it's present. std::vector<xmlNode*> daystarts = GetChildren(root, gupdate_ns, "daystart"); if (!daystarts.empty()) { xmlNode* first = daystarts[0]; std::string elapsed_seconds = GetAttribute(first, "elapsed_seconds"); int parsed_elapsed = kNoDaystart; if (base::StringToInt(elapsed_seconds, &parsed_elapsed)) { results_.daystart_elapsed_seconds = parsed_elapsed; } } // Parse each of the <app> tags. std::vector<xmlNode*> apps = GetChildren(root, gupdate_ns, "app"); for (unsigned int i = 0; i < apps.size(); i++) { Result current; std::string error; if (!ParseSingleAppTag(apps[i], gupdate_ns, &current, &error)) { ParseError("%s", error.c_str()); } else { results_.list.push_back(current); } } return true; }
8,323
2,650
/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2016 The Khronos Group 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. * *//* * \file vktPipelineMultisampleBaseResolveAndPerSampleFetch.cpp * \brief Base class for tests that check results of multisample resolve * and/or values of individual samples *//*--------------------------------------------------------------------*/ #include "vktPipelineMultisampleBaseResolveAndPerSampleFetch.hpp" #include "vktPipelineMakeUtil.hpp" #include "vkBarrierUtil.hpp" #include "vkBuilderUtil.hpp" #include "vkQueryUtil.hpp" #include "vkTypeUtil.hpp" #include "vkCmdUtil.hpp" #include "vkTypeUtil.hpp" #include "vkObjUtil.hpp" #include "tcuTestLog.hpp" #include <vector> namespace vkt { namespace pipeline { namespace multisample { using namespace vk; void MSCaseBaseResolveAndPerSampleFetch::initPrograms (vk::SourceCollections& programCollection) const { // Create vertex shader std::ostringstream vs; vs << "#version 440\n" << "layout(location = 0) in vec4 vs_in_position_ndc;\n" << "\n" << "out gl_PerVertex {\n" << " vec4 gl_Position;\n" << "};\n" << "void main (void)\n" << "{\n" << " gl_Position = vs_in_position_ndc;\n" << "}\n"; programCollection.glslSources.add("per_sample_fetch_vs") << glu::VertexSource(vs.str()); // Create fragment shader std::ostringstream fs; fs << "#version 440\n" << "\n" << "layout(location = 0) out vec4 fs_out_color;\n" << "\n" << "layout(set = 0, binding = 0, input_attachment_index = 0) uniform subpassInputMS imageMS;\n" << "\n" << "layout(set = 0, binding = 1, std140) uniform SampleBlock {\n" << " int sampleNdx;\n" << "};\n" << "void main (void)\n" << "{\n" << " fs_out_color = subpassLoad(imageMS, sampleNdx);\n" << "}\n"; programCollection.glslSources.add("per_sample_fetch_fs") << glu::FragmentSource(fs.str()); } VkPipelineMultisampleStateCreateInfo MSInstanceBaseResolveAndPerSampleFetch::getMSStateCreateInfo (const ImageMSParams& imageMSParams) const { const VkPipelineMultisampleStateCreateInfo multisampleStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineMultisampleStateCreateFlags)0u, // VkPipelineMultisampleStateCreateFlags flags; imageMSParams.numSamples, // VkSampleCountFlagBits rasterizationSamples; VK_TRUE, // VkBool32 sampleShadingEnable; 1.0f, // float minSampleShading; DE_NULL, // const VkSampleMask* pSampleMask; VK_FALSE, // VkBool32 alphaToCoverageEnable; VK_FALSE, // VkBool32 alphaToOneEnable; }; return multisampleStateInfo; } const VkDescriptorSetLayout* MSInstanceBaseResolveAndPerSampleFetch::createMSPassDescSetLayout(const ImageMSParams& imageMSParams) { DE_UNREF(imageMSParams); return DE_NULL; } const VkDescriptorSet* MSInstanceBaseResolveAndPerSampleFetch::createMSPassDescSet(const ImageMSParams& imageMSParams, const VkDescriptorSetLayout* descSetLayout) { DE_UNREF(imageMSParams); DE_UNREF(descSetLayout); return DE_NULL; } tcu::TestStatus MSInstanceBaseResolveAndPerSampleFetch::iterate (void) { const InstanceInterface& instance = m_context.getInstanceInterface(); const DeviceInterface& deviceInterface = m_context.getDeviceInterface(); const VkDevice device = m_context.getDevice(); const VkPhysicalDevice physicalDevice = m_context.getPhysicalDevice(); Allocator& allocator = m_context.getDefaultAllocator(); const VkQueue queue = m_context.getUniversalQueue(); const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex(); VkImageCreateInfo imageMSInfo; VkImageCreateInfo imageRSInfo; const deUint32 firstSubpassAttachmentsCount = 2u; // Check if image size does not exceed device limits validateImageSize(instance, physicalDevice, m_imageType, m_imageMSParams.imageSize); // Check if device supports image format as color attachment validateImageFeatureFlags(instance, physicalDevice, mapTextureFormat(m_imageFormat), VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT); imageMSInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageMSInfo.pNext = DE_NULL; imageMSInfo.flags = 0u; imageMSInfo.imageType = mapImageType(m_imageType); imageMSInfo.format = mapTextureFormat(m_imageFormat); imageMSInfo.extent = makeExtent3D(getLayerSize(m_imageType, m_imageMSParams.imageSize)); imageMSInfo.arrayLayers = getNumLayers(m_imageType, m_imageMSParams.imageSize); imageMSInfo.mipLevels = 1u; imageMSInfo.samples = m_imageMSParams.numSamples; imageMSInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageMSInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageMSInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT; imageMSInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageMSInfo.queueFamilyIndexCount = 0u; imageMSInfo.pQueueFamilyIndices = DE_NULL; if (m_imageType == IMAGE_TYPE_CUBE || m_imageType == IMAGE_TYPE_CUBE_ARRAY) { imageMSInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; } validateImageInfo(instance, physicalDevice, imageMSInfo); const de::UniquePtr<Image> imageMS(new Image(deviceInterface, device, allocator, imageMSInfo, MemoryRequirement::Any)); imageRSInfo = imageMSInfo; imageRSInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageRSInfo.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; validateImageInfo(instance, physicalDevice, imageRSInfo); const de::UniquePtr<Image> imageRS(new Image(deviceInterface, device, allocator, imageRSInfo, MemoryRequirement::Any)); const deUint32 numSamples = static_cast<deUint32>(imageMSInfo.samples); std::vector<de::SharedPtr<Image> > imagesPerSampleVec(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imagesPerSampleVec[sampleNdx] = de::SharedPtr<Image>(new Image(deviceInterface, device, allocator, imageRSInfo, MemoryRequirement::Any)); } // Create render pass std::vector<VkAttachmentDescription> attachments(firstSubpassAttachmentsCount + numSamples); { const VkAttachmentDescription attachmentMSDesc = { (VkAttachmentDescriptionFlags)0u, // VkAttachmentDescriptionFlags flags; imageMSInfo.format, // VkFormat format; imageMSInfo.samples, // VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout initialLayout; VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL // VkImageLayout finalLayout; }; attachments[0] = attachmentMSDesc; const VkAttachmentDescription attachmentRSDesc = { (VkAttachmentDescriptionFlags)0u, // VkAttachmentDescriptionFlags flags; imageRSInfo.format, // VkFormat format; imageRSInfo.samples, // VkSampleCountFlagBits samples; VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp; VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp; VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp; VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout initialLayout; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout finalLayout; }; attachments[1] = attachmentRSDesc; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { attachments[firstSubpassAttachmentsCount + sampleNdx] = attachmentRSDesc; } } const VkAttachmentReference attachmentMSColorRef = { 0u, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; const VkAttachmentReference attachmentMSInputRef = { 0u, // deUint32 attachment; VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL // VkImageLayout layout; }; const VkAttachmentReference attachmentRSColorRef = { 1u, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; std::vector<VkAttachmentReference> perSampleAttachmentRef(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const VkAttachmentReference attachmentRef = { firstSubpassAttachmentsCount + sampleNdx, // deUint32 attachment; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // VkImageLayout layout; }; perSampleAttachmentRef[sampleNdx] = attachmentRef; } std::vector<deUint32> preserveAttachments(1u + numSamples); for (deUint32 attachNdx = 0u; attachNdx < 1u + numSamples; ++attachNdx) { preserveAttachments[attachNdx] = 1u + attachNdx; } std::vector<VkSubpassDescription> subpasses(1u + numSamples); std::vector<VkSubpassDependency> subpassDependencies(numSamples); const VkSubpassDescription firstSubpassDesc = { (VkSubpassDescriptionFlags)0u, // VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; 0u, // deUint32 inputAttachmentCount; DE_NULL, // const VkAttachmentReference* pInputAttachments; 1u, // deUint32 colorAttachmentCount; &attachmentMSColorRef, // const VkAttachmentReference* pColorAttachments; &attachmentRSColorRef, // const VkAttachmentReference* pResolveAttachments; DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment; 0u, // deUint32 preserveAttachmentCount; DE_NULL // const deUint32* pPreserveAttachments; }; subpasses[0] = firstSubpassDesc; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const VkSubpassDescription subpassDesc = { (VkSubpassDescriptionFlags)0u, // VkSubpassDescriptionFlags flags; VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint pipelineBindPoint; 1u, // deUint32 inputAttachmentCount; &attachmentMSInputRef, // const VkAttachmentReference* pInputAttachments; 1u, // deUint32 colorAttachmentCount; &perSampleAttachmentRef[sampleNdx], // const VkAttachmentReference* pColorAttachments; DE_NULL, // const VkAttachmentReference* pResolveAttachments; DE_NULL, // const VkAttachmentReference* pDepthStencilAttachment; 1u + sampleNdx, // deUint32 preserveAttachmentCount; dataPointer(preserveAttachments) // const deUint32* pPreserveAttachments; }; subpasses[1u + sampleNdx] = subpassDesc; const VkSubpassDependency subpassDependency = { 0u, // uint32_t srcSubpass; 1u + sampleNdx, // uint32_t dstSubpass; VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags srcStageMask; VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // VkPipelineStageFlags dstStageMask; VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask; VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, // VkAccessFlags dstAccessMask; 0u, // VkDependencyFlags dependencyFlags; }; subpassDependencies[sampleNdx] = subpassDependency; } const VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkRenderPassCreateFlags)0u, // VkRenderPassCreateFlags flags; static_cast<deUint32>(attachments.size()), // deUint32 attachmentCount; dataPointer(attachments), // const VkAttachmentDescription* pAttachments; static_cast<deUint32>(subpasses.size()), // deUint32 subpassCount; dataPointer(subpasses), // const VkSubpassDescription* pSubpasses; static_cast<deUint32>(subpassDependencies.size()), // deUint32 dependencyCount; dataPointer(subpassDependencies) // const VkSubpassDependency* pDependencies; }; const Unique<VkRenderPass> renderPass(createRenderPass(deviceInterface, device, &renderPassInfo)); const VkImageSubresourceRange fullImageRange = makeImageSubresourceRange(VK_IMAGE_ASPECT_COLOR_BIT, 0u, imageMSInfo.mipLevels, 0u, imageMSInfo.arrayLayers); // Create color attachments image views typedef de::SharedPtr<Unique<VkImageView> > VkImageViewSp; std::vector<VkImageViewSp> imageViewsShPtrs(firstSubpassAttachmentsCount + numSamples); std::vector<VkImageView> imageViews(firstSubpassAttachmentsCount + numSamples); imageViewsShPtrs[0] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imageMS, mapImageViewType(m_imageType), imageMSInfo.format, fullImageRange)); imageViewsShPtrs[1] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imageRS, mapImageViewType(m_imageType), imageRSInfo.format, fullImageRange)); imageViews[0] = **imageViewsShPtrs[0]; imageViews[1] = **imageViewsShPtrs[1]; for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imageViewsShPtrs[firstSubpassAttachmentsCount + sampleNdx] = makeVkSharedPtr(makeImageView(deviceInterface, device, **imagesPerSampleVec[sampleNdx], mapImageViewType(m_imageType), imageRSInfo.format, fullImageRange)); imageViews[firstSubpassAttachmentsCount + sampleNdx] = **imageViewsShPtrs[firstSubpassAttachmentsCount + sampleNdx]; } // Create framebuffer const VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkFramebufferCreateFlags)0u, // VkFramebufferCreateFlags flags; *renderPass, // VkRenderPass renderPass; static_cast<deUint32>(imageViews.size()), // uint32_t attachmentCount; dataPointer(imageViews), // const VkImageView* pAttachments; imageMSInfo.extent.width, // uint32_t width; imageMSInfo.extent.height, // uint32_t height; imageMSInfo.arrayLayers, // uint32_t layers; }; const Unique<VkFramebuffer> framebuffer(createFramebuffer(deviceInterface, device, &framebufferInfo)); const VkDescriptorSetLayout* descriptorSetLayoutMSPass = createMSPassDescSetLayout(m_imageMSParams); // Create pipeline layout const VkPipelineLayoutCreateInfo pipelineLayoutMSPassParams = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineLayoutCreateFlags)0u, // VkPipelineLayoutCreateFlags flags; descriptorSetLayoutMSPass ? 1u : 0u, // deUint32 setLayoutCount; descriptorSetLayoutMSPass, // const VkDescriptorSetLayout* pSetLayouts; 0u, // deUint32 pushConstantRangeCount; DE_NULL, // const VkPushConstantRange* pPushConstantRanges; }; const Unique<VkPipelineLayout> pipelineLayoutMSPass(createPipelineLayout(deviceInterface, device, &pipelineLayoutMSPassParams)); // Create vertex attributes data const VertexDataDesc vertexDataDesc = getVertexDataDescripton(); de::SharedPtr<Buffer> vertexBuffer = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, makeBufferCreateInfo(vertexDataDesc.dataSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), MemoryRequirement::HostVisible)); const Allocation& vertexBufferAllocation = vertexBuffer->getAllocation(); uploadVertexData(vertexBufferAllocation, vertexDataDesc); flushAlloc(deviceInterface, device, vertexBufferAllocation); const VkVertexInputBindingDescription vertexBinding = { 0u, // deUint32 binding; vertexDataDesc.dataStride, // deUint32 stride; VK_VERTEX_INPUT_RATE_VERTEX // VkVertexInputRate inputRate; }; const VkPipelineVertexInputStateCreateInfo vertexInputStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; (VkPipelineVertexInputStateCreateFlags)0u, // VkPipelineVertexInputStateCreateFlags flags; 1u, // uint32_t vertexBindingDescriptionCount; &vertexBinding, // const VkVertexInputBindingDescription* pVertexBindingDescriptions; static_cast<deUint32>(vertexDataDesc.vertexAttribDescVec.size()), // uint32_t vertexAttributeDescriptionCount; dataPointer(vertexDataDesc.vertexAttribDescVec), // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions; }; const std::vector<VkViewport> viewports (1, makeViewport(imageMSInfo.extent)); const std::vector<VkRect2D> scissors (1, makeRect2D(imageMSInfo.extent)); const VkPipelineMultisampleStateCreateInfo multisampleStateInfo = getMSStateCreateInfo(m_imageMSParams); // Create graphics pipeline for multisample pass const Unique<VkShaderModule> vsMSPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("vertex_shader"), (VkShaderModuleCreateFlags)0u)); const Unique<VkShaderModule> fsMSPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("fragment_shader"), (VkShaderModuleCreateFlags)0u)); const Unique<VkPipeline> graphicsPipelineMSPass(makeGraphicsPipeline(deviceInterface, // const DeviceInterface& vk device, // const VkDevice device *pipelineLayoutMSPass, // const VkPipelineLayout pipelineLayout *vsMSPassModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlModule DE_NULL, // const VkShaderModule tessellationEvalModule DE_NULL, // const VkShaderModule geometryShaderModule *fsMSPassModule, // const VkShaderModule fragmentShaderModule *renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors vertexDataDesc.primitiveTopology, // const VkPrimitiveTopology topology 0u, // const deUint32 subpass 0u, // const deUint32 patchControlPoints &vertexInputStateInfo, // const VkPipelineVertexInputStateCreateInfo* vertexInputStateCreateInfo DE_NULL, // const VkPipelineRasterizationStateCreateInfo* rasterizationStateCreateInfo &multisampleStateInfo)); // const VkPipelineMultisampleStateCreateInfo* multisampleStateCreateInfo typedef de::SharedPtr<Unique<VkPipeline> > VkPipelineSp; std::vector<VkPipelineSp> graphicsPipelinesPerSampleFetch(numSamples); // Create descriptor set layout const Unique<VkDescriptorSetLayout> descriptorSetLayout( DescriptorSetLayoutBuilder() .addSingleBinding(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, VK_SHADER_STAGE_FRAGMENT_BIT) .addSingleBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, VK_SHADER_STAGE_FRAGMENT_BIT) .build(deviceInterface, device)); const Unique<VkPipelineLayout> pipelineLayoutPerSampleFetchPass(makePipelineLayout(deviceInterface, device, *descriptorSetLayout)); const deUint32 bufferPerSampleFetchPassSize = 4u * (deUint32)sizeof(tcu::Vec4); de::SharedPtr<Buffer> vertexBufferPerSampleFetchPass = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, makeBufferCreateInfo(bufferPerSampleFetchPassSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT), MemoryRequirement::HostVisible)); // Create graphics pipelines for per sample texel fetch passes { const Unique<VkShaderModule> vsPerSampleFetchPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("per_sample_fetch_vs"), (VkShaderModuleCreateFlags)0u)); const Unique<VkShaderModule> fsPerSampleFetchPassModule(createShaderModule(deviceInterface, device, m_context.getBinaryCollection().get("per_sample_fetch_fs"), (VkShaderModuleCreateFlags)0u)); std::vector<tcu::Vec4> vertices; vertices.push_back(tcu::Vec4(-1.0f, -1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4( 1.0f, -1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4(-1.0f, 1.0f, 0.0f, 1.0f)); vertices.push_back(tcu::Vec4( 1.0f, 1.0f, 0.0f, 1.0f)); const Allocation& vertexAllocPerSampleFetchPass = vertexBufferPerSampleFetchPass->getAllocation(); deMemcpy(vertexAllocPerSampleFetchPass.getHostPtr(), dataPointer(vertices), static_cast<std::size_t>(bufferPerSampleFetchPassSize)); flushAlloc(deviceInterface, device, vertexAllocPerSampleFetchPass); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { graphicsPipelinesPerSampleFetch[sampleNdx] = makeVkSharedPtr((makeGraphicsPipeline(deviceInterface, // const DeviceInterface& vk device, // const VkDevice device *pipelineLayoutPerSampleFetchPass, // const VkPipelineLayout pipelineLayout *vsPerSampleFetchPassModule, // const VkShaderModule vertexShaderModule DE_NULL, // const VkShaderModule tessellationControlModule DE_NULL, // const VkShaderModule tessellationEvalModule DE_NULL, // const VkShaderModule geometryShaderModule *fsPerSampleFetchPassModule, // const VkShaderModule fragmentShaderModule *renderPass, // const VkRenderPass renderPass viewports, // const std::vector<VkViewport>& viewports scissors, // const std::vector<VkRect2D>& scissors VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP, // const VkPrimitiveTopology topology 1u + sampleNdx))); // const deUint32 subpass } } // Create descriptor pool const Unique<VkDescriptorPool> descriptorPool( DescriptorPoolBuilder() .addType(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1u) .addType(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1u) .build(deviceInterface, device, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u)); // Create descriptor set const Unique<VkDescriptorSet> descriptorSet(makeDescriptorSet(deviceInterface, device, *descriptorPool, *descriptorSetLayout)); const VkPhysicalDeviceLimits deviceLimits = getPhysicalDeviceProperties(instance, physicalDevice).limits; VkDeviceSize uboOffsetAlignment = sizeof(deInt32) < deviceLimits.minUniformBufferOffsetAlignment ? deviceLimits.minUniformBufferOffsetAlignment : sizeof(deInt32); uboOffsetAlignment += (deviceLimits.minUniformBufferOffsetAlignment - uboOffsetAlignment % deviceLimits.minUniformBufferOffsetAlignment) % deviceLimits.minUniformBufferOffsetAlignment; const VkBufferCreateInfo bufferSampleIDInfo = makeBufferCreateInfo(uboOffsetAlignment * numSamples, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); const de::UniquePtr<Buffer> bufferSampleID(new Buffer(deviceInterface, device, allocator, bufferSampleIDInfo, MemoryRequirement::HostVisible)); std::vector<deUint32> sampleIDsOffsets(numSamples); { deInt8* sampleIDs = new deInt8[static_cast<deUint32>(uboOffsetAlignment) * numSamples]; for (deInt32 sampleNdx = 0u; sampleNdx < static_cast<deInt32>(numSamples); ++sampleNdx) { sampleIDsOffsets[sampleNdx] = static_cast<deUint32>(sampleNdx * uboOffsetAlignment); deInt8* samplePtr = sampleIDs + sampleIDsOffsets[sampleNdx]; deMemcpy(samplePtr, &sampleNdx, sizeof(deInt32)); } deMemcpy(bufferSampleID->getAllocation().getHostPtr(), sampleIDs, static_cast<deUint32>(uboOffsetAlignment * numSamples)); flushAlloc(deviceInterface, device, bufferSampleID->getAllocation()); delete[] sampleIDs; } { const VkDescriptorImageInfo descImageInfo = makeDescriptorImageInfo(DE_NULL, imageViews[0], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); const VkDescriptorBufferInfo descBufferInfo = makeDescriptorBufferInfo(**bufferSampleID, 0u, sizeof(deInt32)); DescriptorSetUpdateBuilder() .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(0u), VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, &descImageInfo) .writeSingle(*descriptorSet, DescriptorSetUpdateBuilder::Location::binding(1u), VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, &descBufferInfo) .update(deviceInterface, device); } // Create command buffer for compute and transfer oparations const Unique<VkCommandPool> commandPool(createCommandPool(deviceInterface, device, VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, queueFamilyIndex)); const Unique<VkCommandBuffer> commandBuffer(makeCommandBuffer(deviceInterface, device, *commandPool)); // Start recording commands beginCommandBuffer(deviceInterface, *commandBuffer); { std::vector<VkImageMemoryBarrier> imageOutputAttachmentBarriers(firstSubpassAttachmentsCount + numSamples); imageOutputAttachmentBarriers[0] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imageMS, fullImageRange ); imageOutputAttachmentBarriers[1] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imageRS, fullImageRange ); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imageOutputAttachmentBarriers[firstSubpassAttachmentsCount + sampleNdx] = makeImageMemoryBarrier ( 0u, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, **imagesPerSampleVec[sampleNdx], fullImageRange ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, static_cast<deUint32>(imageOutputAttachmentBarriers.size()), dataPointer(imageOutputAttachmentBarriers)); } { const VkDeviceSize vertexStartOffset = 0u; std::vector<VkClearValue> clearValues(firstSubpassAttachmentsCount + numSamples); for (deUint32 attachmentNdx = 0u; attachmentNdx < firstSubpassAttachmentsCount + numSamples; ++attachmentNdx) { clearValues[attachmentNdx] = makeClearValueColor(tcu::Vec4(0.0f, 0.0f, 0.0f, 1.0f)); } beginRenderPass(deviceInterface, *commandBuffer, *renderPass, *framebuffer, makeRect2D(0, 0, imageMSInfo.extent.width, imageMSInfo.extent.height), (deUint32)clearValues.size(), dataPointer(clearValues)); // Bind graphics pipeline deviceInterface.cmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *graphicsPipelineMSPass); const VkDescriptorSet* descriptorSetMSPass = createMSPassDescSet(m_imageMSParams, descriptorSetLayoutMSPass); if (descriptorSetMSPass) { // Bind descriptor set deviceInterface.cmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayoutMSPass, 0u, 1u, descriptorSetMSPass, 0u, DE_NULL); } // Bind vertex buffer deviceInterface.cmdBindVertexBuffers(*commandBuffer, 0u, 1u, &vertexBuffer->get(), &vertexStartOffset); // Perform a draw deviceInterface.cmdDraw(*commandBuffer, vertexDataDesc.verticesCount, 1u, 0u, 0u); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { deviceInterface.cmdNextSubpass(*commandBuffer, VK_SUBPASS_CONTENTS_INLINE); // Bind graphics pipeline deviceInterface.cmdBindPipeline(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, **graphicsPipelinesPerSampleFetch[sampleNdx]); // Bind descriptor set deviceInterface.cmdBindDescriptorSets(*commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *pipelineLayoutPerSampleFetchPass, 0u, 1u, &descriptorSet.get(), 1u, &sampleIDsOffsets[sampleNdx]); // Bind vertex buffer deviceInterface.cmdBindVertexBuffers(*commandBuffer, 0u, 1u, &vertexBufferPerSampleFetchPass->get(), &vertexStartOffset); // Perform a draw deviceInterface.cmdDraw(*commandBuffer, 4u, 1u, 0u, 0u); } // End render pass endRenderPass(deviceInterface, *commandBuffer); } { const VkImageMemoryBarrier imageRSTransferBarrier = makeImageMemoryBarrier ( VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **imageRS, fullImageRange ); deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, 1u, &imageRSTransferBarrier); } // Copy data from imageRS to buffer const deUint32 imageRSSizeInBytes = getImageSizeInBytes(imageRSInfo.extent, imageRSInfo.arrayLayers, m_imageFormat, imageRSInfo.mipLevels, 1u); const VkBufferCreateInfo bufferRSInfo = makeBufferCreateInfo(imageRSSizeInBytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT); const de::UniquePtr<Buffer> bufferRS(new Buffer(deviceInterface, device, allocator, bufferRSInfo, MemoryRequirement::HostVisible)); { const VkBufferImageCopy bufferImageCopy = { 0u, // VkDeviceSize bufferOffset; 0u, // deUint32 bufferRowLength; 0u, // deUint32 bufferImageHeight; makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, imageRSInfo.arrayLayers), // VkImageSubresourceLayers imageSubresource; makeOffset3D(0, 0, 0), // VkOffset3D imageOffset; imageRSInfo.extent, // VkExtent3D imageExtent; }; deviceInterface.cmdCopyImageToBuffer(*commandBuffer, **imageRS, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, bufferRS->get(), 1u, &bufferImageCopy); } { const VkBufferMemoryBarrier bufferRSHostReadBarrier = makeBufferMemoryBarrier ( VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, bufferRS->get(), 0u, imageRSSizeInBytes ); deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, 1u, &bufferRSHostReadBarrier, 0u, DE_NULL); } // Copy data from per sample images to buffers std::vector<VkImageMemoryBarrier> imagesPerSampleTransferBarriers(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { imagesPerSampleTransferBarriers[sampleNdx] = makeImageMemoryBarrier ( VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **imagesPerSampleVec[sampleNdx], fullImageRange ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0u, 0u, DE_NULL, 0u, DE_NULL, static_cast<deUint32>(imagesPerSampleTransferBarriers.size()), dataPointer(imagesPerSampleTransferBarriers)); std::vector<de::SharedPtr<Buffer> > buffersPerSample(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { buffersPerSample[sampleNdx] = de::SharedPtr<Buffer>(new Buffer(deviceInterface, device, allocator, bufferRSInfo, MemoryRequirement::HostVisible)); const VkBufferImageCopy bufferImageCopy = { 0u, // VkDeviceSize bufferOffset; 0u, // deUint32 bufferRowLength; 0u, // deUint32 bufferImageHeight; makeImageSubresourceLayers(VK_IMAGE_ASPECT_COLOR_BIT, 0u, 0u, imageRSInfo.arrayLayers), // VkImageSubresourceLayers imageSubresource; makeOffset3D(0, 0, 0), // VkOffset3D imageOffset; imageRSInfo.extent, // VkExtent3D imageExtent; }; deviceInterface.cmdCopyImageToBuffer(*commandBuffer, **imagesPerSampleVec[sampleNdx], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, **buffersPerSample[sampleNdx], 1u, &bufferImageCopy); } std::vector<VkBufferMemoryBarrier> buffersPerSampleHostReadBarriers(numSamples); for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { buffersPerSampleHostReadBarriers[sampleNdx] = makeBufferMemoryBarrier ( VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT, **buffersPerSample[sampleNdx], 0u, imageRSSizeInBytes ); } deviceInterface.cmdPipelineBarrier(*commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0u, 0u, DE_NULL, static_cast<deUint32>(buffersPerSampleHostReadBarriers.size()), dataPointer(buffersPerSampleHostReadBarriers), 0u, DE_NULL); // End recording commands endCommandBuffer(deviceInterface, *commandBuffer); // Submit commands for execution and wait for completion submitCommandsAndWait(deviceInterface, device, queue, *commandBuffer); // Retrieve data from bufferRS to host memory const Allocation& bufferRSAlloc = bufferRS->getAllocation(); invalidateAlloc(deviceInterface, device, bufferRSAlloc); const tcu::ConstPixelBufferAccess bufferRSData (m_imageFormat, imageRSInfo.extent.width, imageRSInfo.extent.height, imageRSInfo.extent.depth * imageRSInfo.arrayLayers, bufferRSAlloc.getHostPtr()); std::stringstream resolveName; resolveName << "Resolve image " << getImageTypeName(m_imageType) << "_" << bufferRSData.getWidth() << "_" << bufferRSData.getHeight() << "_" << bufferRSData.getDepth() << std::endl; m_context.getTestContext().getLog() << tcu::TestLog::Section(resolveName.str(), resolveName.str()) << tcu::LogImage("resolve", "", bufferRSData) << tcu::TestLog::EndSection; std::vector<tcu::ConstPixelBufferAccess> buffersPerSampleData(numSamples); // Retrieve data from per sample buffers to host memory for (deUint32 sampleNdx = 0u; sampleNdx < numSamples; ++sampleNdx) { const Allocation& bufferAlloc = buffersPerSample[sampleNdx]->getAllocation(); invalidateAlloc(deviceInterface, device, bufferAlloc); buffersPerSampleData[sampleNdx] = tcu::ConstPixelBufferAccess ( m_imageFormat, imageRSInfo.extent.width, imageRSInfo.extent.height, imageRSInfo.extent.depth * imageRSInfo.arrayLayers, bufferAlloc.getHostPtr() ); std::stringstream sampleName; sampleName << "Sample " << sampleNdx << " image" << std::endl; m_context.getTestContext().getLog() << tcu::TestLog::Section(sampleName.str(), sampleName.str()) << tcu::LogImage("sample", "", buffersPerSampleData[sampleNdx]) << tcu::TestLog::EndSection; } return verifyImageData(imageMSInfo, imageRSInfo, buffersPerSampleData, bufferRSData); } } // multisample } // pipeline } // vkt
36,168
14,432
#include <vector> using std::vector; using std::swap; class Solution { public: int firstMissingPositive(vector<int>& nums) { int n = nums.size(); for (int i = 0; i < n; ++i) { while (nums[i] > 0 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) swap(nums[i], nums[nums[i] - 1]); } for (int i = 0; i < n; ++i) { if (nums[i] != i + 1) return i + 1; } return n + 1; } /************************************************************* int partition(vector<int> &nums) { int p = 0; for (int i = 0; i < nums.size(); ++i) { if (nums[i] > 0) { swap(nums[i], nums[p]); p++; } } return p; } int firstMissingPositive(vector<int>& nums) { int k = partition(nums); int first_missing_index = k; for (int i = 0; i < k; ++i) { int tmp = nums[i] < 0 ? -nums[i] : nums[i]; tmp = tmp - 1; if (tmp < k && nums[tmp] > 0) nums[tmp] = -nums[tmp]; } for (int i = 0; i < k; ++i) { if (nums[i] > 0) { first_missing_index = i; break; } } return first_missing_index + 1; } ************************************************************/ };
1,527
496
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/drds/model/DescribeDrdsDBClusterResult.h> #include <json/json.h> using namespace AlibabaCloud::Drds; using namespace AlibabaCloud::Drds::Model; DescribeDrdsDBClusterResult::DescribeDrdsDBClusterResult() : ServiceResult() {} DescribeDrdsDBClusterResult::DescribeDrdsDBClusterResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDrdsDBClusterResult::~DescribeDrdsDBClusterResult() {} void DescribeDrdsDBClusterResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dbInstanceNode = value["DbInstance"]; if(!dbInstanceNode["DBInstanceId"].isNull()) dbInstance_.dBInstanceId = dbInstanceNode["DBInstanceId"].asString(); if(!dbInstanceNode["Port"].isNull()) dbInstance_.port = std::stoi(dbInstanceNode["Port"].asString()); if(!dbInstanceNode["DBInstanceStatus"].isNull()) dbInstance_.dBInstanceStatus = dbInstanceNode["DBInstanceStatus"].asString(); if(!dbInstanceNode["DbInstType"].isNull()) dbInstance_.dbInstType = dbInstanceNode["DbInstType"].asString(); if(!dbInstanceNode["Engine"].isNull()) dbInstance_.engine = dbInstanceNode["Engine"].asString(); if(!dbInstanceNode["EngineVersion"].isNull()) dbInstance_.engineVersion = dbInstanceNode["EngineVersion"].asString(); if(!dbInstanceNode["RdsInstType"].isNull()) dbInstance_.rdsInstType = dbInstanceNode["RdsInstType"].asString(); if(!dbInstanceNode["PayType"].isNull()) dbInstance_.payType = dbInstanceNode["PayType"].asString(); if(!dbInstanceNode["ExpireTime"].isNull()) dbInstance_.expireTime = dbInstanceNode["ExpireTime"].asString(); if(!dbInstanceNode["RemainDays"].isNull()) dbInstance_.remainDays = dbInstanceNode["RemainDays"].asString(); if(!dbInstanceNode["NetworkType"].isNull()) dbInstance_.networkType = dbInstanceNode["NetworkType"].asString(); if(!dbInstanceNode["ReadMode"].isNull()) dbInstance_.readMode = dbInstanceNode["ReadMode"].asString(); auto allEndpointsNode = dbInstanceNode["Endpoints"]["Endpoint"]; for (auto dbInstanceNodeEndpointsEndpoint : allEndpointsNode) { DbInstance::Endpoint endpointObject; if(!dbInstanceNodeEndpointsEndpoint["NodeIds"].isNull()) endpointObject.nodeIds = dbInstanceNodeEndpointsEndpoint["NodeIds"].asString(); if(!dbInstanceNodeEndpointsEndpoint["EndpointId"].isNull()) endpointObject.endpointId = dbInstanceNodeEndpointsEndpoint["EndpointId"].asString(); if(!dbInstanceNodeEndpointsEndpoint["ReadWeight"].isNull()) endpointObject.readWeight = std::stoi(dbInstanceNodeEndpointsEndpoint["ReadWeight"].asString()); dbInstance_.endpoints.push_back(endpointObject); } auto allDBNodesNode = dbInstanceNode["DBNodes"]["DBNode"]; for (auto dbInstanceNodeDBNodesDBNode : allDBNodesNode) { DbInstance::DBNode dBNodeObject; if(!dbInstanceNodeDBNodesDBNode["DBNodeId"].isNull()) dBNodeObject.dBNodeId = dbInstanceNodeDBNodesDBNode["DBNodeId"].asString(); if(!dbInstanceNodeDBNodesDBNode["ZoneId"].isNull()) dBNodeObject.zoneId = dbInstanceNodeDBNodesDBNode["ZoneId"].asString(); if(!dbInstanceNodeDBNodesDBNode["DBNodeStatus"].isNull()) dBNodeObject.dBNodeStatus = dbInstanceNodeDBNodesDBNode["DBNodeStatus"].asString(); if(!dbInstanceNodeDBNodesDBNode["DBNodeRole"].isNull()) dBNodeObject.dBNodeRole = dbInstanceNodeDBNodesDBNode["DBNodeRole"].asString(); dbInstance_.dBNodes.push_back(dBNodeObject); } if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; } DescribeDrdsDBClusterResult::DbInstance DescribeDrdsDBClusterResult::getDbInstance()const { return dbInstance_; } bool DescribeDrdsDBClusterResult::getSuccess()const { return success_; }
4,367
1,403
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/extensions/api/system_indicator/system_indicator_handler.h" #include "base/test/values_test_util.h" #include "components/version_info/channel.h" #include "extensions/common/constants.h" #include "extensions/common/extension_icon_set.h" #include "extensions/common/features/feature_channel.h" #include "extensions/common/manifest_test.h" #include "testing/gmock/include/gmock/gmock.h" namespace extensions { using SystemIndicatorHandlerTest = ManifestTest; TEST_F(SystemIndicatorHandlerTest, BasicTests) { ScopedCurrentChannel current_channel(version_info::Channel::DEV); // Simple icon path. { constexpr char kManifest[] = R"({ "name": "System Indicator", "manifest_version": 2, "version": "0.1", "system_indicator": { "default_icon": "icon.png" } })"; scoped_refptr<const Extension> extension = LoadAndExpectSuccess( ManifestData(base::test::ParseJson(kManifest), "icon")); ASSERT_TRUE(extension); const ExtensionIconSet* icon = SystemIndicatorHandler::GetSystemIndicatorIcon(*extension); ASSERT_TRUE(icon); // Make a copy of the map since [] is more readable than find() for // comparing values. ExtensionIconSet::IconMap icon_map = icon->map(); EXPECT_THAT(icon_map, testing::ElementsAre(std::make_pair( extension_misc::EXTENSION_ICON_GIGANTOR, "icon.png"))); } // Icon dictionary. { constexpr char kManifest[] = R"({ "name": "System Indicator", "manifest_version": 2, "version": "0.1", "system_indicator": { "default_icon": { "24": "icon24.png", "48": "icon48.png", "79": "icon79.png" } } })"; scoped_refptr<const Extension> extension = LoadAndExpectSuccess( ManifestData(base::test::ParseJson(kManifest), "icon")); ASSERT_TRUE(extension); const ExtensionIconSet* icon = SystemIndicatorHandler::GetSystemIndicatorIcon(*extension); ASSERT_TRUE(icon); // Make a copy of the map since [] is more readable than find() for // comparing values. ExtensionIconSet::IconMap icon_map = icon->map(); EXPECT_THAT(icon_map, testing::ElementsAre(std::make_pair(24, "icon24.png"), std::make_pair(48, "icon48.png"), std::make_pair(79, "icon79.png"))); } // Empty dictionary. { constexpr char kManifest[] = R"({ "name": "System Indicator", "manifest_version": 2, "version": "0.1", "system_indicator": {} })"; scoped_refptr<const Extension> extension = LoadAndExpectSuccess( ManifestData(base::test::ParseJson(kManifest), "icon")); ASSERT_TRUE(extension); const ExtensionIconSet* icon = SystemIndicatorHandler::GetSystemIndicatorIcon(*extension); ASSERT_TRUE(icon); EXPECT_TRUE(icon->empty()); } } } // namespace extensions
3,306
999
// ----------------------------------------------------------------------- // // // MODULE : Intelligence.cpp // // PURPOSE : Implementation of the Intelligence object // // CREATED : 9/14/99 // // (c) 1999-2000 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "Intelligence.h" #include "ObjectMsgs.h" #include "PlayerObj.h" #include "CommandMgr.h" // Statics static char *s_szActivate = "ACTIVATE"; static char *s_szGadget = "GADGET"; static char *s_szRespawn = "RESPAWN"; extern CVarTrack g_vtNetIntelScore; CVarTrack g_IntelRespawnScale; #define INTEL_RESPAWN_SOUND "Powerups\\Snd\\spawn_intel.wav" #define INTEL_PICKUP_SOUND "Powerups\\Snd\\pu_intel.wav" // ----------------------------------------------------------------------- // // // CLASS: Intelligence // // PURPOSE: An Intelligence object // // ----------------------------------------------------------------------- // BEGIN_CLASS(Intelligence) // Hide parent properties we don't care about... ADD_STRINGPROP_FLAG(Filename, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(Skin, "", PF_HIDDEN) ADD_STRINGPROP_FLAG(Type, "", PF_STATICLIST | PF_DIMS | PF_LOCALDIMS) ADD_LONGINTPROP(InfoId, 0) ADD_BOOLPROP_FLAG(ShowPopup, LTTRUE, 0) ADD_BOOLPROP_FLAG(PhotoOnly, LTFALSE, 0) ADD_STRINGPROP_FLAG(PickedUpCommand, "", 0) ADD_LONGINTPROP(PlayerTeamFilter, 0) ADD_BOOLPROP_FLAG(StartHidden, LTFALSE, 0) ADD_REALPROP(RespawnTime, 30.0f) END_CLASS_DEFAULT_FLAGS_PLUGIN(Intelligence, Prop, NULL, NULL, 0, CIntelPlugin) LTRESULT CIntelPlugin::PreHook_EditStringList( const char* szRezPath, const char* szPropName, char** aszStrings, uint32* pcStrings, const uint32 cMaxStrings, const uint32 cMaxStringLength) { if ( LT_OK == CPropPlugin::PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) ) { return LT_OK; } else if (_strcmpi("Type", szPropName) == 0) { if (m_IntelMgrPlugin.PreHook_EditStringList(szRezPath, szPropName, aszStrings, pcStrings, cMaxStrings, cMaxStringLength) == LT_OK) { return LT_OK; } } return LT_UNSUPPORTED; } LTRESULT CIntelPlugin::PreHook_Dims( const char* szRezPath, const char* szPropValue, char* szModelFilenameBuf, int nModelFilenameBufLen, LTVector & vDims) { if (m_IntelMgrPlugin.PreHook_Dims(szRezPath, szPropValue, szModelFilenameBuf, nModelFilenameBufLen, vDims) == LT_OK) { return LT_OK; } return LT_UNSUPPORTED; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Intelligence() // // PURPOSE: Initialize object // // ----------------------------------------------------------------------- // Intelligence::Intelligence() : Prop () { m_bShowPopup = LTTRUE; m_bPhotoOnly = LTFALSE; m_hstrPickedUpCmd = LTNULL; m_nPlayerTeamFilter = 0; m_nInfoId = 0; m_nIntelId = INTELMGR_INVALID_ID; m_fRespawnDelay = 30.0f; m_bStartHidden = LTFALSE; m_bFirstUpdate = LTTRUE; m_bSkipUpdate = LTFALSE; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::~Intelligence() // // PURPOSE: Deallocate object // // ----------------------------------------------------------------------- // Intelligence::~Intelligence() { if (m_hstrPickedUpCmd) { g_pLTServer->FreeString(m_hstrPickedUpCmd); m_hstrPickedUpCmd = LTNULL; } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::EngineMessageFn // // PURPOSE: Handle engine messages // // ----------------------------------------------------------------------- // uint32 Intelligence::EngineMessageFn(uint32 messageID, void *pData, LTFLOAT fData) { switch(messageID) { case MID_UPDATE: { Update(); } break; case MID_PRECREATE: { uint32 dwRet = Prop::EngineMessageFn(messageID, pData, fData); if (fData == PRECREATE_WORLDFILE || fData == PRECREATE_STRINGPROP) { ReadProp((ObjectCreateStruct*)pData); PostPropRead((ObjectCreateStruct*)pData); } return dwRet; } break; case MID_SAVEOBJECT: { Save((HMESSAGEWRITE)pData); } break; case MID_LOADOBJECT: { Load((HMESSAGEREAD)pData); } break; case MID_INITIALUPDATE: { if (fData != INITIALUPDATE_SAVEGAME) { InitialUpdate(); } CacheFiles(); } break; default : break; } return Prop::EngineMessageFn(messageID, pData, fData); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::ReadProp // // PURPOSE: Set property value // // ----------------------------------------------------------------------- // void Intelligence::ReadProp(ObjectCreateStruct *pInfo) { if (!pInfo) return; GenericProp genProp; if (g_pLTServer->GetPropGeneric("PhotoOnly", &genProp) == LT_OK) { m_bPhotoOnly = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("StartHidden", &genProp) == LT_OK) { m_bStartHidden = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("ShowPopup", &genProp) == LT_OK) { m_bShowPopup = genProp.m_Bool; } if (g_pLTServer->GetPropGeneric("PickedUpCommand", &genProp) == LT_OK) { if (genProp.m_String[0]) { m_hstrPickedUpCmd = g_pLTServer->CreateString(genProp.m_String); } } if (g_pLTServer->GetPropGeneric("PlayerTeamFilter", &genProp) == LT_OK) { m_nPlayerTeamFilter = (uint8) genProp.m_Long; } if (g_pLTServer->GetPropGeneric("InfoId", &genProp) == LT_OK) { m_nInfoId = genProp.m_Long; } if (g_pLTServer->GetPropGeneric("RespawnTime", &genProp) == LT_OK) { m_fRespawnDelay = genProp.m_Float; } INTEL* pIntel = LTNULL; if (g_pLTServer->GetPropGeneric("Type", &genProp) == LT_OK) { if (genProp.m_String[0]) { pIntel = g_pIntelMgr->GetIntel(genProp.m_String); } } if (pIntel) { if (!pIntel || !pIntel->szFilename[0]) return; SAFE_STRCPY(pInfo->m_Filename, pIntel->szFilename); uint32 iSkin = 0; ConParse conParse; conParse.Init(pIntel->szSkin); while (g_pLTServer->Common()->Parse(&conParse) == LT_OK) { if (conParse.m_nArgs > 0) { SAFE_STRCPY(pInfo->m_SkinNames[iSkin], conParse.m_Args[0]); iSkin++; } if (iSkin >= MAX_MODEL_TEXTURES) break; } pInfo->m_SkinName[MAX_CS_FILENAME_LEN] = '\0'; m_nIntelId = pIntel->nId; if (pIntel->bChromakey) { m_dwFlags2 |= FLAG2_CHROMAKEY; } m_dwFlags = (pIntel->bChrome ? (m_dwFlags | FLAG_ENVIRONMENTMAP) : (m_dwFlags & ~FLAG_ENVIRONMENTMAP)); } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::PostPropRead() // // PURPOSE: Update Properties // // ----------------------------------------------------------------------- // void Intelligence::PostPropRead(ObjectCreateStruct *pStruct) { if (!pStruct) return; // Make us activateable... pStruct->m_Flags |= FLAG_RAYHIT; // Make sure we don't have gravity set... pStruct->m_Flags &= ~FLAG_GRAVITY; pStruct->m_fDeactivationTime = 0.5f; m_dwUsrFlgs |= (USRFLG_GLOW | USRFLG_IGNORE_PROJECTILES); if (m_bPhotoOnly) { m_dwUsrFlgs |= USRFLG_GADGET_INTELLIGENCE; } else { m_dwUsrFlgs |= USRFLG_CAN_ACTIVATE; } m_damage.SetCanHeal(LTFALSE); m_damage.SetCanRepair(LTFALSE); m_damage.SetApplyDamagePhysics(LTFALSE); m_damage.SetMaxHitPoints(1.0f); m_damage.SetHitPoints(1.0f); m_damage.SetCanDamage(LTFALSE); // Use the default info id if necessary... if (!m_nInfoId) { INTEL* pIntel = g_pIntelMgr->GetIntel(m_nIntelId); if (pIntel && m_bShowPopup) { m_nInfoId = pIntel->nDefaultTextId; } } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::ObjectMessageFn // // PURPOSE: Handle object-to-object messages // // ----------------------------------------------------------------------- // uint32 Intelligence::ObjectMessageFn(HOBJECT hSender, uint32 messageID, HMESSAGEREAD hRead) { if (!g_pLTServer) return 0; switch(messageID) { case MID_TRIGGER: { const char* szMsg = (const char*)g_pLTServer->ReadFromMessageDWord(hRead); // ConParse does not destroy szMsg, so this is safe ConParse parse; parse.Init((char*)szMsg); while (g_pLTServer->Common()->Parse(&parse) == LT_OK) { if (parse.m_nArgs > 0 && parse.m_Args[0]) { if (_stricmp(parse.m_Args[0], s_szActivate) == 0) { if (!m_bPhotoOnly) { DoActivate(hSender); } } else if (_stricmp(parse.m_Args[0], s_szGadget) == 0) { if (m_bPhotoOnly) { HandleGadgetMsg(hSender, parse); } } else if (_stricmp(parse.m_Args[0], s_szRespawn) == 0) { SetNextUpdate( m_fRespawnDelay / g_IntelRespawnScale.GetFloat(1.0f)); } } } } break; default : break; } return Prop::ObjectMessageFn(hSender, messageID, hRead); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::HandleGadgetMsg // // PURPOSE: Handle the camera gadget // // ----------------------------------------------------------------------- // void Intelligence::HandleGadgetMsg(HOBJECT hSender, ConParse & parse) { DoActivate(hSender); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::DoActivate() // // PURPOSE: Handle Activate... // // ----------------------------------------------------------------------- // void Intelligence::DoActivate(HOBJECT hSender) { // BL 10/30/00 - fix multiple photographs of items in multiplayer { if ( g_pGameServerShell->GetGameType() != SINGLE ) { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); if ( !(dwFlags & FLAG_VISIBLE) ) { return; } } } HOBJECT hPlayer = hSender; if (!hSender || !IsPlayer(hSender)) { // Find the player if the sender isn't one... ObjArray <HOBJECT, 1> objArray; g_pLTServer->FindNamedObjects(DEFAULT_PLAYERNAME, objArray); if (!objArray.NumObjects()) return; hPlayer = objArray.GetObject(0); } // Increment the player's intelligence count... CPlayerObj* pPlayer = (CPlayerObj*)g_pLTServer->HandleToObject(hPlayer); if (pPlayer) { if (g_pGameServerShell->GetGameType() == COOPERATIVE_ASSAULT && m_nPlayerTeamFilter) { if (pPlayer->GetTeamID() != m_nPlayerTeamFilter) return; uint8 nScore = (uint8)g_vtNetIntelScore.GetFloat(); pPlayer->AddToScore(nScore); HCLIENT hClient = pPlayer->GetClient(); uint32 nPlayerID = g_pLTServer->GetClientID(hClient); HMESSAGEWRITE hWrite = g_pLTServer->StartMessage (LTNULL, MID_TEAM_SCORED); g_pLTServer->WriteToMessageDWord (hWrite, nPlayerID); g_pLTServer->WriteToMessageByte (hWrite, (uint8)pPlayer->GetTeamID()); g_pLTServer->WriteToMessageByte (hWrite, nScore); g_pLTServer->EndMessage (hWrite); } CPlayerSummaryMgr* pPSMgr = pPlayer->GetPlayerSummaryMgr(); if (pPSMgr) { pPSMgr->IncIntelligenceCount(); } HCLIENT hClient = pPlayer->GetClient(); if (hClient) { HMESSAGEWRITE hMessage = g_pLTServer->StartMessage(hClient, MID_PLAYER_INFOCHANGE); g_pLTServer->WriteToMessageByte(hMessage, IC_INTEL_PICKUP_ID); g_pLTServer->WriteToMessageByte(hMessage, 0); g_pLTServer->WriteToMessageByte(hMessage, 0); g_pLTServer->WriteToMessageFloat(hMessage, 0.0f); g_pLTServer->EndMessage(hMessage); } // Show the pop-up associated with the intelligence item, if // applicable... INTEL* pIntel = g_pIntelMgr->GetIntel(m_nIntelId); if (pIntel && m_bShowPopup) { char buf[255]; sprintf(buf, "msg %s (popup %d", DEFAULT_PLAYERNAME, m_nInfoId); // Add the scale fx... for (int i=0; i < pIntel->nNumScaleFXNames; i++) { if (pIntel->szScaleFXNames[i]) { strcat(buf, " "); strcat(buf, pIntel->szScaleFXNames[i]); } } strcat(buf, ")"); if (g_pCmdMgr->IsValidCmd(buf)) { g_pCmdMgr->Process(buf); } } // If we have a command, process it... if (m_hstrPickedUpCmd) { char* pCmd = g_pLTServer->GetStringData(m_hstrPickedUpCmd); if (pCmd && g_pCmdMgr->IsValidCmd(pCmd)) { g_pCmdMgr->Process(pCmd); } } if (g_pGameServerShell->GetGameType() == SINGLE) { g_pLTServer->RemoveObject(m_hObject); } else { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags &= (~FLAG_VISIBLE & ~FLAG_RAYHIT); g_pLTServer->SetObjectFlags(m_hObject, dwFlags); // Play pickup sound... LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); g_pServerSoundMgr->PlaySoundFromPos(vPos, INTEL_PICKUP_SOUND, 600.0f, SOUNDPRIORITY_MISC_HIGH); } } } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Save // // PURPOSE: Save the object // // ----------------------------------------------------------------------- // void Intelligence::Save(HMESSAGEWRITE hWrite) { if (!hWrite) return; g_pLTServer->WriteToMessageByte(hWrite, m_bPhotoOnly); g_pLTServer->WriteToMessageByte(hWrite, m_bShowPopup); g_pLTServer->WriteToMessageHString(hWrite, m_hstrPickedUpCmd); g_pLTServer->WriteToMessageDWord(hWrite, m_nInfoId); g_pLTServer->WriteToMessageDWord(hWrite, m_nIntelId); g_pLTServer->WriteToMessageByte(hWrite, m_bStartHidden); g_pLTServer->WriteToMessageByte(hWrite, m_bFirstUpdate); g_pLTServer->WriteToMessageByte(hWrite, m_bSkipUpdate); g_pLTServer->WriteToMessageFloat(hWrite, m_fRespawnDelay); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Load // // PURPOSE: Load the object // // ----------------------------------------------------------------------- // void Intelligence::Load(HMESSAGEREAD hRead) { if (!hRead) return; m_bPhotoOnly = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bShowPopup = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_hstrPickedUpCmd = g_pLTServer->ReadFromMessageHString(hRead); m_nInfoId = g_pLTServer->ReadFromMessageDWord(hRead); m_nIntelId = g_pLTServer->ReadFromMessageDWord(hRead); m_bStartHidden = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bFirstUpdate = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_bSkipUpdate = (LTBOOL) g_pLTServer->ReadFromMessageByte(hRead); m_fRespawnDelay = g_pLTServer->ReadFromMessageFloat(hRead); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::Update() // // PURPOSE: Update // // ----------------------------------------------------------------------- // LTBOOL Intelligence::Update() { if (m_bFirstUpdate) { m_bFirstUpdate = LTFALSE; if (m_bStartHidden) { SendTriggerMsgToObject(this, m_hObject, LTFALSE, "Hidden 1"); return LTTRUE; } } // If we aren't visible it must be time to respawn... uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); if (!m_bSkipUpdate && !(dwFlags & FLAG_VISIBLE)) { uint32 dwFlags = g_pLTServer->GetObjectFlags(m_hObject); dwFlags |= (FLAG_VISIBLE | FLAG_RAYHIT); g_pLTServer->SetObjectFlags(m_hObject, dwFlags); // Let the world know what happened... LTVector vPos; g_pLTServer->GetObjectPos(m_hObject, &vPos); g_pServerSoundMgr->PlaySoundFromPos(vPos, INTEL_RESPAWN_SOUND, 600.0f, SOUNDPRIORITY_MISC_HIGH); } m_bSkipUpdate = LTFALSE; return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::InitialUpdate() // // PURPOSE: First update // // ----------------------------------------------------------------------- // void Intelligence::InitialUpdate() { if (!g_IntelRespawnScale.IsInitted()) { g_IntelRespawnScale.Init(GetServerDE(), "IntelRespawnScale", LTNULL, 1.0f); } if (m_bStartHidden) { SetNextUpdate(0.001f); } m_bSkipUpdate = m_bMoveToFloor; CacheFiles(); } // ----------------------------------------------------------------------- // // // ROUTINE: Intelligence::CacheFiles // // PURPOSE: Cache whatever resources this object uses // // ----------------------------------------------------------------------- // void Intelligence::CacheFiles() { g_pLTServer->CacheFile(FT_SOUND, INTEL_RESPAWN_SOUND); g_pLTServer->CacheFile(FT_SOUND, INTEL_PICKUP_SOUND); }
16,636
6,734
#include "stdio.h" #include "util.h" int main(int argc, char** argv) { cmplx_f c = atocmplx_f(argv[1]); c.print(); puts(""); return 0; }
141
70
#ifndef MODULO_FILAS_H//include de guarda #define MODULO_FILAS_H #include <deque> #include <vector> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Processos/Processo.hpp" #include "../include/LeitorEntradas.hpp" class Filas{ public: /* Esta classe implementa as filas de prioridade simples. São, na pratica quatro filas de inteiros. Ou seja, nestas filas, apenas os PID's dos processos serão guardados. */ std::deque<int> Fila0; //fila prioridade 0 std::deque<int> Fila1; //fila prioridade 1 std::deque<int> Fila2; //fila prioridade 2 std::deque<int> Fila3; //fila prioridade 3 Filas(); void insereProcesso(Processo );//Metodo que verifica a prioridade do processo e o coloca na fila adequada bool existe_processo_para_executar(); bool existe_processo_para_executar_fila0(); bool existe_processo_para_executar_fila1(); bool existe_processo_para_executar_fila2(); bool existe_processo_para_executar_fila3(); int retira_processo_fila0(); int retira_processo_fila1(); int retira_processo_fila2(); int retira_processo_fila3(); void destroiFilas(); void imprimeEstado(); }; #endif
1,142
475
// A simple and tail recursive C++ program to reverse // a linked list #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; }; void reverseUtil(Node* curr, Node* prev, Node** head); // This function mainly calls reverseUtil() // with prev as NULL void reverse(Node** head) { if (!head) return; reverseUtil(*head, NULL, head); } // A simple and tail recursive function to reverse // a linked list. prev is passed as NULL initially. void reverseUtil(Node* curr, Node* prev, Node** head) { /* If last node mark it head*/ if (!curr->next) { *head = curr; /* Update next to prev node */ curr->next = prev; return; } /* Save curr->next node for recursive call */ Node* next = curr->next; /* and update next ..*/ curr->next = prev; reverseUtil(next, curr, head); } // A utility function to create a new node Node* newNode(int key) { Node* temp = new Node; temp->data = key; temp->next = NULL; return temp; } // A utility function to print a linked list void printlist(Node* head) { while (head != NULL) { cout << head->data << " "; head = head->next; } cout << endl; } // Driver program to test above functions int main() { Node* head1 = newNode(1); head1->next = newNode(2); head1->next->next = newNode(3); head1->next->next->next = newNode(4); cout << "Given linked list\n"; printlist(head1); reverse(&head1); cout << "\nReversed linked list\n"; printlist(head1); return 0; }
1,755
597
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/resolve_gen_names_collisions.hpp" #include "gtest/gtest.h" #include "openvino/opsets/opset8.hpp" #include "openvino/pass/manager.hpp" TEST(ResolveGeneratedNameCollisionsTest, FixGeneratedNames) { auto arg0 = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape{1, 3, 3, 3}); const auto gen_friendly_name = arg0->get_friendly_name(); std::string name = "Parameter_"; EXPECT_NE(std::string::npos, gen_friendly_name.find("Parameter_")); unsigned long long index = std::stoull(gen_friendly_name.substr(name.length())); name += std::to_string(++index); arg0->set_friendly_name(name); auto arg1 = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape{1, 2, 3, 3}); auto concat = std::make_shared<ov::opset8::Concat>(ov::NodeVector{arg0, arg1}, 1); auto result1 = std::make_shared<ov::opset8::Result>(concat); auto model = std::make_shared<ov::Model>(ov::ResultVector{result1}, ov::ParameterVector{arg0, arg1}); EXPECT_EQ(name, arg0->get_friendly_name()); EXPECT_EQ(arg1->get_friendly_name(), arg0->get_friendly_name()); EXPECT_NE(arg1->get_friendly_name(), arg0->get_friendly_name() + "_2"); ov::pass::Manager pass_manager; pass_manager.register_pass<ov::pass::ResolveGeneratedNameCollisions>(); pass_manager.run_passes(model); EXPECT_EQ(name, arg0->get_friendly_name()); EXPECT_NE(arg1->get_friendly_name(), arg0->get_friendly_name()); EXPECT_EQ(arg1->get_friendly_name(), arg0->get_friendly_name() + "_2"); } TEST(ResolveGeneratedNameCollisionsTest, DoNotFixFriendlyNames) { auto arg0 = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape{1, 3, 3, 3}); const auto gen_friendly_name = arg0->get_friendly_name(); arg0->set_friendly_name(gen_friendly_name); auto arg1 = std::make_shared<ov::opset8::Parameter>(ov::element::f32, ov::PartialShape{1, 2, 3, 3}); arg1->set_friendly_name(gen_friendly_name); auto concat = std::make_shared<ov::opset8::Concat>(ov::NodeVector{arg0, arg1}, 1); auto result1 = std::make_shared<ov::opset8::Result>(concat); auto model = std::make_shared<ov::Model>(ov::ResultVector{result1}, ov::ParameterVector{arg0, arg1}); EXPECT_EQ(gen_friendly_name, arg0->get_friendly_name()); EXPECT_EQ(arg1->get_friendly_name(), arg0->get_friendly_name()); EXPECT_NE(arg1->get_friendly_name(), arg0->get_friendly_name() + "_2"); ov::pass::Manager pass_manager; pass_manager.register_pass<ov::pass::ResolveGeneratedNameCollisions>(); pass_manager.run_passes(model); EXPECT_EQ(gen_friendly_name, arg0->get_friendly_name()); EXPECT_EQ(arg1->get_friendly_name(), arg0->get_friendly_name()); EXPECT_NE(arg1->get_friendly_name(), arg0->get_friendly_name() + "_2"); }
2,912
1,111
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Client for cert_provision library. #include <base/bind.h> #include <base/command_line.h> #include <base/files/file_util.h> #include <base/strings/string_number_conversions.h> #include <brillo/syslog_logging.h> #include "cryptohome/cert_provision.h" void ProgressCallback(cert_provision::Status status, int progress, const std::string& message) { LOG(INFO) << "ProgressCallback: " << static_cast<int>(status) << ", " << progress << "%: " << message; } void PrintHelp() { printf("Usage: cert_provision_client <command> [--v=<log_verbosity>]\n"); printf("Commands:\n"); printf(" Provision a certificate:\n"); printf(" --provision --label=<label> --pca=<type> --profile=<profile>\n"); printf(" where type: default, test\n"); printf(" profile: cast, jetstream\n"); printf(" Force enroll:\n"); printf(" --enroll --pca=<type>\n"); printf(" Print the provisioned certificate:\n"); printf(" --get --label=<label> --include_chain\n"); printf(" [--out=<file_out>]\n"); printf(" Sign using the provisioned certificate:\n"); printf(" --sign --label=<label> --in=<file_in> [--out=<file_out>]\n"); printf(" --mechanism=<mechanism>\n"); printf(" where mechanism: sha1_rsa, sha256_rsa, sha256_rsa_pss\n"); } int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); brillo::InitLog(brillo::kLogToSyslog | brillo::kLogToStderr); if (cl->HasSwitch("h") || cl->HasSwitch("help")) { PrintHelp(); return 2; } cert_provision::Status sts; if (cl->HasSwitch("provision")) { std::string cert_label = cl->GetSwitchValueASCII("label"); if (cert_label.empty()) { PrintHelp(); return 2; } cert_provision::PCAType pca_type; std::string pca = cl->GetSwitchValueASCII("pca"); if (pca == "default") { pca_type = cert_provision::PCAType::kDefaultPCA; } else if (pca == "test") { pca_type = cert_provision::PCAType::kTestPCA; } else { PrintHelp(); return 2; } cert_provision::CertificateProfile cert_profile; std::string profile = cl->GetSwitchValueASCII("profile"); if (profile == "cast") { cert_profile = cert_provision::CertificateProfile::CAST_CERTIFICATE; } else if (profile == "jetstream") { cert_profile = cert_provision::CertificateProfile::JETSTREAM_CERTIFICATE; } else { PrintHelp(); return 2; } sts = cert_provision::ProvisionCertificate(pca_type, std::string(), cert_label, cert_profile, base::Bind(&ProgressCallback)); if (sts != cert_provision::Status::Success) { LOG(ERROR) << "ProvisionCertificate returned " << static_cast<int>(sts); return 3; } VLOG(1) << "ProvisionCertificate returned " << static_cast<int>(sts); } else if (cl->HasSwitch("enroll")) { cert_provision::PCAType pca_type; std::string pca = cl->GetSwitchValueASCII("pca"); if (pca == "default") { pca_type = cert_provision::PCAType::kDefaultPCA; } else if (pca == "test") { pca_type = cert_provision::PCAType::kTestPCA; } else { PrintHelp(); return 2; } sts = cert_provision::ForceEnroll(pca_type, std::string(), base::Bind(&ProgressCallback)); if (sts != cert_provision::Status::Success) { LOG(ERROR) << "ForceEnroll returned " << static_cast<int>(sts); return 3; } VLOG(1) << "ForceEnroll returned " << static_cast<int>(sts); } else if (cl->HasSwitch("get")) { std::string cert_label = cl->GetSwitchValueASCII("label"); if (cert_label.empty()) { PrintHelp(); return 2; } std::string certificate; sts = cert_provision::GetCertificate( cert_label, cl->HasSwitch("include_chain"), &certificate); if (sts != cert_provision::Status::Success) { LOG(ERROR) << "GetCertificate returned " << static_cast<int>(sts); return 3; } VLOG(1) << "GetCertificate returned " << static_cast<int>(sts); base::FilePath out(cl->GetSwitchValueASCII("out")); if (!out.empty()) { if (base::WriteFile(out, certificate.data(), certificate.size()) < 0) { LOG(ERROR) << "Failed to write output file: " << out.value(); return 1; } } else { puts(certificate.c_str()); } } else if (cl->HasSwitch("sign")) { std::string cert_label = cl->GetSwitchValueASCII("label"); if (cert_label.empty()) { PrintHelp(); return 2; } base::FilePath in(cl->GetSwitchValueASCII("in")); if (in.empty()) { PrintHelp(); return 2; } cert_provision::SignMechanism sign_mechanism; std::string mechanism = cl->GetSwitchValueASCII("mechanism"); if (mechanism == "sha1_rsa") { sign_mechanism = cert_provision::SHA1_RSA_PKCS; } else if (mechanism == "sha256_rsa") { sign_mechanism = cert_provision::SHA256_RSA_PKCS; } else if (mechanism == "sha256_rsa_pss") { sign_mechanism = cert_provision::SHA256_RSA_PSS; } else { PrintHelp(); return 2; } std::string data; if (!base::ReadFileToString(in, &data)) { LOG(ERROR) << "Failed to read input file: " << in.value(); return 1; } std::string sig; sts = cert_provision::Sign(cert_label, sign_mechanism, data, &sig); if (sts != cert_provision::Status::Success) { LOG(ERROR) << "Sign returned " << static_cast<int>(sts); return 3; } VLOG(1) << "Sign returned " << static_cast<int>(sts); base::FilePath out(cl->GetSwitchValueASCII("out")); if (!out.empty()) { if (base::WriteFile(out, sig.data(), sig.size()) < 0) { LOG(ERROR) << "Failed to write output file: " << out.value(); return 1; } } else { puts(base::HexEncode(sig.data(), sig.size()).c_str()); } } return 0; }
6,201
2,141
//////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Graphics.hpp> #include <windows.h> #include <cmath> HWND button; //////////////////////////////////////////////////////////// /// Function called whenever one of our windows receives a message /// //////////////////////////////////////////////////////////// LRESULT CALLBACK OnEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { // Quit when we close the main window case WM_CLOSE : { PostQuitMessage(0); return 0; } // Quit when we click the "quit" button case WM_COMMAND : { if (reinterpret_cast<HWND>(lParam) == button) { PostQuitMessage(0); return 0; } } } return DefWindowProc(handle, message, wParam, lParam); } //////////////////////////////////////////////////////////// /// Entry point of application /// /// \param Instance : Instance of the application /// /// \return Error code /// //////////////////////////////////////////////////////////// INT WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, INT) { // Define a class for our main window WNDCLASS windowClass; windowClass.style = 0; windowClass.lpfnWndProc = &OnEvent; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = instance; windowClass.hIcon = NULL; windowClass.hCursor = 0; windowClass.hbrBackground = reinterpret_cast<HBRUSH>(COLOR_BACKGROUND); windowClass.lpszMenuName = NULL; windowClass.lpszClassName = TEXT("SFML App"); RegisterClass(&windowClass); // Let's create the main window HWND window = CreateWindow(TEXT("SFML App"), TEXT("SFML Win32"), WS_SYSMENU | WS_VISIBLE, 200, 200, 660, 520, NULL, NULL, instance, NULL); // Add a button for exiting button = CreateWindow(TEXT("BUTTON"), TEXT("Quit"), WS_CHILD | WS_VISIBLE, 560, 440, 80, 40, window, NULL, instance, NULL); // Let's create two SFML views HWND view1 = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 20, 20, 300, 400, window, NULL, instance, NULL); HWND view2 = CreateWindow(TEXT("STATIC"), NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, 340, 20, 300, 400, window, NULL, instance, NULL); sf::RenderWindow SFMLView1(view1); sf::RenderWindow SFMLView2(view2); // Load some images to display sf::Image image1, image2; if (!image1.LoadFromFile("resources/image1.jpg") || !image2.LoadFromFile("resources/image2.jpg")) return EXIT_FAILURE; sf::Sprite sprite1(image1); sf::Sprite sprite2(image2); sprite1.SetOrigin(sprite1.GetSize() / 2.f); sprite1.SetPosition(sprite1.GetSize() / 2.f); // Create a clock for measuring elapsed time sf::Clock clock; // Loop until a WM_QUIT message is received MSG message; message.message = static_cast<UINT>(~WM_QUIT); while (message.message != WM_QUIT) { if (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) { // If a message was waiting in the message queue, process it TranslateMessage(&message); DispatchMessage(&message); } else { // Clear views SFMLView1.Clear(); SFMLView2.Clear(); // Draw sprite 1 on view 1 sprite1.SetRotation(clock.GetElapsedTime() * 100); SFMLView1.Draw(sprite1); // Draw sprite 2 on view 2 sprite2.SetX(cos(clock.GetElapsedTime()) * 100); SFMLView2.Draw(sprite2); // Display each view on screen SFMLView1.Display(); SFMLView2.Display(); } } // Destroy the main window (all its child controls will be destroyed) DestroyWindow(window); // Don't forget to unregister the window class UnregisterClass(TEXT("SFML App"), instance); return EXIT_SUCCESS; }
4,245
1,374
/*============================================================================== Copyright (c) 2005-2010 Joel de Guzman Copyright (c) 2010 Thomas Heller 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) ==============================================================================*/ namespace detail { template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 1> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename qsboost::result_of< Fun(A0, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 2> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename qsboost::result_of< Fun(A0 , A1, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 3> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename qsboost::result_of< Fun(A0 , A1 , A2, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 4> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 5> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 6> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 7> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 8> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 9> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 10> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 11> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 12> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 13> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 14> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 15> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 16> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 17> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 18> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 19> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 20> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 21> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 22> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 23> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 24> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 25> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 26> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 27> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 28> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 29> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 30> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 31> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 32> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 33> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 34> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 35> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 36> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 37> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 38> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 39> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 40> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 41> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 42> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 43> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 44> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 45> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 46> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 47> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 48> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 49> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename proto::result_of::child_c<Expr, 48>::type A48; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47 , A48, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , proto::child_c< 48>(e) , qsboost::phoenix::context(s, d) ); } }; template <typename Fun, typename Expr, typename State, typename Data> struct call_impl<Fun, Expr, State, Data, 50> : proto::transform_impl<Expr, State, Data> { typedef typename qsboost::phoenix::result_of::context<State, Data>::type context_type; typedef typename proto::result_of::child_c<Expr, 0>::type A0; typedef typename proto::result_of::child_c<Expr, 1>::type A1; typedef typename proto::result_of::child_c<Expr, 2>::type A2; typedef typename proto::result_of::child_c<Expr, 3>::type A3; typedef typename proto::result_of::child_c<Expr, 4>::type A4; typedef typename proto::result_of::child_c<Expr, 5>::type A5; typedef typename proto::result_of::child_c<Expr, 6>::type A6; typedef typename proto::result_of::child_c<Expr, 7>::type A7; typedef typename proto::result_of::child_c<Expr, 8>::type A8; typedef typename proto::result_of::child_c<Expr, 9>::type A9; typedef typename proto::result_of::child_c<Expr, 10>::type A10; typedef typename proto::result_of::child_c<Expr, 11>::type A11; typedef typename proto::result_of::child_c<Expr, 12>::type A12; typedef typename proto::result_of::child_c<Expr, 13>::type A13; typedef typename proto::result_of::child_c<Expr, 14>::type A14; typedef typename proto::result_of::child_c<Expr, 15>::type A15; typedef typename proto::result_of::child_c<Expr, 16>::type A16; typedef typename proto::result_of::child_c<Expr, 17>::type A17; typedef typename proto::result_of::child_c<Expr, 18>::type A18; typedef typename proto::result_of::child_c<Expr, 19>::type A19; typedef typename proto::result_of::child_c<Expr, 20>::type A20; typedef typename proto::result_of::child_c<Expr, 21>::type A21; typedef typename proto::result_of::child_c<Expr, 22>::type A22; typedef typename proto::result_of::child_c<Expr, 23>::type A23; typedef typename proto::result_of::child_c<Expr, 24>::type A24; typedef typename proto::result_of::child_c<Expr, 25>::type A25; typedef typename proto::result_of::child_c<Expr, 26>::type A26; typedef typename proto::result_of::child_c<Expr, 27>::type A27; typedef typename proto::result_of::child_c<Expr, 28>::type A28; typedef typename proto::result_of::child_c<Expr, 29>::type A29; typedef typename proto::result_of::child_c<Expr, 30>::type A30; typedef typename proto::result_of::child_c<Expr, 31>::type A31; typedef typename proto::result_of::child_c<Expr, 32>::type A32; typedef typename proto::result_of::child_c<Expr, 33>::type A33; typedef typename proto::result_of::child_c<Expr, 34>::type A34; typedef typename proto::result_of::child_c<Expr, 35>::type A35; typedef typename proto::result_of::child_c<Expr, 36>::type A36; typedef typename proto::result_of::child_c<Expr, 37>::type A37; typedef typename proto::result_of::child_c<Expr, 38>::type A38; typedef typename proto::result_of::child_c<Expr, 39>::type A39; typedef typename proto::result_of::child_c<Expr, 40>::type A40; typedef typename proto::result_of::child_c<Expr, 41>::type A41; typedef typename proto::result_of::child_c<Expr, 42>::type A42; typedef typename proto::result_of::child_c<Expr, 43>::type A43; typedef typename proto::result_of::child_c<Expr, 44>::type A44; typedef typename proto::result_of::child_c<Expr, 45>::type A45; typedef typename proto::result_of::child_c<Expr, 46>::type A46; typedef typename proto::result_of::child_c<Expr, 47>::type A47; typedef typename proto::result_of::child_c<Expr, 48>::type A48; typedef typename proto::result_of::child_c<Expr, 49>::type A49; typedef typename qsboost::result_of< Fun(A0 , A1 , A2 , A3 , A4 , A5 , A6 , A7 , A8 , A9 , A10 , A11 , A12 , A13 , A14 , A15 , A16 , A17 , A18 , A19 , A20 , A21 , A22 , A23 , A24 , A25 , A26 , A27 , A28 , A29 , A30 , A31 , A32 , A33 , A34 , A35 , A36 , A37 , A38 , A39 , A40 , A41 , A42 , A43 , A44 , A45 , A46 , A47 , A48 , A49, context_type) >::type result_type; result_type operator()( typename call_impl::expr_param e , typename call_impl::state_param s , typename call_impl::data_param d ) const { return Fun()( proto::child_c< 0>(e) , proto::child_c< 1>(e) , proto::child_c< 2>(e) , proto::child_c< 3>(e) , proto::child_c< 4>(e) , proto::child_c< 5>(e) , proto::child_c< 6>(e) , proto::child_c< 7>(e) , proto::child_c< 8>(e) , proto::child_c< 9>(e) , proto::child_c< 10>(e) , proto::child_c< 11>(e) , proto::child_c< 12>(e) , proto::child_c< 13>(e) , proto::child_c< 14>(e) , proto::child_c< 15>(e) , proto::child_c< 16>(e) , proto::child_c< 17>(e) , proto::child_c< 18>(e) , proto::child_c< 19>(e) , proto::child_c< 20>(e) , proto::child_c< 21>(e) , proto::child_c< 22>(e) , proto::child_c< 23>(e) , proto::child_c< 24>(e) , proto::child_c< 25>(e) , proto::child_c< 26>(e) , proto::child_c< 27>(e) , proto::child_c< 28>(e) , proto::child_c< 29>(e) , proto::child_c< 30>(e) , proto::child_c< 31>(e) , proto::child_c< 32>(e) , proto::child_c< 33>(e) , proto::child_c< 34>(e) , proto::child_c< 35>(e) , proto::child_c< 36>(e) , proto::child_c< 37>(e) , proto::child_c< 38>(e) , proto::child_c< 39>(e) , proto::child_c< 40>(e) , proto::child_c< 41>(e) , proto::child_c< 42>(e) , proto::child_c< 43>(e) , proto::child_c< 44>(e) , proto::child_c< 45>(e) , proto::child_c< 46>(e) , proto::child_c< 47>(e) , proto::child_c< 48>(e) , proto::child_c< 49>(e) , qsboost::phoenix::context(s, d) ); } }; }
166,332
62,322
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *left, *right; }; bool iterativeSearch(struct Node* root, int key) { while (root != NULL) { if (key > root->data) root = root->right; else if (key < root->data) root = root->left; else return true; } return false; } struct Node* newNode(int item) { struct Node* temp = new Node; temp->data = item; temp->left = temp->right = NULL; return temp; } struct Node* insert(struct Node* Node, int data) { if (Node == NULL) return newNode(data); if (data < Node->data) Node->left = insert(Node->left, data); else if (data > Node->data) Node->right = insert(Node->right, data); return Node; } int main() { struct Node* root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout<<"Searching for 15: in 30 20 40 70 60 80 "<<endl; if (iterativeSearch(root, 15)) cout << "Found"; else cout << "Not Found"; return 0; }
1,039
441
#include <bits/stdc++.h> using namespace std; // input handle #define iln() scanf("\n") #define in(n) scanf("%d",&n) #define ins(n) scanf("%s",n) #define inc(n) scanf("%c",&n) #define inf(n) scanf("%lf",&n) #define inl(n) scanf("%lld",&n) #define ot(x) printf("%d", x) #define sp() printf(" ") #define ots(x) printf("%s", x) #define otc(x) printf("%c", x) #define ln() printf("\n") #define otl(x) printf("%lld", x) #define otf(x) printf("%.2lf", x) // helpers defines #define all(v) v.begin(), v.end() #define sz(v) ((int)((v).size())) #define ssz(s) ((int)strlen(s)) #define pb push_back #define mem(a,b) memset(a,b,sizeof(a)) //helpers void file() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); // freopen("ot.txt", "w", stdout); #else // freopen("jumping.in", "r", stdin); // HERE #endif } // constants #define EPS 1e-9 #define PI acos(-1.0) // important constant; alternative #define PI (2.0 * acos(0.0)) const int MN = 1e9 + 1e2; const int MW = 1e3 + 5; typedef long long int lli; const int OO = 1e9 + 5; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ii> vii; typedef pair<lli, string> lls; #define isOn(S, j) (S & (1 << j)) #define setBit(S, j) (S |= (1 << j)) #define clearBit(S, j) (S &= ~(1 << j)) int main() { file(); //TODO int n, m, k, p[1002] { 0 }, ans = 0; in(n), in(m), in(k); for (int i = 0; i <= m and in(p[i]); ++i) ; for (int i = 0, df = 0; i < m; ans += (df <= k), df = 0, ++i) for (int j = 0; j < 21 and df <= k; ++j) if (isOn(p[m],j) != isOn(p[i], j)) df++; ot(ans); return 0; }
1,574
758
// MIT Licensed (see LICENSE.md). #pragma once namespace Zero { /// Create the starting space and load the starting level into that space class DefaultGameSetup : public Component { public: ZilchDeclareType(DefaultGameSetup, TypeCopyMode::ReferenceType); DefaultGameSetup(); // Component Interface void Initialize(CogInitializer& initializer) override; void Serialize(Serializer& stream) override; void SetDefaults() override; // Space to create for the game. ResourceProperty(Archetype, StartingSpace); // Level to load into the game. ResourceProperty(Level, StartingLevel); void OnSetup(GameEvent* event); // If set to true StartingLevel will be overridden by the currently edited // level bool mLoadEditingLevel; }; } // namespace Zero
776
217
#include "GDCore/Serialization/SerializerElement.h" #include <iostream> namespace gd { SerializerElement SerializerElement::nullElement; SerializerElement::SerializerElement() : valueUndefined(true), isArray(false) {} SerializerElement::SerializerElement(const SerializerValue& value) : valueUndefined(false), elementValue(value), isArray(false) {} SerializerElement::~SerializerElement() {} const SerializerValue& SerializerElement::GetValue() const { if (valueUndefined && attributes.find("value") != attributes.end()) return attributes.find("value")->second; return elementValue; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, bool value) { attributes[name].SetBool(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, const gd::String& value) { attributes[name].SetString(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, int value) { attributes[name].SetInt(value); return *this; } SerializerElement& SerializerElement::SetAttribute(const gd::String& name, double value) { attributes[name].SetDouble(value); return *this; } bool SerializerElement::GetBoolAttribute(const gd::String& name, bool defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) { return attributes.find(name)->second.GetBool(); } else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) { return attributes.find(deprecatedName)->second.GetBool(); } else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) { return child.GetValue().GetBool(); } } } std::cout << "Bool attribute \"" << name << "\" not found, returning " << defaultValue; return defaultValue; } gd::String SerializerElement::GetStringAttribute( const gd::String& name, gd::String defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetString(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetString(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetString(); } } return defaultValue; } int SerializerElement::GetIntAttribute(const gd::String& name, int defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetInt(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetInt(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetInt(); } } return defaultValue; } double SerializerElement::GetDoubleAttribute(const gd::String& name, double defaultValue, gd::String deprecatedName) const { if (attributes.find(name) != attributes.end()) return attributes.find(name)->second.GetDouble(); else if (!deprecatedName.empty() && attributes.find(deprecatedName) != attributes.end()) return attributes.find(deprecatedName)->second.GetDouble(); else { if (HasChild(name, deprecatedName)) { SerializerElement& child = GetChild(name, 0, deprecatedName); if (!child.IsValueUndefined()) return child.GetValue().GetDouble(); } } return defaultValue; } bool SerializerElement::HasAttribute(const gd::String& name) const { return attributes.find(name) != attributes.end(); } SerializerElement& SerializerElement::AddChild(gd::String name) { if (!arrayOf.empty()) { if (name != arrayOf) { std::cout << "WARNING: Adding a child, to a SerializerElement which is " "considered as an array, with a name (" << name << ") which is not the same as the array elements (" << arrayOf << "). Child was renamed." << std::endl; name = arrayOf; } } std::shared_ptr<SerializerElement> newElement(new SerializerElement); children.push_back(std::make_pair(name, newElement)); return *newElement; } SerializerElement& SerializerElement::GetChild(std::size_t index) const { if (arrayOf.empty()) { std::cout << "ERROR: Getting a child from its index whereas the parent is " "not considered as an array." << std::endl; return nullElement; } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == arrayOf || children[i].first.empty() || (!deprecatedArrayOf.empty() && children[i].first == deprecatedArrayOf)) { if (index == currentIndex) return *children[i].second; else currentIndex++; } } std::cout << "ERROR: Request out of bound child at index " << index << std::endl; return nullElement; } SerializerElement& SerializerElement::GetChild( gd::String name, std::size_t index, gd::String deprecatedName) const { if (!arrayOf.empty()) { if (name != arrayOf) { std::cout << "WARNING: Getting a child, from a SerializerElement which " "is considered as an array, with a name (" << name << ") which is not the same as the array elements (" << arrayOf << ")." << std::endl; name = arrayOf; } } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!arrayOf.empty() && children[i].first.empty()) || (!deprecatedName.empty() && children[i].first == deprecatedName)) { if (index == currentIndex) return *children[i].second; else currentIndex++; } } std::cout << "Child " << name << " not found in SerializerElement::GetChild" << std::endl; return nullElement; } std::size_t SerializerElement::GetChildrenCount( gd::String name, gd::String deprecatedName) const { if (name.empty()) { if (arrayOf.empty()) { std::cout << "ERROR: Getting children count without specifying name, from a " "SerializerElement which is NOT considered as an array." << std::endl; return 0; } name = arrayOf; deprecatedName = deprecatedArrayOf; } std::size_t currentIndex = 0; for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!arrayOf.empty() && children[i].first.empty()) || (!deprecatedName.empty() && children[i].first == deprecatedName)) currentIndex++; } return currentIndex; } bool SerializerElement::HasChild(const gd::String& name, gd::String deprecatedName) const { for (size_t i = 0; i < children.size(); ++i) { if (children[i].second == std::shared_ptr<SerializerElement>()) continue; if (children[i].first == name || (!deprecatedName.empty() && children[i].first == deprecatedName)) return true; } return false; } } // namespace gd
8,110
2,296
/*! * \file SickNav350.hh * \brief Defines the SickNav350 class for working with the * Sick NAV350. * * Code by Jason C. Derenick and Thomas H. Miller. * Contact derenick(at)lehigh(dot)edu * * The Sick LIDAR Matlab/C++ Toolbox * Copyright (c) 2008, Jason C. Derenick and Thomas H. Miller * All rights reserved. * * This software is released under a BSD Open-Source License. * See http://sicktoolbox.sourceforge.net */ #ifndef SICK_NAV350_HH #define SICK_NAV350_HH /* Macros */ #define DEFAULT_SICK_IP_ADDRESS "192.168.1.10" ///< Default Sick LD INet 4 address #define DEFAULT_SICK_TCP_PORT (2111) ///< Default TCP port #define DEFAULT_SICK_MESSAGE_TIMEOUT (unsigned int)(5e6) ///< The max time to wait for a message reply (usecs) #define DEFAULT_SICK_CONNECT_TIMEOUT (unsigned int)(1e6) ///< The max time to wait before considering a connection attempt as failed (usecs) #define DEFAULT_SICK_NUM_SCAN_PROFILES (0) ///< Setting this value to 0 will tell the Sick LD to stream measurements when measurement data is requested (NOTE: A profile is a single scans worth of range measurements) #define DEFAULT_SICK_SIGNAL_SET (0) ///< Default Sick signal configuration /** * \def SWAP_VALUES(x,y,t) * \brief A simple macro for swapping two values. */ #define SWAP_VALUES(x,y,t) (t=x,x=y,y=t); /* Definition dependencies */ #include <string> #include <vector> #include <pthread.h> #include <arpa/inet.h> #include <stdlib.h> #include "sicktoolbox/SickLIDAR.hh" #include "sicktoolbox/SickNAV350BufferMonitor.hh" #include "sicktoolbox/SickNAV350Message.hh" #include "sicktoolbox/SickException.hh" #define SICK_MAX_NUM_REFLECTORS 50 /** * \namespace SickToolbox * \brief Encapsulates the Sick NAV350 Matlab/C++ toolbox */ namespace SickToolbox { /** * \class SickNav350 * \brief Provides a simple driver interface for working with the * Sick Nav350 long-range models via Ethernet. */ struct sick_nav350_reflector_tag{ unsigned int error; unsigned int filter; unsigned int landmarkDataFollow; unsigned int num_reflector; unsigned int cart[SICK_MAX_NUM_REFLECTORS]; double x[SICK_MAX_NUM_REFLECTORS]; double y[SICK_MAX_NUM_REFLECTORS]; unsigned int polar[SICK_MAX_NUM_REFLECTORS]; double dist[SICK_MAX_NUM_REFLECTORS]; double phi[SICK_MAX_NUM_REFLECTORS]; unsigned int optional[SICK_MAX_NUM_REFLECTORS]; unsigned int LocalID[SICK_MAX_NUM_REFLECTORS]; unsigned int GlobalID[SICK_MAX_NUM_REFLECTORS]; unsigned int type[SICK_MAX_NUM_REFLECTORS]; unsigned int subtype[SICK_MAX_NUM_REFLECTORS]; unsigned int quality[SICK_MAX_NUM_REFLECTORS]; unsigned int timestamp[SICK_MAX_NUM_REFLECTORS]; unsigned int size [SICK_MAX_NUM_REFLECTORS]; unsigned int hitCount[SICK_MAX_NUM_REFLECTORS]; unsigned int meanEchoAmplitude[SICK_MAX_NUM_REFLECTORS]; unsigned int indexStart[SICK_MAX_NUM_REFLECTORS]; unsigned int indexEnd[SICK_MAX_NUM_REFLECTORS]; } ; struct sick_nav350_pose_tag{ unsigned int error; int x; int y; unsigned int phi; unsigned int optionalPoseData; unsigned int outputMode; unsigned int timeStamp; int meanDeviation; int positionMode; int infoState; int numUsedReflectors; int optionalLandmarkData; }; class SickNav350 : public SickLIDAR< SickNav350BufferMonitor, SickNav350Message > { public: /* Some constants for the developer/end-user */ static const uint16_t SICK_MAX_NUM_MEASUREMENTS = 2881; ///< Maximum number of measurements per sector static const uint16_t SICK_MAX_NUM_SECTORS = 8; ///< Maximum number of scan sectors (NOTE: This value must be even) static const uint16_t SICK_MAX_NUM_MEASURING_SECTORS = 4; ///< Maximum number of active/measuring scan sectors static const uint16_t SICK_MAX_SCAN_AREA = 360; ///< Maximum area that can be covered in a single scan (deg) static const uint16_t SICK_MIN_MOTOR_SPEED = 8; ///< Minimum motor speed in Hz static const uint16_t SICK_MAX_MOTOR_SPEED = 8; ///< Maximum motor speed in Hz static const uint16_t SICK_MIN_VALID_SENSOR_ID = 1; ///< The lowest value the Sick will accept as a Sensor ID static const uint16_t SICK_MAX_VALID_SENSOR_ID = 254; ///< The largest value the Sick will accept as a Sensor ID static const uint16_t SICK_MAX_MEAN_PULSE_FREQUENCY = 10800; ///< Max mean pulse frequence of the current device configuration (in Hz) (see page 22 of the operator's manual) static const uint16_t SICK_MAX_PULSE_FREQUENCY = 14400; ///< Max pulse frequency of the device (in Hz) (see page 22 of the operator's manual) static const uint16_t SICK_NUM_TICKS_PER_MOTOR_REV = 5760; ///< Odometer ticks per revolution of the Sick LD scan head static const double SICK_MAX_SCAN_ANGULAR_RESOLUTION = 0.125; ///< Minimum valid separation between laser pulses in active scan ares (deg) static const double SICK_DEGREES_PER_MOTOR_STEP = 0.0625; ///< Each odometer tick is equivalent to rotating the scan head this many degrees /* Sick NAV350 sensor modes of operation */ static const uint8_t SICK_SENSOR_MODE_POWERDOWN = 0x00; ///< The Sick LD is powered down static const uint8_t SICK_SENSOR_MODE_STANDBY = 0x01; ///< The Sick NAV350 is in standby static const uint8_t SICK_SENSOR_MODE_MAPPING = 0x02; ///< The Sick NAV350 is mapping static const uint8_t SICK_SENSOR_MODE_LMDETECTION = 0x03; ///< The Sick NAV350 is detecting landmarks static const uint8_t SICK_SENSOR_MODE_NAVIGATION = 0x04; ///< The Sick Nav350 is in navigation mode /* COMMAND TYPE */ static const std::string READBYNAME_COMMAND; static const std::string WRITEBYNAME_COMMAND; static const std::string METHODCALL_COMMAND; /* COMMAND */ static const std::string DEVICEIDENT_COMMAND; static const std::string SERIALNUMBER_COMMAND; static const std::string DEVICEINFO_COMMAND; static const std::string FIRMWAREVERSION_COMMAND; static const std::string CURLAYER_COMMAND; static const std::string IDENTWINDOW_COMMAND; static const std::string CFGMAPPING_COMMAND; static const std::string SLIDINGMEAN_COMMAND; static const std::string POSDATAFORMAT_COMMAND; static const std::string LMDATAFORMAT_COMMAND; static const std::string SCANDATAFORMAT_COMMAND; static const std::string HWTIMESYNC_COMMAND; static const std::string REFLECTORSIZE_COMMAND; static const std::string REFLECTORTYPE_COMMAND; static const std::string LMMATCHING_COMMAND; static const std::string SECTORMUTING_COMMAND; static const std::string COORDORIENTATION_COMMAND; static const std::string CLOSESTREFL_COMMAND; static const std::string ACTIONRADIUS_COMMAND; static const std::string REFLTHRESHOLD_COMMAND; static const std::string SETMODE_COMMAND; static const std::string SETACCESSMODE_COMMAND; static const std::string SETPERMDATA_COMMAND; static const std::string SYNCTIMESTAMP_COMMAND; static const std::string NAVBREAK_COMMAND; static const std::string NAVRESET_COMMAND; static const std::string CFGSERIAL_COMMAND; static const std::string CFGIP_COMMAND; static const std::string CFGETH_COMMAND; static const std::string ENABLEDHCP_COMMAND; static const std::string ADDLANDMARK_COMMAND; static const std::string EDITLANDMARK_COMMAND; static const std::string DELETELANDMARK_COMMAND; static const std::string READLANDMARK_COMMAND; static const std::string READLAYER_COMMAND; static const std::string READLAYOUT_COMMAND; static const std::string ERASELAYOUT_COMMAND; static const std::string SAVELAYOUT_COMMAND; static const std::string DOMAPPING_COMMAND; static const std::string GETLANDMARK_COMMAND; static const std::string POSEREQ_COMMAND; static const std::string POSEDATA_COMMAND; static const std::string SETSPEED_COMMAND; static const std::string SETPOSE_COMMAND; static const std::string SETPOSEID_COMMAND; /** * \struct sick_nav350_config_global_tag * \brief A structure to aggregate the data used to configure the * Sick NAV350 global parameter values. */ /** * \typedef sick_nav350_config_global_t * \brief Adopt c-style convention */ typedef struct sick_nav350_config_global_tag { uint16_t sick_sensor_id; ///< The single word sensor ID for the Sick unit uint16_t sick_motor_speed; ///< Nominal motor speed value: 0x0005 to 0x0014 (5 to 20) double sick_angle_step; ///< Difference between two laser pulse positions in 1/16th deg. (NOTE: this value must be a divisor of 5760 and be greater than 1) } sick_nav350_config_global_t; /** * \struct sick_nav350_config_ethernet_tag * \brief A structure to aggregate the data used to configure * the Sick LD unit for Ethernet. * * \todo Eventually add similar config structures for the other protocols. */ /** * \typedef sick_nav350_config_ethernet_t * \brief Adopt c-style convention */ typedef struct sick_nav350_config_ethernet_tag { uint16_t sick_ip_address[4]; ///< IP address in numerical form w/ leftmost part at sick_ip_address[0] uint16_t sick_subnet_mask[4]; ///< Subnet mask for the network to which the Sick LD is assigned uint16_t sick_gateway_ip_address[4]; ///< The address of the local gateway uint16_t sick_node_id; ///< Single word address of the Sick LD uint16_t sick_transparent_tcp_port; ///< The TCP/IP transparent port associated with the Sick LD } sick_nav350_config_ethernet_t; /** * \struct sick_nav350_config_sector_tag * \brief A structure to aggregate data used to define the * Sick LD's sector configuration. */ /** * \typedef sick_nav350_config_sector_t * \brief Adopt c-style convention */ typedef struct sick_nav350_config_sector_tag { uint8_t sick_num_active_sectors; ///< Number of active sectors (sectors that are actually being scanned) uint8_t sick_num_initialized_sectors; ///< Number of sectors configured w/ a function other than "not initialized" uint8_t sick_active_sector_ids[SICK_MAX_NUM_SECTORS]; ///< IDs of all active sectors uint8_t sick_sector_functions[SICK_MAX_NUM_SECTORS]; ///< Function values associated w/ each of the Sick LD's sectors double sick_sector_start_angles[SICK_MAX_NUM_SECTORS]; ///< Start angles for each initialized sector (deg) double sick_sector_stop_angles[SICK_MAX_NUM_SECTORS]; ///< Stop angles for each sector (deg) } sick_nav350_config_sector_t; /** * \struct sick_nav350_identity_tag * \brief A structure to aggregate the fields that collectively * define the identity of a Sick LD unit. */ /** * \typedef sick_nav350_identity_t * \brief Adopt c-style convention */ typedef struct sick_nav350_identity_tag { std::string sick_part_number; ///< The Sick LD's part number std::string sick_name; ///< The name assigned to the Sick std::string sick_version; ///< The Sick LD's version number std::string sick_serial_number; ///< The Sick LD's serial number std::string sick_edm_serial_number; ///< The Sick LD's edm??? serial number std::string sick_firmware_part_number; ///< The Sick LD's firmware part number std::string sick_firmware_name; ///< The Sick LD's firmware name std::string sick_firmware_version; ///< The Sick LD's firmware version std::string sick_application_software_part_number; ///< The Sick LD's app. software part number std::string sick_application_software_name; ///< The Sick LD's app. software name std::string sick_application_software_version; ///< The Sick LD's app. software version } sick_nav350_identity_t; sick_nav350_reflector_tag ReflectorData_; sick_nav350_pose_tag PoseData_; /** * \struct sick_nav350_sector_data_tag * \brief A structure to aggregate the fields that collectively * define a sector in the scan area of the Sick LD unit. */ /** * \typedef sick_nav350_sector_data_t * \brief Adopt c-style convention */ typedef struct sick_nav350_sector_data_tag { unsigned int sector_num; ///< The sector number in the scan area unsigned int num_data_points; ///< The number of data points in the scan area unsigned int timestamp_start; ///< The timestamp (in ms) corresponding to the time the first measurement in the sector was taken unsigned int timestamp_stop; ///< The timestamp (in ms) corresponding to the time the last measurement in the sector was taken unsigned int echo_values[SICK_MAX_NUM_MEASUREMENTS]; ///< The corresponding echo/reflectivity values double angle_step; ///< The angle step used for the given sector (this should be the same for all sectors) double angle_start; ///< The angle at which the first measurement in the sector was acquired double angle_stop; ///< The angle at which the last measurement in the sector was acquired double range_values[SICK_MAX_NUM_MEASUREMENTS]; ///< The corresponding range values (NOTE: The size of this array is intended to be large enough to accomodate various sector configs.) double scan_angles[SICK_MAX_NUM_MEASUREMENTS]; ///< The scan angles corresponding to the respective measurements } sick_nav350_sector_data_t; /** * \struct sick_nav350_scan_profile_tag * \brief A structure to aggregate the fields that collectively * define the profile of a single scan acquired from the * Sick LD unit. */ /** * \typedef sick_nav350_scan_profile_t * \brief Adopt c-style convention */ typedef struct sick_nav350_scan_profile_tag { unsigned int profile_number; ///< The number of profiles sent to the host (i.e. the current profile number) unsigned int profile_counter; ///< The number of profiles gathered by the Sick LD unsigned int layer_num; ///< The layer number associated with a scan (this will always be 0) unsigned int sensor_status; ///< The status of the Sick LD sensor unsigned int motor_status; ///< The status of the Sick LD motor unsigned int num_sectors; ///< The number of sectors returned in the profile sick_nav350_sector_data_t sector_data[SICK_MAX_NUM_SECTORS]; ///< The sectors associated with the scan profile } sick_nav350_scan_profile_t; sick_nav350_sector_data_tag* MeasuredData_; /** Primary constructor */ SickNav350( const std::string sick_ip_address = DEFAULT_SICK_IP_ADDRESS, const uint16_t sick_tcp_port = DEFAULT_SICK_TCP_PORT ); /** Initializes the Sick LD unit (use scan areas defined in flash) */ void Initialize( ) throw( SickIOException, SickThreadException, SickTimeoutException, SickErrorException ); /** Initializes the Sick LD unit (use scan areas defined in flash) */ void Uninitialize( ) throw (SickIOException, SickThreadException, SickTimeoutException, SickErrorException); /** Gets the sensor and motor mode of the unit */ void GetSickStatus( unsigned int &sick_sensor_mode, unsigned int &sick_motor_mode ) throw( SickIOException, SickTimeoutException ); /** Sets the temporal scan configuration (until power is cycled) */ void SetSickTempScanAreas( const double * active_sector_start_angles, const double * const active_sector_stop_angles, const unsigned int num_active_sectors ) throw( SickTimeoutException, SickIOException, SickConfigException ); /** Sets the internal clock of the Sick LD unit */ void SetSickTimeAbsolute( const uint16_t absolute_clock_time, uint16_t &new_sick_clock_time ) throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException ); /** Sets the internal clock of the Sick LD using the relative given time value */ void SetSickTimeRelative( const int16_t time_delta, uint16_t &new_sick_clock_time ) throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException ); /** Gets the internal clock time of the Sick LD unit */ void GetSickTime( uint16_t &sick_time ) throw( SickIOException, SickTimeoutException, SickErrorException ); /** Sets the scan data format to be used (until power is cycled). This is defined on Page 26 of NAV350 Telegram Listing **/ void SetScanDataFormat (uint8_t dataMode, uint8_t showRSSI) throw( SickIOException, SickTimeoutException, SickErrorException ); /** Sets the access mode */ void SetAccessMode( uint8_t newMode) throw(SickIOException, SickTimeoutException, SickErrorException); /** Acquire the Sick LD's current scan resolution */ double GetSickScanResolution( ) const; /** Acquire the current IP address of the Sick */ std::string GetSickIPAddress( ) const; /** Acquire the subnet mask for the Sick */ std::string GetSickSubnetMask( ) const; /** Acquire the IP address of the Sick gateway */ std::string GetSickGatewayIPAddress( ) const; /** Acquire the Sick LD's part number */ std::string GetSickPartNumber( ) const; /** Acquire the Sick LD's name */ std::string GetSickName( ) const; /** Acquire the Sick LD's version number */ std::string GetSickVersion( ) const; std::string GetSickSerialNumber( ) const; std::string GetSickFirmwareVersion( ) const; std::string GetSickSoftwareVersion( ) const; void SetCurrentLayer(uint16_t layer); std::string GetCurrentLayer(); void SetReflectorWindow(uint16_t winLow, uint16_t winHigh, uint32_t distLow, uint32_t distHigh); std::string GetReflectorWindow(); void SetMappingConfiguration(uint8_t mean, uint8_t negative, int x, int y, int phi); std::string GetMappingConfiguration(); void SetSlidingMean(uint8_t mean); std::string GetSlidingMean(); void SetPoseDataFormat(uint8_t outputMode, uint8_t showOptParam); std::string GetPoseDataFormat(); void SetLandmarkDataFormat(int format, int showOptParam, int landmarkFilter); std::string GetLandmarkDataFormat(); std::string GetScanDataFormat(); void SetTimeSync(uint8_t mode, uint8_t mask); std::string GetTimeSync(); void SetReflectorSize(uint16_t size); std::string GetReflectorSize(); void SetReflectorType(uint8_t type); std::string GetReflectorType(); void SetLandmarkMatching(uint8_t filter); std::string GetLandmarkMatching(); void SetSectorMuting(uint32_t angleFrom_0, uint32_t angleTo_0, bool isActive_0,uint32_t angleFrom_1, uint32_t angleTo_1, bool isActive_1,uint32_t angleFrom_2, uint32_t angleTo_2, bool isActive_2,uint32_t angleFrom_3, uint32_t angleTo_3, bool isActive_3); std::string GetMutedSectors(); void SetCoordinateOrientation(uint8_t dir); std::string GetCoordinateOrientation(); void SetNClosestReflectors(uint8_t num); std::string GetNClosestReflectors(); void SetActionRadius(int min, int max); std::string GetActionRadius(); void SetReflectorThreshold(int percent); std::string GetReflectorThreshold(); void SetDataPermenant(); void SyncTimeStamp(); void BreakAsyncCall(); void ResetDevice(); void SetSerialConfig(uint8_t baudrate, uint8_t dataBits, uint8_t parity, uint8_t stopBits); void SetIPConfig(uint8_t ipAddress, uint8_t subnetMask, uint8_t gateway); void SetEthConfig(uint8_t speedDuplex); void EnableDHCP(bool isEnable); void AddLandmark(uint16_t num, int data[][7]); void EditLandmark(uint16_t num, uint16_t id, int x, int y, uint8_t lmType, uint8_t reflectorType, uint16_t size, uint16_t layer, uint16_t layerID); void DeleteLandmark(uint16_t num, int id[]); void GetLandmark(uint16_t num, uint16_t id); void GetLayer(uint16_t id); void GetLayout(); void EraseLayout(uint8_t mem); void SaveLayout(); void DoMapping(); void GetLandmarkData(bool useNewLandmark, uint8_t dataFormat); void GetPose(bool wait); void GetPoseNScan(bool wait, uint8_t data); void SetSpeed(double x, double y, double phi, int timestamp, int coordbase); void SetPose(double x, double y, double phi); void SetPoseID(uint16_t id); /** Get Sick Identity */ void GetSickIdentity(); /** Change to navigation mode */ void SetOperatingMode(int mode); /**Get data */ void GetPoseData(int wait,int dataset); void GetDataLandMark(int wait,int dataset); void GetDataNavigation(int wait,int dataset); /**Get Measurements*/ void GetSickMeasurements(double* range_values,unsigned int *num_measurements, double *sector_step_angle, double *sector_start_angle, double *sector_stop_angle, unsigned int *sector_start_timestamp, unsigned int *sector_stop_timestamp); void GetSickMeasurementsWithRemission(double* range_values, unsigned int *remission_values,unsigned int *num_measurements, double *sector_step_angle, double *sector_start_angle, double *sector_stop_angle, unsigned int *sector_start_timestamp, unsigned int *sector_stop_timestamp); /**Send custom message and get response*/ void GetResponseFromCustomMessage(uint8_t *req,int req_size,uint8_t *res,int *res_size); /** Destructor */ ~SickNav350(); private: std::string* arg; int argumentcount_; /** The Sick LD IP address */ std::string _sick_ip_address; /** The Sick LD TCP port number */ uint16_t _sick_tcp_port; // /** Sick LD socket structure */ // unsigned int _socket; /** Sick LD socket address structure */ struct sockaddr_in _sick_inet_address_info; /** Indicates whether the Sick LD is currently streaming range data */ bool _sick_streaming_range_data; /** Indicates whether the Sick LD is currently streaming range and echo data */ bool _sick_streaming_range_and_echo_data; /** The identity structure for the Sick */ sick_nav350_identity_t _sick_identity; /** The current global configuration for the unit */ sick_nav350_config_global_t _sick_global_config; /** The current Ethernet configuration for the unit */ sick_nav350_config_ethernet_t _sick_ethernet_config; /** The current sector configuration for the unit */ sick_nav350_config_sector_t _sick_sector_config; /** Setup the connection parameters and establish TCP connection! */ void _setupConnection( ) throw( SickIOException, SickTimeoutException ); /** Synchronizes the driver state with the Sick LD (used for initialization) */ void _syncDriverWithSick( ) throw( SickIOException, SickTimeoutException, SickErrorException ); /** Set the function for a particular scan secto */ void _setSickSectorFunction( const uint8_t sector_number, const uint8_t sector_function, const double sector_angle_stop, const bool write_to_flash = false ) throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException ); /** Acquires the given Sector's function (i.e. current config) */ void _getSickSectorFunction( const uint8_t sector_num, uint8_t &sector_function, double &sector_stop_angle ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Sets the Sick LD to IDLE mode */ void _setSickSensorModeToIdle( ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Sets the Sick LD to ROTATE mode */ void _setSickSensorModeToRotate( ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Sets the Sick LD to MEASURE mode */ void _setSickSensorModeToMeasure( ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Sets the Sick LD's sensor mode to IDLE (laser off, motor off) */ void _setSickSensorMode( const uint8_t new_sick_sensor_mode ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Requests n range measurement profiles from the Sick LD */ void _getSickScanProfiles( const uint16_t profile_format, const uint16_t num_profiles = DEFAULT_SICK_NUM_SCAN_PROFILES ) throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException ); /** Parses a sequence of bytes and populates the profile_data struct w/ the results */ void _parseScanProfile( uint8_t * const src_buffer, sick_nav350_scan_profile_t &profile_data ) const; /** Cancels the active data stream */ void _cancelSickScanProfiles( ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Turns nearfield suppression on/off */ void _setSickFilter( const uint8_t suppress_code ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Stores an image of the Sick LD's identity locally */ void _getSickIdentity( ) /*throw( SickTimeoutException, SickIOException )*/; void _getSickSerialNumber(); void _getSickFirmwareVersion(); void _getSickSoftwareVersion(); /** Query the Sick for its sensor and motor status */ void _getSickStatus( ) throw( SickTimeoutException, SickIOException ); /** Sets the Sick LD's global configuration (in flash) */ void _setSickGlobalConfig( const uint8_t sick_sensor_id, const uint8_t sick_motor_speed, const double sick_angle_step ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Query the Sick for its global configuration parameters */ void _getSickGlobalConfig( ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Query the Sick for its Ethernet configuration parameters */ void _getSickEthernetConfig( ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Acquires the configuration (function and stop angle) for each sector */ void _getSickSectorConfig( ) throw( SickErrorException, SickTimeoutException, SickIOException ); /** Query the Sick for ID information */ void _getIdentificationString( const uint8_t id_request_code, std::string &id_return_string ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for its sensor part number */ void _getSensorPartNumber( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for its assigned name */ void _getSensorName( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for its version number */ void _getSensorVersion( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for its serial number */ void _getSensorSerialNumber( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for its EDM unit's serial number */ void _getSensorEDMSerialNumber( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for the part number of its firmware */ void _getFirmwarePartNumber( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for the name of its firmware */ void _getFirmwareName( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for the version of the firmware */ void _getFirmwareVersion( ) throw( SickTimeoutException, SickIOException ); /** Query the part number of the application software */ void _getApplicationSoftwarePartNumber( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for the application name */ void _getApplicationSoftwareName( ) throw( SickTimeoutException, SickIOException ); /** Query the Sick for the application software version */ void _getApplicationSoftwareVersion( ) throw( SickTimeoutException, SickIOException ); /** Allows setting the global parameters and scan area definition (in flash) */ void _setSickGlobalParamsAndScanAreas( const unsigned int sick_motor_speed, const double sick_step_angle, const double * const active_sector_start_angles, const double * const active_sector_stop_angles, const unsigned int num_active_sectors ) throw( SickTimeoutException, SickIOException, SickConfigException, SickErrorException ); /** Allows setting a temporary (until a device reset) sector configuration on the device */ void _setSickTemporaryScanAreas( const double * const active_sector_start_angles, const double * const active_sector_stop_angles, const unsigned int num_active_sectors ) throw( SickTimeoutException, SickIOException, SickConfigException ); /** Sets the sick sector configuration */ void _setSickSectorConfig( const unsigned int * const sector_functions, const double * const sector_stop_angles, const unsigned int num_sectors, const bool write_to_flash = false ) throw( SickErrorException, SickTimeoutException, SickIOException, SickConfigException ); /** Sets the signals for the device */ void _setSickSignals( const uint8_t sick_signal_flags = DEFAULT_SICK_SIGNAL_SET ) throw( SickIOException, SickTimeoutException, SickErrorException ); /** Flushed the TCP receive buffer */ void _flushTCPRecvBuffer( ) throw ( SickIOException, SickThreadException ); /** Generates a device-ready sector set given only an active sector spec. */ void _generateSickSectorConfig( const double * const active_sector_start_angles, const double * const active_sector_stop_angles, const unsigned int num_active_sectors, const double sick_step_angle, unsigned int * const sector_functions, double * const sector_stop_angles, unsigned int &num_sectors ) const; /** Converts odometry ticks to an equivalent angle */ double _ticksToAngle( const uint16_t ticks ) const; /** Converts angle to an equivalent representation in odometer ticks */ uint16_t _angleToTicks( const double angle ) const; /** Computes the mean pulse frequency for the given config */ double _computeMeanPulseFrequency( const double active_scan_area, const double curr_motor_speed, const double curr_angular_resolution ) const; /** Computes the total pulse frequency for the given config */ double _computeMaxPulseFrequency( const double total_scan_area, const double curr_motor_speed, const double curr_angular_resolution ) const; /** Indicates whether a given sensor ID is valid for the device */ bool _validSickSensorID( const unsigned int sick_sensor_id ) const; /** Indicates whether a given motor speed is valid for the device */ bool _validSickMotorSpeed( const unsigned int sick_motor_speed ) const; /** Indicates whether a given motor speed is valid for the device */ bool _validSickScanResolution( const double sick_step_angle, const double * const active_sector_start_angles, const double * const active_sector_stop_angles, const unsigned int num_active_sectors ) const; /** Indicates whether the given configuration yields a valid max and mean pulse frequency */ bool _validPulseFrequency( const unsigned int sick_motor_speed, const double sick_step_angle ) const; /** Indicates whether the given configuration yields a valid max and mean pulse frequency */ bool _validPulseFrequency( const unsigned int sick_motor_speed, const double sick_step_angle, const double * const active_sector_start_angles, const double * const active_sector_stop_angles, const unsigned int num_active_sectors ) const; /** Returns the scanning area for the device given the current sector configuration */ double _computeScanArea( const double sick_step_angle, const double * const sector_start_angles, const double * const sector_stop_angles, const unsigned int num_sectors ) const; /** Reorders given sector angle sets */ void _sortScanAreas( double * const sector_start_angles, double * const sector_stop_angles, const unsigned int num_sectors ) const; /** Checks the given sector arguments for overlapping regions yielding an invalid configuration */ bool _validActiveSectors( const double * const sector_start_angles, const double * const sector_stop_angles, const unsigned int num_active_sectors ) const; /** Indicates whether the supplied profile format is currently supported by the driver */ bool _supportedScanProfileFormat( const uint16_t profile_format ) const; /** Prints data corresponding to a single scan sector (data obtained using GET_PROFILE) */ void _printSectorProfileData( const sick_nav350_sector_data_t &sector_data ) const; /** Prints the data corresponding to the given scan profile (for debugging purposes) */ void _printSickScanProfile( const sick_nav350_scan_profile_t profile_data, const bool print_sector_data = true ) const; /** Converts _sick_sensor_mode to a representative string */ std::string _sickSensorModeToString( const uint8_t sick_sensor_mode ) const; /** Converts _sick_motor_mode to a representative string */ std::string _sickMotorModeToString( const uint8_t sick_motor_mode ) const; /** Converts the specified trans measurement mode return value to a string */ std::string _sickTransMeasureReturnToString( const uint8_t return_value ) const; /** Converts the specified reset level to a representative string */ std::string _sickResetLevelToString( const uint16_t reset_level ) const; /** Converts Sick LD sector configuration word to a representative string */ std::string _sickSectorFunctionToString( const uint16_t sick_sector_function ) const; /** Converts a given scan profile format to a string for friendlier output */ std::string _sickProfileFormatToString( const uint16_t profile_format ) const; /** Teardown the connection to the Sick LD */ void _teardownConnection( ) throw( SickIOException ); /** Send a message, get the reply from the Sick Nav350 and check it */ void _sendMessageAndGetReply( const SickNav350Message &send_message, SickNav350Message &recv_message, const unsigned int timeout_value = DEFAULT_SICK_MESSAGE_TIMEOUT ) throw( SickIOException, SickTimeoutException ); /** Split message by space symbol*/ void _SplitReceivedMessage(SickNav350Message recv_message); /** Parse data gotten by GetScanData*/ void _ParseScanData(); void _ParseScanDataLandMark(); void _ParseScanDataNavigation(); /**Convert Hex to number*/ int _ConvertHexToDec(std::string num); }; } //namespace SickToolbox #endif /* SICK_NAV350_HH */
37,188
11,126
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Electronic Arts Inc. All rights reserved. /////////////////////////////////////////////////////////////////////////////// #include "TestThread.h" #include <EATest/EATest.h> #include <eathread/eathread_thread.h> #include <eathread/eathread_rwsemalock.h> #include <stdlib.h> const int kThreadCount = EATHREAD_MAX_CONCURRENT_THREAD_COUNT; /////////////////////////////////////////////////////////////////////////////// // RWSTestType // enum RWSTestType { kRWSTestTypeStandard, kRWSTestTypeAllWriters, kRWSTestTypeAllReaders, kRWSTestTypeMostlyWriters, kRWSTestTypeMostlyReaders, kRWSTestTypeCount }; /////////////////////////////////////////////////////////////////////////////// // RWSemaWorkData // struct RWSemaWorkData { volatile bool mbShouldQuit; EA::Thread::RWSemaLock mRWSemaLock; volatile int mnWriterCount; EA::Thread::AtomicInt32 mnErrorCount; EA::Thread::AtomicInt32 mnCurrentTestType; RWSemaWorkData() : mbShouldQuit(false) , mRWSemaLock() , mnWriterCount(0) , mnErrorCount(0) , mnCurrentTestType(kRWSTestTypeStandard) {} private: RWSemaWorkData(const RWSemaWorkData& rhs); RWSemaWorkData& operator=(const RWSemaWorkData& rhs); }; /////////////////////////////////////////////////////////////////////////////// // RWSThreadFunction // static intptr_t RWSThreadFunction(void* pvWorkData) { using namespace EA::Thread; RWSemaWorkData* const pWorkData = (RWSemaWorkData*)pvWorkData; ThreadId threadId = GetThreadId(); EA::UnitTest::ReportVerbosity(1, "RWSemaLock test function created: %s\n", EAThreadThreadIdToString(threadId)); int nErrorCount = 0; while(!pWorkData->mbShouldQuit) { int nWriteLockChance = 0; const RWSTestType testType = (RWSTestType)pWorkData->mnCurrentTestType.GetValue(); switch (testType) { default: case kRWSTestTypeStandard: nWriteLockChance = 20; break; case kRWSTestTypeAllWriters: nWriteLockChance = 1000; break; case kRWSTestTypeAllReaders: nWriteLockChance = 0; break; case kRWSTestTypeMostlyWriters: nWriteLockChance = 700; break; case kRWSTestTypeMostlyReaders: nWriteLockChance = 5; break; } const bool bShouldWrite = ((rand() % 1000) < nWriteLockChance); if(bShouldWrite) { AutoSemaWriteLock _(pWorkData->mRWSemaLock); pWorkData->mnWriterCount++; EA::UnitTest::ThreadSleepRandom(2, 10); pWorkData->mnWriterCount--; } else { AutoSemaReadLock _(pWorkData->mRWSemaLock); EATEST_VERIFY_MSG(pWorkData->mnWriterCount == 0, "ReadLock is held, there should be no active WriteLocks."); } } pWorkData->mnErrorCount.SetValue(nErrorCount); return nErrorCount; } // NOTE(rparolin): // This exists to introduce test-only functionality for the RWSemaLock. We can add these functions here because we // guarantee they will not be called in a concurrent context and they simplify validation of assumption of the lock. struct TestRWSemaLock : public EA::Thread::RWSemaLock { TestRWSemaLock() = default; TestRWSemaLock(const TestRWSemaLock&) = delete; TestRWSemaLock(TestRWSemaLock&&) = delete; TestRWSemaLock& operator=(const TestRWSemaLock&) = delete; TestRWSemaLock& operator=(TestRWSemaLock&&) = delete; bool IsReadLocked() { Status status; status.data = mStatus.GetValue(); return status.readers > 0; } bool IsWriteLocked() { Status status; status.data = mStatus.GetValue(); return status.writers > 0; } }; int TestThreadRWSemaLock() { using namespace EA::Thread; int nErrorCount = 0; { // RWSemaLock -- Basic single-threaded test. TestRWSemaLock rwSemaLock; // There are no construction parameters. EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); rwSemaLock.ReadTryLock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); rwSemaLock.ReadLock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.ReadUnlock(); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.ReadUnlock(); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); rwSemaLock.WriteTryLock(); EATEST_VERIFY_MSG(rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.ReadTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); } { // AutoRWSemaLock -- Basic single-threaded test. TestRWSemaLock rwSemaLock; // There are no construction parameters. { //Special scope just for the AutoRWSemaLock AutoSemaReadLock autoRWSemaLock1(rwSemaLock); AutoSemaReadLock autoRWSemaLock2(rwSemaLock); EATEST_VERIFY_MSG(rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.WriteTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); } EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); { //Special scope just for the AutoRWSemaLock AutoSemaWriteLock autoRWSemaLock(rwSemaLock); EATEST_VERIFY_MSG(rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.ReadTryLock(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); } EATEST_VERIFY_MSG(!rwSemaLock.IsReadLocked(), "RWSemaLock failure"); EATEST_VERIFY_MSG(!rwSemaLock.IsWriteLocked(), "RWSemaLock failure"); } #if EA_THREADS_AVAILABLE { // Multithreaded test RWSemaWorkData workData; Thread thread[kThreadCount]; ThreadId threadId[kThreadCount]; Thread::Status status; for(int i(0); i < kThreadCount; i++) threadId[i] = thread[i].Begin(RWSThreadFunction, &workData); for(int e = 0; e < kRWSTestTypeCount; e++) { workData.mnCurrentTestType.SetValue(e); EA::UnitTest::ThreadSleepRandom(gTestLengthSeconds * 500, gTestLengthSeconds * 500); } workData.mbShouldQuit = true; for(int t(0); t < kThreadCount; t++) { if(threadId[t] != kThreadIdInvalid) { status = thread[t].WaitForEnd(GetThreadTime() + 30000); EATEST_VERIFY_MSG(status != Thread::kStatusRunning, "RWSemalock/Thread failure: status == kStatusRunning.\n"); } } nErrorCount += (int)workData.mnErrorCount; } #endif return nErrorCount; }
7,087
2,866
/************************************************************************************//** // Copyright (c) 2006-2015 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file ****************************************************************************************/ #include "tootlepch.h" #include "jrtcommon.h" #include "jrtppmimage.h" /********************************************************/ /****** Implementation of Class JRTPPMJRTPPMImage *******************/ /********************************************************/ /*************************** * JRTPPMImage Constructor: * Sets the width and height of the image, in pixels * allocates memory for pixels. Each pixel is initialized to * 0,0,0 (black) ***************************/ JRTPPMImage::JRTPPMImage(int width, int height) { p_mlpPixels = NULL; p_miWidth = 0; p_miHeight = 0; AllocPixels(width, height); } JRTPPMImage::JRTPPMImage(const JRTPPMImage& img) { *this = img; } const JRTPPMImage& JRTPPMImage::operator =(const JRTPPMImage& img) { FreePixels(); this->p_miHeight = img.p_miHeight; this->p_miWidth = img.p_miWidth; this->p_mlpPixels = new PIXEL[ GetWidth() * GetHeight() ]; memcpy(this->p_mlpPixels, img.p_mlpPixels, sizeof(PIXEL)*GetWidth()*GetHeight()); return *this; } /*************************** * JRTPPMImage Destructor: * Frees all dynamic memory. ***************************/ JRTPPMImage::~JRTPPMImage() { FreePixels(); } double Round(double x) { double frac = x - floor(x); if (frac > 0.5) { return ceil(x); } else { return floor(x); } } void JRTPPMImage::SetPixel(int x, int y, float r, float g, float b) { if (x >= 0 && x < p_miWidth && y >= 0 && y < p_miHeight) { p_mlpPixels[y * p_miWidth + x].r = (unsigned char)Round(r * 255.0); p_mlpPixels[y * p_miWidth + x].g = (unsigned char)Round(g * 255.0); p_mlpPixels[y * p_miWidth + x].b = (unsigned char)Round(b * 255.0); } } /****************************** * SaveFile * Outputs the image to a PPM (P6) file * with the specified filename. Returns true if the * output was a success, false if not. *********************************/ bool JRTPPMImage::SaveFile(const char* sFile) { // binary write must be specified or this code blows up // on windows FILE* fp = fopen(sFile, "wb"); // sanity check if (fp == NULL) { return false; } // print PPM header stuff fprintf(fp, "P6\n%d %d\n%d\n", this->p_miWidth, this->p_miHeight, 255); // iterate across pixels and dump them to the file for (int row = 0; row < p_miHeight; row++) { for (int col = 0; col < p_miWidth; col++) { const PIXEL& pix = p_mlpPixels[(row * p_miWidth) + col]; fwrite(&pix, 3, 1, fp); } // repeat for next pixel } fclose(fp); return true; } /* Helper function for parsing the headers of PPM files */ void ISkipToToken(FILE* fp) { bool hit_token = false; while (!feof(fp) && !hit_token) { // skip to beginning of next token (width, height, or maxval) int c = fgetc(fp); if (c == '#') { // comment, skip ahead till next newline while (!feof(fp) && c != '\n' && c != '\f' && c != '\r') { c = fgetc(fp); } } else if (c == '\n' || c == '\f' || c == '\r' || c == '\t' || c == ' ') { // whitespace, skip it } else { hit_token = true; // we need that character we just read, so backtrack so we're pointed at it ungetc(c, fp); } } } bool JRTPPMImage::LoadFile(const char* filename) { // try and open the image file FILE* fp = fopen(filename, "rb"); if (fp == NULL) { return false; } /* For reference, here is the PPM image format description, direct from the ppm man page. A "magic number" for identifying the file type. A ppm file's magic number is the two characters "P3". Whitespace (blanks, TABs, CRs, LFs). A width, formatted as ASCII characters in decimal. Whitespace. A height, again in ASCII decimal. Whitespace. The maximum color-component value, again in ASCII decimal. Whitespace. Width * height pixels, each three ASCII decimal values between 0 and the specified maximum value, starting at the top-left corner of the pixmap, proceeding in normal English reading order. The three values for each pixel represent red, green, and blue, respectively; a value of 0 means that color is off, and the maximum value means that color is maxxed out. Characters from a "#" to the next end-of-line are ignored (comments). No line should be longer than 70 characters. The "magic number" is "P6" instead of "P3". The pixel values are stored as plain bytes, instead of ASCII decimal. Whitespace is not allowed in the pixels area, and only a single character of whitespace (typically a newline) is allowed after the maxval. */ // first two bytes had better be "P6" if (fgetc(fp) != 'P') { fclose(fp); return false; } if (fgetc(fp) != '6') { fclose(fp); return false; } UINT width = 0, height = 0, maxval = 0; // parse out the width, height, and maxval, ignoring whitespace and comments. bool at_bits = false, got_width = false, got_height = false, got_maxval = false; while (!at_bits && !feof(fp)) { ISkipToToken(fp); if (!got_width) { // read width if (fscanf(fp, "%d", &width) != 1) { fclose(fp); return false; } got_width = true; } else if (!got_height) { // read height if (fscanf(fp, "%d", &height) != 1) { fclose(fp); return false; } got_height = true; } else if (!got_maxval) { // read maxval if (fscanf(fp, "%d", &maxval) != 1) { fclose(fp); return false; } got_maxval = true; at_bits = true; } } // verify that we got all the header information we needed // if we're EOF, it means we did not if (feof(fp) && (!got_width || !got_height || !got_maxval)) { fclose(fp); return false; } // there are now 3*width*height bytes left in the file. // excluding the extraneous whitespace that may or may not be there // allocate enough space for the rest of the data unsigned char* bytes = (unsigned char*)malloc(3 * width * height); // store current file position long offs = ftell(fp); // read the data size_t bytes_read = fread(bytes, 1, 3 * width * height, fp); if (bytes_read < 3 * width * height) { // not enough bytes fclose(fp); free(bytes); return false; } else if (!feof(fp)) { // still more data in file, means that there was // extraneous whitespace before that needs to be skipped int extra_bytes = 0; while (!feof(fp)) { extra_bytes++; fgetc(fp); } extra_bytes--; // disregard EOF character fseek(fp, offs, SEEK_SET); for (int i = 0; i < extra_bytes; i++) { fgetc(fp); } bytes_read = fread(bytes, 1, 3 * width * height, fp); if (bytes_read != 3 * width * height) { // something is wrong fclose(fp); free(bytes); return false; } } // convert data to double and copy it AllocPixels(width, height); int i = 0; for (int y = 0; y < GetHeight(); y++) { for (int x = 0; x < GetWidth(); x++) { float r = bytes[i] / (float)maxval; float g = bytes[i + 1] / (float)maxval; float b = bytes[i + 2] / (float)maxval; i += 3; SetPixel(x, y, r, g, b); } } free(bytes); return true; } void JRTPPMImage::AllocPixels(int iWidth, int iHeight) { // prevent accidental memory leaks if (p_mlpPixels != NULL) { FreePixels(); } p_miWidth = iWidth; p_miHeight = iHeight; // and make new pixel memory p_mlpPixels = new PIXEL[p_miHeight * p_miWidth]; } void JRTPPMImage::FreePixels() { delete[] p_mlpPixels; p_mlpPixels = NULL; } PIXEL* JRTPPMImage::AccessPixel(int x, int y) { return &p_mlpPixels[ y * p_miWidth + x ]; }
8,693
2,875
#include "UnitTest++/Config.h" #ifndef UNITTEST_NO_DEFERRED_REPORTER #include "UnitTest++/UnitTestPP.h" #include "UnitTest++/DeferredTestReporter.h" #include <cstring> namespace UnitTest { namespace { #ifndef UNITTEST_MEMORYOUTSTREAM_IS_STD_OSTRINGSTREAM MemoryOutStream& operator <<(MemoryOutStream& lhs, const std::string& rhs) { lhs << rhs.c_str(); return lhs; } #endif struct MockDeferredTestReporter : public DeferredTestReporter { virtual void ReportSummary(int, int, int, float) { } }; struct DeferredTestReporterFixture { DeferredTestReporterFixture() : testName("UniqueTestName") , testSuite("UniqueTestSuite") , fileName("filename.h") , lineNumber(12) , details(testName.c_str(), testSuite.c_str(), fileName.c_str(), lineNumber) { } MockDeferredTestReporter reporter; std::string const testName; std::string const testSuite; std::string const fileName; int const lineNumber; TestDetails const details; }; TEST_FIXTURE(DeferredTestReporterFixture, ReportTestStartCreatesANewDeferredTest) { reporter.ReportTestStart(details); CHECK_EQUAL(1, (int)reporter.GetResults().size()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportTestStartCapturesTestNameAndSuite) { reporter.ReportTestStart(details); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_EQUAL(testName.c_str(), result.testName.c_str()); CHECK_EQUAL(testSuite.c_str(), result.suiteName.c_str()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportTestEndCapturesTestTime) { float const elapsed = 123.45f; reporter.ReportTestStart(details); reporter.ReportTestFinish(details, elapsed); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_CLOSE(elapsed, result.timeElapsed, 0.0001f); } TEST_FIXTURE(DeferredTestReporterFixture, ReportFailureSavesFailureDetails) { char const* failure = "failure"; reporter.ReportTestStart(details); reporter.ReportFailure(details, failure); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK(result.failed == true); CHECK_EQUAL(fileName.c_str(), result.failureFile.c_str()); } TEST_FIXTURE(DeferredTestReporterFixture, ReportFailureSavesFailureDetailsForMultipleFailures) { char const* failure1 = "failure 1"; char const* failure2 = "failure 2"; reporter.ReportTestStart(details); reporter.ReportFailure(details, failure1); reporter.ReportFailure(details, failure2); DeferredTestResult const& result = reporter.GetResults().at(0); CHECK_EQUAL(2, (int)result.failures.size()); CHECK_EQUAL(failure1, result.failures[0].failureStr); CHECK_EQUAL(failure2, result.failures[1].failureStr); } TEST_FIXTURE(DeferredTestReporterFixture, DeferredTestReporterTakesCopyOfFailureMessage) { reporter.ReportTestStart(details); char failureMessage[128]; char const* goodStr = "Real failure message"; char const* badStr = "Bogus failure message"; using namespace std; strcpy(failureMessage, goodStr); reporter.ReportFailure(details, failureMessage); strcpy(failureMessage, badStr); DeferredTestResult const& result = reporter.GetResults().at(0); DeferredTestFailure const& failure = result.failures.at(0); CHECK_EQUAL(goodStr, failure.failureStr); } }} #endif
3,371
1,146
/** * @file inter_code_generator.h * @brief 中间代码生成器类具体实现 */ #include "../include/inter_code_generator.h" #define POS(cur) cur->line_number, cur->pos map<string, VARIABLE_INFO_ENUM> Info::VAR_INFO_MAP = { {"double", VARIABLE_INFO_ENUM::DOUBLE}, {"float", VARIABLE_INFO_ENUM::DOUBLE}, {"int", VARIABLE_INFO_ENUM::INT}, {"void", VARIABLE_INFO_ENUM::VOID}, }; /** * @brief VarInfo构造函数 */ VarInfo::VarInfo() = default; /** * @brief VarInfo构造函数 * @param _name 变量名字 * @param _type 种类 */ VarInfo::VarInfo(VARIABLE_INFO_ENUM _type, int _place) { name = "v" + int2string(_place); place = _place; type = _type; } FuncInfo::FuncInfo() = default; FuncInfo::FuncInfo(string _name, VARIABLE_INFO_ENUM _ret_type, int _start_place, int _end_place) { name = move(_name); ret_type = _ret_type; start_place = _start_place; end_place = _end_place; } /** * @brief 中间代码生成器构造函数 */ InterCodeGenerator::InterCodeGenerator() = default; /** * @brief 中间代码生成 * @param _tree SyntaxTree * */ void InterCodeGenerator::analyze(SyntaxTree * _tree, bool verbose) { inter_code.clear(); var_index = 0; temp_var_index = 0; context_index = 0; func_backpatch.clear(); tree = _tree; try { _analyze(tree -> root -> first_son); } catch (Error & e) { cout << "Semantic analyze errors :" << endl; cout << e; exit(0); } if (verbose) { int l = inter_code.size(); cout << "Generated " << l << " inter codes" << endl; for (int i = 0; i < l; i ++) { cout << "#" << setw(3) << setfill(' ') << std::left << i; cout << inter_code[i]; } } } void InterCodeGenerator::_analyze(SyntaxTreeNode * cur) { SyntaxTreeNode * name_tree, * main_block; vector<SyntaxTreeNode *> funcs; string name, type; while (cur) { temp_var_index = 0; if (cur -> value == "FunctionStatement") { name_tree = cur -> first_son -> right; name = name_tree -> first_son -> value; if (name == "main") main_block = name_tree -> right -> right; else { type = cur -> first_son -> value; func_table[name] = FuncInfo(name, Info::VAR_INFO_MAP[type], 0, 0); funcs.emplace_back(cur); } } else if (cur -> value == "Statement") { _statement(cur); } else throw Error("`" + cur -> value + "` is not allowed in a root of a class", POS(cur)); cur = cur -> right; } // main 函数直接执行 _block(main_block, false); int main_end = inter_code.size(); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); // 翻译别的函数 for (auto func: funcs) _functionStatement(func); // main 结束就直接结束 inter_code[main_end].res = int2string(inter_code.size()); for (auto it: func_backpatch) if (! it.second.empty()) { string dest = int2string(func_table[it.first].start_place); for (auto i: it.second) inter_code[i].res = dest; } } void InterCodeGenerator::_functionStatement(SyntaxTreeNode * cur) { SyntaxTreeNode * name_tree, * param_tree, * block_tree, * type_tree; type_tree = cur -> first_son; name_tree = type_tree -> right; param_tree = name_tree -> right; block_tree = param_tree -> right; string func_name = name_tree -> first_son -> value; int func_start = int(inter_code.size()); // start SyntaxTreeNode * ps = param_tree -> first_son; while (ps) { _statement(ps); _emit(INTER_CODE_OP_ENUM::POP, "", "", table[ps -> first_son -> value].name); ps = ps -> right; } _block(block_tree); string temp_place = "t" + int2string(temp_var_index ++); // 自动return _emit(INTER_CODE_OP_ENUM::POP, "", "", temp_place); _emit(INTER_CODE_OP_ENUM::J, "", "", temp_place); // end int func_end = inter_code.size() - 1; func_table[func_name] = FuncInfo(name_tree -> first_son -> value, Info::VAR_INFO_MAP[type_tree -> first_son -> value], func_start, func_end); } /** * @brief 翻译block */ void InterCodeGenerator::_block(SyntaxTreeNode * cur, bool restore) { int _pre_var_index = var_index; map<string, VarInfo> pre_table = table; context_index ++; SyntaxTreeNode * cs = cur -> first_son; cur -> next_list = cs -> next_list; while (cs) { if (cs -> value == "Statement") _statement(cs); else if (cs -> value == "Assignment") _assignment(cs); else if (cs -> value == "Print") _print(cs); else if (cs -> value == "Control-If") _if(cs); else if (cs -> value == "Control-While") _while(cs); else if (cs -> value == "Block") { _block(cs); cur -> next_list = cs -> next_list; } else if (cs -> value == "FunctionCall") _functionCall(cs); else if (cs -> value == "VoidReturn") _voidReturn(cs); // TODO 其他 else cout << "Debug <<<" << cs -> value << endl; // 回填 _backpatch(cs -> next_list, inter_code.size()); cs = cs -> right; // 回填 if (cs) cur -> next_list = cs -> next_list; } if (restore) { var_index = _pre_var_index; table = pre_table; } } /** * @brief 翻译Print */ void InterCodeGenerator::_if(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son, * pre = nullptr; int m1_inst, m2_inst; while (cs) { if (cs -> value == "Control-Condition") { // 读取条件语句 _expression(cs -> first_son); pre = cs -> first_son; // 回填一下 m1_inst = inter_code.size(); // 读取紧随其后的执行语句 cs = cs -> right; _block(cs); // 只有if if (! cs -> right) { _backpatch(pre -> true_list, m1_inst); cur -> next_list.insert(cur -> next_list.end(), V(cs -> left -> first_son -> false_list)); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } else { cur -> next_list.emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } } else { // 回填一下 m2_inst = inter_code.size(); _block(cs); _backpatch(pre -> true_list, m1_inst); _backpatch(pre -> false_list, m2_inst); cur -> next_list.insert(cur -> next_list.end(), V(cs -> next_list)); } cs = cs -> right; } } /** * @brief 翻译Print */ void InterCodeGenerator::_print(SyntaxTreeNode * cur) { SyntaxTreeNode * ps = cur -> first_son; string print_place; while (ps) { print_place = _expression(ps); _emit(INTER_CODE_OP_ENUM::PRINT, print_place, "", ""); ps = ps -> right; } _emit(INTER_CODE_OP_ENUM::PRINT, "", "", ""); } /** * @brief 翻译赋值语句 */ void InterCodeGenerator::_assignment(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son; string r_value_place = _expression(cs -> right); string store_place; if (cs -> value == "Expression-ArrayItem") store_place = _lookUpVar(cs); else store_place = _lookUpVar(cur -> first_son -> value, cur); _emit(INTER_CODE_OP_ENUM::MOV, r_value_place, "", store_place); } /** * @brief 翻译表达式 * @param cur 一个Expression-*节点执政 * @return place, string */ string InterCodeGenerator::_expression(SyntaxTreeNode * cur) { // 双目运算符 if (cur -> value == "Expression-DoubleOp" || cur -> value == "Expression-Bool-DoubleOp") { SyntaxTreeNode * a = cur -> first_son; SyntaxTreeNode * op = a -> right; SyntaxTreeNode * b = op -> right; string a_place, b_place; // 如果是数字运算的话 if (cur -> value == "Expression-DoubleOp") { a_place = _expression(a); b_place = _expression(b); string temp_var_place = "t" + int2string(temp_var_index ++); _emit(Quadruple::INTER_CODE_MAP[op -> first_son -> value], a_place, b_place, temp_var_place); return temp_var_place; } // bool运算要考虑回填 else { string a_place, b_place; if (op -> first_son -> value == "||") { a_place = _expression(a); int m_inst = inter_code.size(); b_place = _expression(b); _backpatch(a -> false_list, m_inst); // update true_list cur -> true_list.insert(cur -> true_list.end(), V(a -> true_list)); cur -> true_list.insert(cur -> true_list.end(), V(b -> true_list)); // update false_list cur -> false_list = b -> false_list; } else if (op -> first_son -> value == "&&") { a_place = _expression(a); int m_inst = inter_code.size(); b_place = _expression(b); _backpatch(a -> true_list, m_inst); // update true_list cur -> true_list = b -> true_list; // update false_list cur -> false_list.insert(cur -> false_list.end(), a -> false_list.begin(), a -> false_list.end()); cur -> false_list.insert(cur -> false_list.end(), b -> false_list.begin(), b -> false_list.end()); } else { a_place = _expression(a); b_place = _expression(b); cur -> true_list.emplace_back(inter_code.size()); _emit(Quadruple::INTER_CODE_MAP[op -> first_son -> value], a_place, b_place, ""); cur -> false_list.emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); } return ""; } } // 单目运算符 else if (cur -> value == "Expression-UniOp") { // TODO } else if (cur -> value == "Expression-Bool-UniOp") { // TODO } // 常量 else if (cur -> value == "Expression-Constant"){ return cur -> first_son -> value; } // 字符串常量 else if (cur -> value == "Expression-String") { string temp = cur -> first_son -> value; // 转义 temp = regex_replace(temp, regex(","), string("\\,")); temp = regex_replace(temp, regex("\\\\"), string("\\\\")); return temp; } // 变量 else if (cur -> value == "Expression-Variable") { return _lookUpVar(cur -> first_son -> value, cur); } // 数组项 else if (cur -> value == "Expression-ArrayItem") { return _lookUpVar(cur); } cout << "debug >> " << cur -> value << endl; throw Error("How can you step into this place???", POS(cur)); } /** * @brief 翻译while语句 */ void InterCodeGenerator::_while(SyntaxTreeNode * cur) { int m_inst1 = inter_code.size(); SyntaxTreeNode * condition_tree = cur -> first_son -> first_son; _expression(condition_tree); int m_inst2 = inter_code.size(); SyntaxTreeNode * block_tree = cur -> first_son -> right; _block(block_tree); _backpatch(block_tree -> next_list, m_inst1); _backpatch(condition_tree -> true_list, m_inst2); cur -> next_list = condition_tree -> false_list; _emit(INTER_CODE_OP_ENUM::J, "", "", int2string(m_inst1)); } /** * @brief 翻译变量声明语句 */ void InterCodeGenerator::_statement(SyntaxTreeNode * cur) { SyntaxTreeNode * cs = cur -> first_son; while (cs) { string type = cs -> type; if (type == "double" || type == "float") { VarInfo info(VARIABLE_INFO_ENUM::DOUBLE, var_index ++); table[cs -> value] = info; } else if (type == "int") { VarInfo info(VARIABLE_INFO_ENUM::INT, var_index ++); table[cs -> value] = info; } else if (type.size() > 6 && type.substr(0, 6) == "array-") { VarInfo info(VARIABLE_INFO_ENUM::ARRAY, var_index ++); table[cs -> value] = info; string extra_info = cs -> extra_info; int extra_info_len = extra_info.size(); int cur_i = 0; if (cur_i < extra_info_len && extra_info.substr(cur_i, 5) == "size=") { cur_i += 5; int len = 0; while (cur_i + len < extra_info_len && extra_info[cur_i + len] != '&') len ++; var_index += string2int(extra_info.substr(cur_i, len)); cur_i += len; } if (cur_i < extra_info_len && extra_info.substr(cur_i, 3) == "&v=") { cur_i += 3; int len, arr_i = 0; while (cur_i < extra_info_len) { len = 0; while (cur_i + len < extra_info_len && extra_info[cur_i + len] != ',') len ++; _emit(INTER_CODE_OP_ENUM::MOV, extra_info.substr(cur_i, len), "", info.name + "[" + int2string(arr_i) + "]"); cur_i += len + 1; arr_i ++; } } } else { throw Error("type `" + type + "` are not supported yet", POS(cur)); } cs = cs -> right; } } /** * @brief 处理函数调用 */ void InterCodeGenerator::_functionCall(SyntaxTreeNode * cur) { // backup int _pre_var_index = var_index; map<string, VarInfo> pre_table = table; string func_name = cur -> first_son -> first_son -> value; if (func_table.find(func_name) == func_table.end()) throw Error("function `" + func_name + "` is not defined before use", POS(cur)); // TODO 返回地址 int temp_place = inter_code.size(); _emit(INTER_CODE_OP_ENUM::PUSH, "", "", ""); SyntaxTreeNode * param = cur -> first_son -> right; SyntaxTreeNode * ps = param -> first_son; while (ps -> right) ps = ps -> right; string param_place; while (ps) { param_place = _expression(ps -> first_son); _emit(INTER_CODE_OP_ENUM::PUSH, "", "", param_place); ps = ps -> left; } inter_code[temp_place].res = "pc+" + int2string(inter_code.size() - temp_place + 1); if (func_backpatch.find(func_name) == func_backpatch.end()) { vector<int> t; func_backpatch[func_name] = t; } func_backpatch[func_name].emplace_back(inter_code.size()); _emit(INTER_CODE_OP_ENUM::J, "", "", ""); // restore var_index = _pre_var_index; table = pre_table; } /** * @brief 寻找标识符 * @param name 标识符 * @return code var */ string InterCodeGenerator::_lookUpVar(string name, SyntaxTreeNode * cur) { if (table.find(name) == table.end()) throw Error("variable `" + name + "` is not defined before use", POS(cur)); return table[name].name; } /** * @brief 寻找标识符 * @param name 标识符 * @return code var */ string InterCodeGenerator::_lookUpVar(SyntaxTreeNode * arr_pointer) { string base = arr_pointer -> first_son -> value; string index_place = _expression(arr_pointer -> first_son -> right -> first_son); return _lookUpVar(base, arr_pointer) + "[" + index_place + "]"; } /** * @brief 生成一个四元式 * @param op 操作符 * @param arg1 参数1 * @param arg2 参数2 * @param res 结果 */ void InterCodeGenerator::_emit(INTER_CODE_OP_ENUM op, string arg1, string arg2, string res) { inter_code.emplace_back(Quadruple(op, move(arg1), move(arg2), move(res))); } /** * @brief 保存到文件 * @param 路径 */ void InterCodeGenerator::saveToFile(string path) { ofstream out_file; out_file.open(path, ofstream::out | ofstream::trunc); for (auto ic: inter_code) out_file << Quadruple::INTER_CODE_OP[int(ic.op)] << "," << ic.arg1 << "," << ic.arg2 << "," << ic.res << endl; out_file.close(); } void InterCodeGenerator::_backpatch(vector<int> v, int dest_index) { for (auto i: v) inter_code[i].res = int2string(dest_index); } void InterCodeGenerator::_voidReturn(SyntaxTreeNode * cur) { SyntaxTreeNode * cf = cur; while (cf && cf -> value != "FunctionStatement") cf = cf -> father; string temp_place = "t" + int2string(temp_var_index ++); // 自动return _emit(INTER_CODE_OP_ENUM::POP, "", "", temp_place); _emit(INTER_CODE_OP_ENUM::J, "", "", temp_place); }
16,722
5,754
/** * TimerThread class definition * * @file TimerThread.hxx */ #ifndef TIMERTHREAD_HXX #define TIMERTHREAD_HXX /* Includes -------------------------------------------- */ #include <functional> #include <chrono> #include <unordered_map> #include <set> #include <thread> #include <mutex> #include <condition_variable> #include <cstdint> /* TimerThread class definition ------------------------ */ class TimerThread { public: /* Defining the timer ID type */ using timer_id_t = std::uint64_t; /* Each Timer is assigned a unique ID of type timer_id_t */ static timer_id_t constexpr no_timer = timer_id_t(0); /* Valid IDs are guaranteed not to be this value */ /* Defining the handler function type */ using handler_type = std::function<void()>; // Function object we actually use // Function object that we boil down to handler_type with std::bind template<typename ... Args> using bound_handler_type = std::function<void(Args ...)>; /* Defining the microsecond type */ using time_us_t = std::int64_t; /* Values that are a large-range microsecond count */ /** @brief Constructor does not start worker until there is a Timer */ explicit TimerThread(); /** @brief Destructor is thread safe, even if a timer * callback is running. All callbacks are guaranteed * to have returned before this destructor returns */ ~TimerThread(); /** @brief Create timer using microseconds * The delay will be called msDelay microseconds from now * If msPeriod is nonzero, call the callback again every * msPeriod microseconds * All timer creation functions eventually call this one */ timer_id_t addTimer(time_us_t msDelay, time_us_t msPeriod, handler_type handler); /** @brief Create timer using std::chrono delay and period * Optionally binds additional arguments to the callback */ template<typename SRep, typename SPer, typename PRep, typename PPer, typename ... Args> timer_id_t addTimer(typename std::chrono::duration<SRep, SPer> const &delay, typename std::chrono::duration<PRep, PPer> const &period, bound_handler_type<Args ...> handler, Args && ... args); /** @brief Create timer using millisecond units delay and period * Optionally binds additional arguments to the callback */ template<typename ... Args> timer_id_t addTimer(time_us_t msDelay, time_us_t msPeriod, bound_handler_type<Args ...> handler, Args && ... args); /** @brief setInterval API like browser javascript * Call handler every `period` milliseconds, * starting `period` milliseconds from now * Optionally binds additional arguments to the callback */ timer_id_t setInterval(handler_type handler, time_us_t period); /** @brief setTimeout API like browser javascript * Call handler once `timeout` ms from now */ timer_id_t setTimeout(handler_type handler, time_us_t timeout); /** @brief setInterval API like browser javascript * Call handler every `period` microseconds, * starting `period` microseconds from now */ template<typename ... Args> timer_id_t setInterval(bound_handler_type<Args ...> handler, time_us_t period, Args && ... args); /** @brief setTimeout API like browser javascript * Call handler once `timeout` ms from now * binds extra arguments and passes them to the * timer callback */ template<typename ... Args> timer_id_t setTimeout(bound_handler_type<Args ...> handler, time_us_t timeout, Args && ... args); /** @brief Destroy the specified timer * * Synchronizes with the worker thread if the * callback for this timer is running, which * guarantees that the handler for that callback * is not running before clearTimer returns * * You are not required to clear any timers. You can * forget their timer_id_t if you do not need to cancel * them. * * The only time you need this is when you want to * stop a timer that has a repetition period, or * you want to cancel a timeout that has not fired * yet * * See clear() to wipe out all timers in one go */ bool clearTimer(timer_id_t id); /* @brief Destroy all timers, but preserve id uniqueness * This carefully makes sure every timer is not * executing its callback before destructing it */ void clear(); /* @brief Set the TimerThread's priority */ int setScheduling(const int &pPolicy, const int &pPriority); /* @brief Get the TimerThread's priority */ int scheduling(int * const pPolicy, int * const pPriority) noexcept; /* Peek at current state */ std::size_t size() const noexcept; bool empty() const noexcept; /** @brief Returns initialized singleton */ static TimerThread &global(); private: /* Type definitions */ using Lock = std::mutex; using ScopedLock = std::unique_lock<Lock>; using ConditionVar = std::condition_variable; using Clock = std::chrono::high_resolution_clock; using Timestamp = std::chrono::time_point<Clock>; using Duration = std::chrono::microseconds; /* changed milliseconds to microseconds */ /** @brief Timer structure definition */ struct Timer { explicit Timer(timer_id_t id = 0U); Timer(Timer &&r) noexcept; Timer &operator=(Timer &&r) noexcept; Timer(timer_id_t id, Timestamp next, Duration period, handler_type handler) noexcept; // Never called Timer(Timer const &r) = delete; Timer &operator=(Timer const &r) = delete; timer_id_t id; Timestamp next; Duration period; handler_type handler; // You must be holding the 'sync' lock to assign waitCond std::unique_ptr<ConditionVar> waitCond; bool running; }; // Comparison functor to sort the timer "queue" by Timer::next struct NextActiveComparator { bool operator()(Timer const &a, Timer const &b) const noexcept { return a.next < b.next; } }; // Queue is a set of references to Timer objects, sorted by next using QueueValue = std::reference_wrapper<Timer>; using Queue = std::multiset<QueueValue, NextActiveComparator>; using TimerMap = std::unordered_map<timer_id_t, Timer>; void timerThreadWorker(); bool destroy_impl(ScopedLock &lock, TimerMap::iterator i, bool notify); // Inexhaustible source of unique IDs timer_id_t nextId; // The Timer objects are physically stored in this map TimerMap active; // The ordering queue holds references to items in `active` Queue queue; // One worker thread for an unlimited number of timers is acceptable // Lazily started when first timer is started // TODO: Implement auto-stopping the timer thread when it is idle for // a configurable period. mutable Lock sync; ConditionVar wakeUp; std::thread worker; bool done; }; /* Template implementation fo class methods */ template<typename SRep, typename SPer, typename PRep, typename PPer, typename ... Args> TimerThread::timer_id_t TimerThread::addTimer(typename std::chrono::duration<SRep, SPer> const &delay, typename std::chrono::duration<PRep, PPer> const &period, bound_handler_type<Args ...> handler, Args && ... args) { time_us_t msDelay = std::chrono::duration_cast<std::chrono::microseconds>(delay).count(); time_us_t msPeriod = std::chrono::duration_cast<std::chrono::microseconds>(period).count(); return addTimer(msDelay, msPeriod, std::move(handler), std::forward<Args>(args) ...); } template<typename ... Args> TimerThread::timer_id_t TimerThread::addTimer(time_us_t msDelay, time_us_t msPeriod, bound_handler_type<Args ...> handler, Args && ... args) { return addTimer(msDelay, msPeriod, std::bind(std::move(handler), std::forward<Args>(args) ...)); } // Javascript-like setInterval template<typename ... Args> TimerThread::timer_id_t TimerThread::setInterval(bound_handler_type<Args ...> handler, time_us_t period, Args && ... args) { return setInterval(std::bind(std::move(handler), std::forward<Args>(args) ...), period); } // Javascript-like setTimeout template<typename ... Args> TimerThread::timer_id_t TimerThread::setTimeout(bound_handler_type<Args ...> handler, time_us_t timeout, Args && ... args) { return setTimeout(std::bind(std::move(handler), std::forward<Args>(args) ...), timeout); } #endif /* TIMERTHREAD_HXX */
10,759
2,637
/* * Copyright (C) 2006-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /// \file parser/uparser.cc #include <fstream> #include <parser/uparser.hh> #include <parser/parser-impl.hh> namespace parser { /*----------. | UParser. | `----------*/ UParser::UParser(std::istream& input, const yy::location* loc) : pimpl_(0) , stream_(&input) , stream_delete_(false) , oneshot_(false) , loc_(loc) { pimpl_ = new ParserImpl(*stream_); } UParser::UParser(const std::string& code, const yy::location* loc) : pimpl_(0) , stream_(new std::stringstream(code)) , stream_delete_(true) , oneshot_(true) , loc_(loc) { pimpl_ = new ParserImpl(*stream_); } UParser::UParser(const libport::path& file) : pimpl_(0) , stream_(0) , stream_delete_(true) , oneshot_(true) , loc_file_(new libport::Symbol(file.to_string())) // FIXME: leaks. , loc_(&loc_file_) { std::ifstream* input = new std::ifstream(file.to_string().c_str()); if (!input->good()) throw 42; // FIXME stream_ = input; pimpl_ = new ParserImpl(*stream_); } UParser::UParser(const UParser& rhs) : pimpl_(new ParserImpl(*rhs.pimpl_)) { } UParser::~UParser() { if (stream_delete_) delete stream_; delete pimpl_; } void UParser::meta(bool b) { pimpl_->meta(b); } parse_result_type UParser::parse() { pimpl_->initial_token_set(oneshot_ ? ::yy::parser::token::TOK_MODE_EXPS : ::yy::parser::token::TOK_MODE_EXP); return pimpl_->parse(loc_); } void UParser::oneshot_set(bool v) { oneshot_ = v; } }
1,910
718
// This file has been generated by Py++. #ifndef BufferObject_hpp__pyplusplus_wrapper #define BufferObject_hpp__pyplusplus_wrapper void register_BufferObject_class(); #endif//BufferObject_hpp__pyplusplus_wrapper
215
66
#include <test/cpp/tensorexpr/test_base.h> #include <memory> #include <sstream> #include <stdexcept> #include <unordered_map> #include <test/cpp/tensorexpr/padded_buffer.h> #include <torch/csrc/jit/tensorexpr/analysis.h> #include <torch/csrc/jit/tensorexpr/bounds_inference.h> #include <torch/csrc/jit/tensorexpr/eval.h> #include <torch/csrc/jit/tensorexpr/ir.h> #include <torch/csrc/jit/tensorexpr/ir_printer.h> #include <torch/csrc/jit/tensorexpr/ir_simplifier.h> #include <torch/csrc/jit/tensorexpr/loopnest.h> #include <torch/csrc/jit/tensorexpr/tensor.h> #include <torch/csrc/jit/testing/file_check.h> namespace torch { namespace jit { using namespace torch::jit::tensorexpr; void testExprSimple01() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{16, "X"}, {5, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); For* x_outer; For* x_inner; For* x_tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithTail(loops[0], 2, &x_outer, &x_inner, &x_tail); For* x_2; For* x_1; For* x_tail_2; l.splitWithTail(x_outer, 2, &x_2, &x_1, &x_tail_2); } void testExprLower01() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{16, "x"}, {5, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; ASSERT_GT(oss.str().size(), 20); ASSERT_LT(oss.str().size(), 200); } void testExprSimple02() { KernelScope kernel_scope; auto func = [](const ExprHandle& x, const ExprHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }; Tensor* tensor = Compute("f", {{26, "x"}, {5, "y"}}, func); LoopNest l({tensor}); For* x_outer; For* x_inner; For* x_tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithTail(loops[0], 4, &x_outer, &x_inner, &x_tail); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; ASSERT_GT(oss.str().size(), 200); ASSERT_LT(oss.str().size(), 600); { // Compare to a reference loop structure structure. VarHandle x_outer("x_outer", kInt); VarHandle x_inner("x_inner", kInt); VarHandle y("y", kInt); VarHandle x_tail("x_tail", kInt); BufHandle f("f", {26, 5}, kFloat); ExprHandle x_1 = x_outer * 4 + x_inner; ExprHandle x_outer_end = (ExprHandle(26) - 0) / 4; For* stmt1 = For::make( x_outer, 0, x_outer_end, For::make( x_inner, 0, 4, For::make(y, 0, 5, Store::make(f, {x_1, y}, func(x_1, y), 1)))); ExprHandle x_2 = x_tail + x_outer_end * 4; For* stmt2 = For::make( x_tail, 0, (ExprHandle(26) - 0) % 4, For::make(y, 0, 5, Store::make(f, {x_2, y}, func(x_2, y), 1))); Stmt* stmt = Block::make({stmt1, stmt2}); std::ostringstream oss_ref; oss_ref << *stmt; ASSERT_EQ(oss.str(), oss_ref.str()); } { PaddedBuffer<float> f_v(26, 5, "f_v"); PaddedBuffer<float> f_ref(26, 5, "f_res"); stmt = FlattenIndexes(stmt); SimpleIREvaluator ir_eval(stmt, tensor); ir_eval(f_v); for (int x = 0; x < 26; x++) { for (int y = 0; y < 5; y++) { f_ref(x, y) = 1 + x * x + y * y; } } ExpectAllNear(f_v, f_ref, 1e-5); } } Block* getSimplifiedBody(const LoopNest& l) { Stmt* stmt = l.root_stmt(); Stmt* simplified = IRSimplifier::simplify(stmt); return dynamic_cast<Block*>(simplified); } void assertForRange(For* f, int expected_start, int expected_stop) { ASSERT_NE(f, nullptr); const IntImm* start = dynamic_cast<const IntImm*>(f->start()); ASSERT_NE(start, nullptr); ASSERT_EQ(start->value(), expected_start); const IntImm* stop = dynamic_cast<const IntImm*>(f->stop()); ASSERT_NE(stop, nullptr); ASSERT_EQ(stop->value(), expected_stop); } void assertForRanges( Block* body, const std::vector<std::pair<int, int>>& start_stops) { ASSERT_EQ(body->nstmts(), start_stops.size()); auto it = body->begin(); for (size_t i = 0; i < start_stops.size(); i++, it++) { For* loop = dynamic_cast<For*>(*it); assertForRange(loop, start_stops[i].first, start_stops[i].second); } } void testExprSliceHeadWithLoopOptions() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.setGPUBlockIndex(loops[0], LoopOptions::IDX_Y); l.sliceHead(loops[0], 2, &head, &tail); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 2}, {0, 8}}); ASSERT_TRUE(tail->loop_options().is_gpu_block_index()); ASSERT_EQ(tail->loop_options().gpu_block_index(), LoopOptions::IDX_Y); ASSERT_TRUE(head->loop_options().isDefault()); } void testExprSliceTailWithLoopOptions() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceTail(loops[0], 4, &head, &tail); For* tail_head; For* tail_tail; l.setGPUBlockIndex(tail, LoopOptions::IDX_Y); l.sliceTail(tail, 2, &tail_head, &tail_tail); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 6}, {0, 2}, {8, 10}}); ASSERT_TRUE(tail_head->loop_options().is_gpu_block_index()); ASSERT_EQ(tail_head->loop_options().gpu_block_index(), LoopOptions::IDX_Y); ASSERT_TRUE(head->loop_options().isDefault()); ASSERT_TRUE(tail_tail->loop_options().isDefault()); } void testExprSliceHeadWhenFactorEqualsSize() { // When factor equals the For loop's original size, keep using the original // For loop. KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceHead(loops[0], 10, &head, &tail); ASSERT_EQ(head, loops[0]); ASSERT_EQ(tail, nullptr); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 10}}); } void testExprSliceHeadWhenFactorLargerThanSize() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceHead(loops[0], 100, &head, &tail); ASSERT_EQ(head, loops[0]); ASSERT_EQ(tail, nullptr); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 10}}); } void testExprSliceHead() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceHead(loops[0], 4, &head, &tail); ASSERT_NE(head, nullptr); ASSERT_NE(head, loops[0]); ASSERT_NE(tail, nullptr); ASSERT_NE(tail, loops[0]); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 4}, {4, 10}}); } void testExprSliceHeadWithNonZeroStart() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); For* head; For* tail; l.sliceTail(loops[0], 4, &head, &tail); // head: [0, 6) // tail: [6, 10) For* tail_head; For* tail_tail; l.sliceHead(tail, 2, &tail_head, &tail_tail); // tail_head: [6, 8) // tail_tail: [8, 10) Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 6}, {6, 8}, {8, 10}}); } void testExprSliceTailWhenFactorEqualsSize() { // When factor equals the For loop's original size, keep using the original // For loop. KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceTail(loops[0], 10, &head, &tail); ASSERT_EQ(head, nullptr); ASSERT_EQ(tail, loops[0]); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 10}}); } void testExprSliceTailWhenFactorLargerThanSize() { // When factor equals the For loop's original size, keep using the original // For loop. KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceTail(loops[0], 100, &head, &tail); ASSERT_EQ(head, nullptr); ASSERT_EQ(tail, loops[0]); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 10}}); } void testExprSliceTail() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); For* head; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.sliceTail(loops[0], 4, &head, &tail); ASSERT_NE(head, nullptr); ASSERT_NE(head, loops[0]); ASSERT_NE(tail, nullptr); ASSERT_NE(tail, loops[0]); Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 6}, {6, 10}}); } void testExprSplitAndSlice() { // 0: splitWithTail // 1: sliceTail on inner loop // 2: sliceHead on outer loop KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{100, "x"}}, func); LoopNest l({tensor}); For* outer; For* inner; For* tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); // outer: [0, 4) // inner: [0, 21) // tail: [84, 100) l.splitWithTail(loops[0], 21, &outer, &inner, &tail); For* inner_head; For* inner_tail; l.sliceTail(inner, 2, &inner_head, &inner_tail); For* outer_head; For* outer_tail; l.sliceHead(outer, 2, &outer_head, &outer_tail); // for (int x_outer = 0; x_outer < 2; x_outer++) { // for (int x_inner = 0; x_inner < 19; x_inner++) { // f[21 * x_outer + x_inner] = 1.f + float(21 * x_outer + x_inner); // } // for (int x_inner = 19; x_inner < 21; x_inner++) { // f[21 * x_outer + x_inner] = 1.f + float(21 * x_outer + x_inner); // } // } // for (int x_outer = 2; x_outer < 4; x_outer++) { // for (int x_inner = 0; x_inner < 19; x_inner++) { // f[21 * x_outer + x_inner] = 1.f + float(21 * x_outer + x_inner); // } // for (int x_inner = 19; x_inner < 21; x_inner++) { // f[21 * x_outer + x_inner] = 1.f + float(21 * x_outer + x_inner); // } // } // for (int x_tail = 0; x_tail < 16; x_tail++) { // f[x_tail + 84] = 1.f + float(x_tail + 84); // } Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 2}, {2, 4}, {0, 16}}); auto biter = body->begin(); For* loop = dynamic_cast<For*>(*biter++); assertForRanges(loop->body(), {{0, 19}, {19, 21}}); loop = dynamic_cast<For*>(*biter); assertForRanges(loop->body(), {{0, 19}, {19, 21}}); } void testExprSliceAndNormalize() { // 0: sliceHead // 1: normalize tail KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{10, "x"}}, func); LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); For* head; For* tail; l.sliceHead(loops[0], 2, &head, &tail); // head: [0, 2) // tail: [2, 10) For* normalized_tail; LoopNest::normalize(tail, &normalized_tail); // normalized_tail: [0, 8) Block* body = getSimplifiedBody(l); assertForRanges(body, {{0, 2}, {0, 8}}); } template <typename T> T evalExpr(const ExprHandle& expr, const VarHandle& var, T value) { ExprEval<SimpleIREvaluator> eval(expr, {var}); return eval.value<T>(value); } void testExprSliceWithVariableDimension() { auto testWithDimension = [](int dimension, const std::vector<std::pair<int, int>>& expected_for_ranges) { KernelScope kernel_scope; VarHandle dim("dim", kInt); Tensor* tensor = Compute("f", {{dim, "x"}}, [](const ExprHandle& x) { return x; }); LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); For* head; For* tail; l.sliceHead(loops[0], 2, &head, &tail); For* tail_head; For* tail_tail; l.sliceTail(tail, 2, &tail_head, &tail_tail); Block* body = getSimplifiedBody(l); ASSERT_EQ(expected_for_ranges.size(), 3); auto it = body->begin(); for (auto& start_stop : expected_for_ranges) { For* loop = dynamic_cast<For*>(*it++); int start = evalExpr<int>(ExprHandle(loop->start()), dim, dimension); int stop = evalExpr<int>(ExprHandle(loop->stop()), dim, dimension); ASSERT_EQ(start, start_stop.first); ASSERT_EQ(stop, start_stop.second); } }; testWithDimension(1, {{0, 1}, {1, 1}, {1, 1}}); testWithDimension(2, {{0, 2}, {2, 2}, {2, 2}}); testWithDimension(3, {{0, 2}, {2, 2}, {2, 3}}); testWithDimension(4, {{0, 2}, {2, 2}, {2, 4}}); testWithDimension(5, {{0, 2}, {2, 3}, {3, 5}}); testWithDimension(10, {{0, 2}, {2, 8}, {8, 10}}); } void testExprSplitWithTail() { KernelScope kernel_scope; auto func = [](const ExprHandle& x) { return ExprHandle(1.0f) + cast<float>(x); }; Tensor* tensor = Compute("f", {{199, "x"}}, func); LoopNest l({tensor}); For* x_outer; For* x_inner; For* x_tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithTail(loops[0], 17, &x_outer, &x_inner, &x_tail); For* a; For* b; For* c; l.splitWithTail(x_outer, 7, &a, &b, &c); Stmt* stmt = l.root_stmt(); Stmt* simplified = IRSimplifier::simplify(stmt); Block* body = dynamic_cast<Block*>(simplified); ASSERT_EQ(body->nstmts(), 3); auto biter = body->begin(); // Verify that the split loops are ordered correctly. For* loop = dynamic_cast<For*>(*biter++); assertForRange(loop, 0, 7); loop = dynamic_cast<For*>(*biter++); assertForRange(loop, 0, 4); loop = dynamic_cast<For*>(*biter); assertForRange(loop, 0, 12); } void testExprSplitWithTailNone() { KernelScope kernel_scope; auto func = [](const ExprHandle& x, const ExprHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }; Tensor* tensor = Compute("f", {{24, "x"}, {5, "y"}}, func); LoopNest l({tensor}); For* x_outer; For* x_inner; For* x_tail; std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithTail(loops[0], 4, &x_outer, &x_inner, &x_tail); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; ASSERT_GT(oss.str().size(), 200); ASSERT_LT(oss.str().size(), 600); { // Compare to a reference loop structure structure. VarHandle x_outer("x_outer", kInt); VarHandle x_inner("x_inner", kInt); VarHandle y("y", kInt); VarHandle x_tail("x_tail", kInt); BufHandle f("f", {24, 5}, kFloat); ExprHandle x_1 = x_outer * 4 + x_inner; ExprHandle x_outer_end = (ExprHandle(24) - 0) / 4; Stmt* stmt = new Block({For::make( x_outer, 0, x_outer_end, For::make( x_inner, 0, 4, For::make(y, 0, 5, Store::make(f, {x_1, y}, func(x_1, y), 1))))}); std::ostringstream oss_ref; oss_ref << *stmt; ASSERT_EQ(oss.str(), oss_ref.str()); } { PaddedBuffer<float> f_v(24, 5, "f_v"); PaddedBuffer<float> f_ref(24, 5, "f_res"); SimpleIREvaluator ir_eval(stmt, tensor); ir_eval(f_v); for (int x = 0; x < 24; x++) { for (int y = 0; y < 5; y++) { f_ref(x, y) = 1 + x * x + y * y; } } ExpectAllNear(f_v, f_ref, 1e-5); } } void testExprSplitWithMask01() { KernelScope kernel_scope; const int M = 26; const int N = 5; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {M, N}); Tensor* tensor = Compute( "f", {{M, "m"}, {N, "n"}}, [&](const ExprHandle& m, const ExprHandle& n) { return a_buf.load(m, n) + b_buf.load(m, n) + 1.0f; }); For* n_outer; For* n_inner; LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); l.splitWithMask(loops[1], 4, &n_outer, &n_inner); Stmt* stmt = l.root_stmt(); PaddedBuffer<float> a_v(M, N, "a"); PaddedBuffer<float> b_v(M, N, "b"); PaddedBuffer<float> c_v(M, N, "c"); PaddedBuffer<float> c_ref(M, N, "c_ref"); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { a_v(m, n) = 2 * m; b_v(m, n) = 3 * n; c_ref(m, n) = a_v(m, n) + b_v(m, n) + 1.0f; } } SimpleIREvaluator(stmt, a_buf, b_buf, tensor)(a_v, b_v, c_v); ExpectAllNear(c_v, c_ref, 1e-5); } // Tests the case where we split a loop cleanly multiple times, we should not // insert any masks. void testExprSplitWithMaskRepeatedNoMask() { KernelScope kernel_scope; const int M = 64; Placeholder a_buf("a", kFloat, {M}); Placeholder b_buf("b", kFloat, {M}); Tensor* tensor = Compute("f", {{M, "m"}}, [&](const ExprHandle& m) { return a_buf.load(m) + b_buf.load(m) + 1.0f; }); LoopNest l({tensor}); std::vector<For*> loops = l.getLoopStmtsFor(tensor); For *outer, *mid, *inner; l.splitWithMask(loops[0], 4, &outer, &inner); l.splitWithMask(outer, 4, &outer, &mid); Stmt* stmt1 = IRSimplifier::simplify(l.root_stmt()); std::ostringstream oss; oss << *stmt1; // Two splits mean 3 loops, but should need no masks in this case. const std::string& verification_pattern = R"IR( # CHECK: for ( # CHECK-NOT: if ( # CHECK: for ( # CHECK-NOT: if ( # CHECK: for ( # CHECK-NOT: if ( # CHECK: f[)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } void testSplitWithTailWithLoopOptions() { KernelScope kernel_scope; const int M = 21; Placeholder a_buf("a", kFloat, {M}); Placeholder b_buf("b", kFloat, {M}); Tensor* tensor = Compute("f", {{M, "m"}}, [&](const ExprHandle& m) { return a_buf.load(m) + b_buf.load(m) + 1.0f; }); For *outer, *inner, *tail; LoopNest l({tensor}); auto loops = NodeFinder<For>::find(l.root_stmt()); ASSERT_GT(loops.size(), 0); l.setGPUBlockIndex(loops[0], LoopOptions::IDX_Y); l.splitWithTail(loops[0], 4, &outer, &inner, &tail); ASSERT_NE(outer, nullptr); ASSERT_NE(inner, nullptr); ASSERT_NE(tail, nullptr); // Outer loop carries loop axis bindings. ASSERT_TRUE(outer->loop_options().is_gpu_block_index()); ASSERT_EQ(outer->loop_options().gpu_block_index(), LoopOptions::IDX_Y); // Inner loop has none. ASSERT_TRUE(inner->loop_options().isDefault()); // Tail loop has none. ASSERT_TRUE(tail->loop_options().isDefault()); } void testSplitWithMaskWithLoopOptions() { KernelScope kernel_scope; const int M = 21; Placeholder a_buf("a", kFloat, {M}); Placeholder b_buf("b", kFloat, {M}); Tensor* tensor = Compute("f", {{M, "m"}}, [&](const ExprHandle& m) { return a_buf.load(m) + b_buf.load(m) + 1.0f; }); For *outer, *inner; LoopNest l({tensor}); auto loops = NodeFinder<For>::find(l.root_stmt()); l.setGPUBlockIndex(loops[0], LoopOptions::IDX_Y); l.splitWithMask(loops[0], 4, &outer, &inner); // Outer loop carries loop axis bindings. ASSERT_TRUE(outer->loop_options().is_gpu_block_index()); ASSERT_EQ(outer->loop_options().gpu_block_index(), LoopOptions::IDX_Y); // Inner loop has none. ASSERT_TRUE(inner->loop_options().isDefault()); } void testScheduleBroadcastAddBuffer() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Tensor* c = Compute( "broadcast_add", {{M, "m"}, {N, "n"}, {K, "k"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) + b_buf.load(n, k); }); LoopNest l({c}); Stmt* stmt = l.root_stmt(); PaddedBuffer<float> a_v(M, N, "a_v"); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { a_v(m, n) = 7 * m * n; } } a_v.Backup(); PaddedBuffer<float> b_v(N, K, "b_v"); for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { b_v(n, k) = 11 * n * k; } } b_v.Backup(); PaddedBuffer<float> c_v(M, N, K, "c_buf"); SimpleIREvaluator ir_eval(stmt, a_buf, b_buf, c); ir_eval(a_v, b_v, c_v); a_v.CheckBackup(); b_v.CheckBackup(); PaddedBuffer<float> c_ref(M, N, K, "c_ref"); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { c_ref(m, n, k) = 7 * m * n + 11 * n * k; } } } ExpectAllNear(c_v, c_ref, 1e-5); } void testScheduleFunctionCall01() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Tensor* c = Compute( "broadcast_add", {{M, "m"}, {N, "n"}, {K, "k"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) + b_buf.load(n, k); }); Tensor* d = Compute( "d", {{M, "m"}, {N, "n"}, {K, "k"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return c->call(m, n, k) + 1; }); LoopNest l({d}); l.prepareForCodegen(); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; ASSERT_GT(oss.str().size(), 100); PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); PaddedBuffer<float> c_v(M, N, K); PaddedBuffer<float> d_v(M, N, K); PaddedBuffer<float> d_ref(M, N, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < K; k++) { d_ref(i, j, k) = a_v(i, j) + b_v(j, k) + 1; } } } SimpleIREvaluator eval(stmt, a_buf, b_buf, d); eval(a_v, b_v, d_v); ExpectAllNear(d_v, d_ref, 1e-5); } void testScheduleInlineSimple() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Placeholder c_buf("c", kFloat, {M, N}); Placeholder d_buf("d", kFloat, {M, K}); Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return c_buf.load(m, n) * d_buf.load(m, k) + x->call(m, n, k); }); LoopNest l1({y}); LoopNest l2({y}); l2.computeInline(x->buf()); l1.prepareForCodegen(); l2.prepareForCodegen(); Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); Stmt* stmt2 = IRSimplifier::simplify(l2.root_stmt()); SimpleIREvaluator eval1(stmt1, a_buf, b_buf, c_buf, d_buf, y); SimpleIREvaluator eval2(stmt2, a_buf, b_buf, c_buf, d_buf, y); PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); PaddedBuffer<float> c_v(M, N); PaddedBuffer<float> d_v(M, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c_v(i, j) = i + j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < K; j++) { d_v(i, j) = i * j; } } PaddedBuffer<float> y_1(M, N, K); PaddedBuffer<float> y_2(M, N, K); eval1(a_v, b_v, c_v, d_v, y_1); eval2(a_v, b_v, c_v, d_v, y_2); ExpectAllNear(y_1, y_2, 1e-5); std::ostringstream oss1, oss2; oss1 << *stmt1; oss2 << *stmt2; ASSERT_GT(oss1.str().size(), oss2.str().size()); } static std::string remove_space(const std::string& str) { std::string str_new = str; str_new.erase( remove_if(str_new.begin(), str_new.end(), isspace), str_new.end()); return str_new; } void InlineFunc01Helper(const std::vector<std::string>& inline_order) { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Placeholder c_buf("c", kFloat, {M, N}); Placeholder d_buf("d", kFloat, {M, K}); Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return c_buf.load(m, n) * d_buf.load(m, k) + x->call(m, n, k); }); Tensor* z = Compute( "z", {{M, "m3"}, {N, "n3"}, {K, "k3"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m, n, k) + y->call(m, n, k); }); LoopNest l({z}); for (const std::string& order : inline_order) { if (order == "x") { l.computeInline(x->buf()); } else if (order == "y") { l.computeInline(y->buf()); } else { throw std::runtime_error("Invalid order: " + order); } } l.prepareForCodegen(); Stmt* stmt = l.root_stmt(); std::ostringstream oss; oss << *stmt; std::string str1 = remove_space(oss.str()); { PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); PaddedBuffer<float> c_v(M, N); PaddedBuffer<float> d_v(M, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c_v(i, j) = i + j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < K; j++) { d_v(i, j) = i * j; } } PaddedBuffer<float> z_v(M, N, K); PaddedBuffer<float> z_ref(M, N, K); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { z_ref(m, n, k) = a_v(m, n) * b_v(n, k) * 2 + c_v(m, n) * d_v(m, k); } } } SimpleIREvaluator eval(stmt, a_buf, b_buf, c_buf, d_buf, z); eval(a_v, b_v, c_v, d_v, z_v); ExpectAllNear(z_v, z_ref, 1e-5); } if (inline_order.size() == 2) { Tensor* z2 = Compute( "z", {{M, "m3"}, {N, "n3"}, {K, "k3"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k) + (c_buf.load(m, n) * d_buf.load(m, k) + a_buf.load(m, n) * b_buf.load(n, k)); }); LoopNest l2({z2}); l2.prepareForCodegen(); Stmt* stmt2 = l2.root_stmt(); std::ostringstream oss2; oss2 << *stmt2; std::string str2 = remove_space(oss2.str()); ASSERT_EQ(str1, str2); ASSERT_GT(str1.size(), 100); } } void testScheduleInlineFunc01() { InlineFunc01Helper({"x", "y"}); InlineFunc01Helper({"y", "x"}); InlineFunc01Helper({"x"}); InlineFunc01Helper({"y"}); InlineFunc01Helper({}); } // Make sure we cache random vars if we should. void testScheduleInlineRandom() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return Mod::make(Intrinsics::make(kRand, kInt), 5); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m, n, k) + x->call(m, n, k); }); LoopNest l1({y}); l1.computeInline(x->buf()); // would normally compare results but Rand isn't implemented in the // SimpleIREvaluator, even if we could seed it. Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); std::ostringstream oss; oss << *stmt1; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int m2 = 0; m2 < 4; m2++) # CHECK: for (int n2 = 0; n2 < 5; n2++) # CHECK: for (int k2 = 0; k2 < 6; k2++) # CHECK: int x = rand(); # CHECK: y[m2, n2, k2] = 2 * (x % 5);)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } // Make sure we don't cache random vars that are not being inlined. void testScheduleInlineRandomUnrelated() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return m * n * k; }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m, n, k) + Intrinsics::make(kRand, kInt) + Intrinsics::make(kRand, kInt); }); LoopNest l1({y}); l1.computeInline(x->buf()); // would normally compare results but Rand isn't implemented in the // SimpleIREvaluator, even if we could seed it. Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); std::ostringstream oss; oss << *stmt1; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int m2 = 0; m2 < 4; m2++) # CHECK: for (int n2 = 0; n2 < 5; n2++) # CHECK: for (int k2 = 0; k2 < 6; k2++) # CHECK: y[m2, n2, k2] = ((n2 * m2) * k2 + (rand())) + (rand());)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } // Make sure we generate the right number of random values == the dimensionality // of the production tensor. void testScheduleInlineRandomLowerDimensions() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Tensor* x = Compute("x", {{M, "m1"}}, [&](const VarHandle& m) { return Mod::make(Intrinsics::make(kRand, kInt), 5); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m) + x->call(m); }); LoopNest l1({y}); l1.computeInline(x->buf()); // would normally compare results but Rand isn't implemented in the // SimpleIREvaluator, even if we could seed it. Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); std::ostringstream oss; oss << *stmt1; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int m2 = 0; m2 < 4; m2++) # CHECK: int x = rand(); # CHECK: for (int n2 = 0; n2 < 5; n2++) # CHECK: for (int k2 = 0; k2 < 6; k2++) # CHECK: y[m2, n2, k2] = 2 * (x % 5);)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } // Make sure we don't screw up intrinsics thinking they're rand. void testScheduleInlineIntrinsics() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return Intrinsics::make(kSqrt, x->call(m, n, k)); }); PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } LoopNest l1({y}); LoopNest l2({y}); l2.computeInline(x->buf()); l1.prepareForCodegen(); l2.prepareForCodegen(); Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); Stmt* stmt2 = IRSimplifier::simplify(l2.root_stmt()); SimpleIREvaluator eval1(stmt1, a_buf, b_buf, y); SimpleIREvaluator eval2(stmt2, a_buf, b_buf, y); PaddedBuffer<float> y_1(M, N, K); PaddedBuffer<float> y_2(M, N, K); eval1(a_v, b_v, y_1); eval2(a_v, b_v, y_2); ExpectAllNear(y_1, y_2, 1e-5); std::ostringstream oss1, oss2; oss1 << *stmt1; oss2 << *stmt2; ASSERT_GT(oss1.str().size(), oss2.str().size()); } // Make sure we can handle rand and non-rand intrinsics. void testScheduleInlineRandWithIntrinsics() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return Intrinsics::make(kRand, kFloat); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return Intrinsics::make(kSqrt, x->call(m, n, k)); }); LoopNest l1({y}); l1.computeInline(x->buf()); Stmt* stmt1 = IRSimplifier::simplify(l1.root_stmt()); std::ostringstream oss; oss << *stmt1; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int m2 = 0; m2 < 4; m2++) # CHECK: for (int n2 = 0; n2 < 5; n2++) # CHECK: for (int k2 = 0; k2 < 6; k2++) # CHECK: float x = rand(); # CHECK: y[m2, n2, k2] = sqrt(x);)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } // Split a Compute then inline it into another compute. void testScheduleSplitAThenInline() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{2, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.splitWithMask(loops[0], 4, &i_outer, &i_inner); ASSERT_THROWS_WITH(l.computeInline(a->buf()), "compound indices"); } // Split a Compute then inline another Compute into it. void testScheduleSplitBThenInline() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); std::vector<For*> loops = l.getLoopStmtsFor(b); l.splitWithMask(loops[0], 3, &i_outer, &i_inner); l.computeInline(a->buf()); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(6, 0); SimpleIREvaluator eval(s, b); eval(output); for (int i = 0; i < 6; ++i) { ASSERT_EQ(output[i], (i + 8) * (i + 8)); } } // Split a Compute twice then inline it. void testScheduleSplitTwiceThenInline() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{2, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.splitWithMask(loops[0], 4, &i_outer, &i_inner); l.splitWithMask(i_inner, 2, &i_outer, &i_inner); ASSERT_THROWS_WITH(l.computeInline(a->buf()), "compound indices"); } // Inline a Compute, then split. void testScheduleInlineThenSplit() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); l.computeInline(a->buf()); std::vector<For*> loops = NodeFinder<For>::find(l.root_stmt()); l.splitWithMask(loops.back(), 3, &i_outer, &i_inner); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(6, 0); SimpleIREvaluator eval(s, b); eval(output); for (int i = 0; i < 6; ++i) { ASSERT_EQ(output[i], (i + 8) * (i + 8)); } } // Split a Compute, inline it, then split the result. void testScheduleSplitInlineThenSplit() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{16, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); auto loops = NodeFinder<For>::find(l.root_stmt()); l.splitWithMask(loops.back(), 2, &i_outer, &i_inner); l.computeInline(a->buf()); loops = NodeFinder<For>::find(l.root_stmt()); l.splitWithMask(loops.front(), 2, &i_outer, &i_inner); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(16, 0); SimpleIREvaluator eval(s, b); eval(output); for (int i = 0; i < 16; ++i) { ASSERT_EQ(output[i], (i + 8) * (i + 8)); } } // Oversplit a loop that is simplified out after inlining. void testScheduleSplitInlineSimplify() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return ExprHandle(4) * i - ExprHandle(2) * i; }); Tensor* b = Compute("b", {{2, "j"}}, [&](const VarHandle& j) { return a->call(j) - ExprHandle(1); }); LoopNest loop({b}); For* i_outer; For* i_inner; LoopNest l({b}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.splitWithMask(loops[0], 4, &i_outer, &i_inner); ASSERT_THROWS_WITH(l.computeInline(a->buf()), "compound indices"); } // Inline a Compute with two consumers. void testScheduleInlineThreeMixedOnce() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); Tensor* c = Compute( "c", {{4, "k"}, {3, "l"}}, [&](const VarHandle& k, const VarHandle& l) { return a->call(k) * b->call(l); }); LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.computeInline(a->buf()); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(4 * 3, 0); SimpleIREvaluator eval(s, c); eval(output); for (int k = 0; k < 4; ++k) { for (int l = 0; l < 3; ++l) { ASSERT_EQ(output[k * 3 + l], (k) * (k) * (l + 8) * (l + 8)); } } } // Inline Compute A into B, then inline B into C. void testScheduleInlineThreeMixedTwice() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); Tensor* c = Compute( "c", {{4, "k"}, {3, "l"}}, [&](const VarHandle& k, const VarHandle& l) { return a->call(k) * b->call(l); }); LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.computeInline(a->buf()); l.computeInline(b->buf()); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(4 * 3, 0); SimpleIREvaluator eval(s, c); eval(output); for (int k = 0; k < 4; ++k) { for (int l = 0; l < 3; ++l) { ASSERT_EQ(output[k * 3 + l], (k) * (k) * (l + 8) * (l + 8)); } } } // Inline a Compute that is both a producer and consumer. void testScheduleInlineThreeMixedInner() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); Tensor* c = Compute( "c", {{4, "k"}, {3, "l"}}, [&](const VarHandle& k, const VarHandle& l) { return a->call(k) * b->call(l); }); LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.computeInline(b->buf()); l.prepareForCodegen(); Stmt* s = IRSimplifier::simplify(l.root_stmt()); std::vector<int> output(4 * 3, 0); SimpleIREvaluator eval(s, c); eval(output); for (int k = 0; k < 4; ++k) { for (int l = 0; l < 3; ++l) { ASSERT_EQ(output[k * 3 + l], (k) * (k) * (l + 8) * (l + 8)); } } } // Split 3 Computes, then inline the first two into the last. void testScheduleInlineThreeMixedSplit() { KernelScope kernel_scope; Tensor* a = Compute("a", {{18, "i"}}, [&](const VarHandle& i) { return i * i; }); Tensor* b = Compute("b", {{6, "j"}}, [&](const VarHandle& j) { return a->call(j + ExprHandle(8)); }); Tensor* c = Compute( "c", {{4, "k"}, {3, "l"}}, [&](const VarHandle& k, const VarHandle& l) { return a->call(k) * b->call(l); }); For* i_outer; For* i_inner; LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(a); l.splitWithMask(loops[0], 4, &i_outer, &i_inner); loops = l.getLoopStmtsFor(b); l.splitWithMask(loops[0], 3, &i_outer, &i_inner); loops = l.getLoopStmtsFor(c); l.splitWithMask(loops[0], 2, &i_outer, &i_inner); ASSERT_THROWS_WITH(l.computeInline(a->buf()), "compound indices"); } void testScheduleFuserStyle() { KernelScope kernel_scope; const int kVectorSize = 8; const int kVectorCount = 128; const int kTotalSize = kVectorSize * kVectorCount; Placeholder a_buf(BufHandle("A", {ExprHandle(kTotalSize)}, kFloat)); Tensor* b = Compute( "f", {{kTotalSize, "i"}}, [&](const std::vector<VarHandle>& axes) { return a_buf.load(axes[0]) + 11.0f; }); Tensor* c = Compute( "g", {{kTotalSize, "i"}}, [&](const std::vector<VarHandle>& axes) { return b->call(axes[0]) + 1.0f; }); LoopNest l({b, c}); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::vector<float> a_data(kTotalSize, 7.0f); std::vector<float> b_data(kTotalSize, 0.0f); std::vector<float> c_data(kTotalSize, 0.0f); SimpleIREvaluator(s, a_buf, b, c)(a_data, b_data, c_data); for (int i = 0; i < kTotalSize; i++) { ASSERT_EQ(b_data[i], 18.0f); ASSERT_EQ(c_data[i], 19.0f); } } void testScheduleFuserThreeArg() { KernelScope kernel_scope; const int kVectorSize = 8; const int kVectorCount = 128; const int kTotalSize = kVectorSize * kVectorCount; Placeholder a(BufHandle("A", {ExprHandle(kTotalSize)}, kFloat)); Placeholder b(BufHandle("B", {ExprHandle(kTotalSize)}, kFloat)); Placeholder c(BufHandle("C", {ExprHandle(kTotalSize)}, kFloat)); Placeholder d(BufHandle("D", {ExprHandle(kTotalSize)}, kFloat)); Tensor* e = Compute("e", {{kTotalSize, "i"}}, [&](const VarHandle& i) { return a.load(i) + b.load(i); }); Tensor* f = Compute("f", {{kTotalSize, "i"}}, [&](const VarHandle& i) { return e->call(i) + c.load(i); }); Tensor* g = Compute("g", {{kTotalSize, "i"}}, [&](const VarHandle& i) { return f->call(i) + d.load(i); }); LoopNest l({g}); l.computeInline(l.getLoopBodyFor(e)); l.computeInline(l.getLoopBodyFor(f)); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::vector<float> a_data(kTotalSize, 1.0f); std::vector<float> b_data(kTotalSize, 2.0f); std::vector<float> c_data(kTotalSize, 3.0f); std::vector<float> d_data(kTotalSize, 4.0f); std::vector<float> g_data(kTotalSize, 0.0f); SimpleIREvaluator(s, a, b, c, d, g)(a_data, b_data, c_data, d_data, g_data); for (int i = 0; i < kTotalSize; i++) { ASSERT_EQ(g_data[i], 10.0f); } } void testScheduleDynamicShape2D() { KernelScope kernel_scope; auto testWithSize = [](int32_t M, int32_t N) { VarHandle m("m", kInt); VarHandle n("n", kInt); Placeholder a(BufHandle("a", {m, n}, kFloat)); Placeholder b(BufHandle("b", {m, n}, kFloat)); Tensor* c = Compute( "c", {{m, "m"}, {n, "n"}}, [&](const VarHandle& i, const VarHandle& j) { return a.load(i, j) + b.load(i, j); }); LoopNest l({c}); Stmt* s = l.root_stmt(); SimpleIREvaluator cg(s, {a, b, c, m, n}); std::vector<float> aData(M * N, 1.0f); std::vector<float> bData(M * N, 2.0f); std::vector<float> cData(M * N, 0.0f); cg.call({aData, bData, cData, M, N}); ExpectAllNear(cData, std::vector<float>(M * N, 3.0f), 1e-7); }; testWithSize(1, 8); testWithSize(16, 32); testWithSize(37, 11); } void testLoopNestComputeAt_1() { // Verify that compute_at works on the following example: // // for (int i_a = 0; i_a < N; i_a++) { // A[i_a] = i_a * i_a // } // for (int i_b = 0; i_b < N; i_b++) { // B[i_b] = A[i_b] // } // // After the transformation the i_b loop should have an allocation for a temp // buffer and that buffer should be used in computation of B. No use of A // should be in that loop after the transformation. Also, computation of A // should not be inlined into B. Instead, it should be computed into the temp, // and the temp should be used in B. KernelScope kernel_scope; VarHandle N("N", kInt); Tensor* A = Compute( "A", {{N, "i_a"}}, [&](const VarHandle& i_a) { return i_a * i_a; }); Tensor* B = Compute( "B", {{N, "i_b"}}, [&](const VarHandle& i_b) { return A->call(i_b); }); LoopNest l({B}); std::vector<For*> loops = l.getLoopStmtsFor(B); l.computeAt(l.getLoopBodyFor(A), loops[0]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; const std::string& verification_pattern = R"IR( # CHECK: for (int i_b = 0; i_b < N; i_b++) # CHECK: Allocate(temp, int, {1}) # CHECK: temp[ # CHECK-NOT: A[ # CHECK: B[i_b] = temp[0] # CHECK: Free(temp))IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> b_data(100, 0); SimpleIREvaluator cg(s, {B, N}); cg.call({b_data, 100}); std::vector<int> b_ref(100, 0); for (int i = 0; i < 100; i++) { b_ref[i] = i * i; } assertAllEqual(b_data, b_ref); } void testLoopNestComputeAt_2() { // Verify that compute_at works on the following example: // // for (int py = 0; py < H+1; py++) { // for (int px = 0; px < W+1; px++) { // p[py, px] = py*px // } // } // for (int cy = 0; cy < H; cy++) { // for (int cx = 0; cx < W; cx++) { // c[py, px] = p[cy,cx] + p[cy+1,cx] + // p[cy,cx+1] + p[cy+1,cx+1] // } // } KernelScope kernel_scope; const int kW = 16, kH = 16; VarHandle W("W", kInt); VarHandle H("H", kInt); Tensor* p = Compute( "prod", {{H + 1, "py"}, {W + 1, "px"}}, [&](const VarHandle& py, const VarHandle& px) { return px * py; }); Tensor* c = Compute( "cons", {{H, "cy"}, {W, "cx"}}, [&](const VarHandle& y, const VarHandle& x) { return p->call(y, x) + p->call(y + 1, x) + p->call(y, x + 1) + p->call(y + 1, x + 1); }); std::vector<int> c_ref(kW * kH, 0); for (int y = 0; y < kH; y++) { for (int x = 0; x < kW; x++) { c_ref[y * kW + x] = y * x + (y + 1) * x + y * (x + 1) + (y + 1) * (x + 1); } } { // First let's try to compute P at axis cy (the outer loop) LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(c); l.computeAt(l.getLoopBodyFor(p), loops[0]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int cy = 0; cy < H; cy++) # CHECK: Allocate(temp, int, {2, W + 1}) # CHECK: for # CHECK: for # CHECK: for (int cx = 0; cx < W; cx++) # CHECK-NOT: prod[ # CHECK: cons[ # CHECK: Free(temp))IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> c_data(kW * kH, 0); SimpleIREvaluator cg(s, {c, W, H}); cg.call({c_data, kW, kH}); assertAllEqual(c_data, c_ref); } { // Now let's try to compute P at axis cx (the inner loop) LoopNest l({c}); std::vector<For*> loops = l.getLoopStmtsFor(c); l.computeAt(l.getLoopBodyFor(p), loops[1]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int cy = 0; cy < H; cy++) # CHECK: for (int cx = 0; cx < W; cx++) # CHECK: Allocate(temp, int, {2, 2}) # CHECK: for # CHECK: for # CHECK-NOT: prod[ # CHECK: cons[ # CHECK: Free(temp))IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> c_data(kW * kH, 0); SimpleIREvaluator cg(s, {c, W, H}); cg.call({c_data, kW, kH}); assertAllEqual(c_data, c_ref); } } void testLoopNestComputeAt_3() { // Verify that compute_at works on the following example: // // A(x,y) = x*y // B(x,y) = A(x, y) // C(x,y) = B(x+1, y) // D(x,y) = A(x, y+1) + C(x, y) // // i.e. when 'A' comes to 'D' directly and indirectly through 'C'. KernelScope kernel_scope; const int kW = 16, kH = 16; VarHandle W("W", kInt); VarHandle H("H", kInt); Tensor* A = Compute( "A", {{H + 1, "ay"}, {W + 1, "ax"}}, [&](const VarHandle& ay, const VarHandle& ax) { return ax * ay; }); Tensor* B = Compute( "B", {{H + 1, "by"}, {W + 1, "bx"}}, [&](const VarHandle& by, const VarHandle& bx) { return A->call(by, bx); }); Tensor* C = Compute( "C", {{H, "cy"}, {W, "cx"}}, [&](const VarHandle& cy, const VarHandle& cx) { return B->call(cy, cx + 1); }); Tensor* D = Compute( "D", {{H, "dy"}, {W, "dx"}}, [&](const VarHandle& dy, const VarHandle& dx) { return A->call(dy + 1, dx) + C->call(dy, dx); }); std::vector<int> c_ref(kW * kH, 0); for (int y = 0; y < kH; y++) { for (int x = 0; x < kW; x++) { c_ref[y * kW + x] = (y + 1) * x + y * (x + 1); } } { // First let's try to compute A at axis dy (the outer loop) LoopNest l({D}); std::vector<For*> loops = l.getLoopStmtsFor(D); l.computeAt(l.getLoopBodyFor(A), loops[0]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int ay = 0; ay < H + 1; ay++) # CHECK: for (int ax = 0; ax < W + 1; ax++) # CHECK: A[ # CHECK: for (int by = 0; by < H + 1; by++) # CHECK: for (int bx = 0; bx < W + 1; bx++) # CHECK: B[ # CHECK: for (int cy = 0; cy < H; cy++) # CHECK: for (int cx = 0; cx < W; cx++) # CHECK: C[ # CHECK: for (int dy = 0; dy < H; dy++) # CHECK: Allocate(temp, int, {1, W}) # CHECK: for (int dx = 0; dx < W; dx++) # CHECK-NOT: A[)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> c_data(kW * kH, 0); SimpleIREvaluator cg(s, {D, W, H}); cg.call({c_data, kW, kH}); assertAllEqual(c_data, c_ref); } { // Now let's try to compute A at axis dx (the inner loop) LoopNest l({D}); std::vector<For*> loops = l.getLoopStmtsFor(D); l.computeAt(l.getLoopBodyFor(A), loops[1]); l.prepareForCodegen(); Stmt* s = l.root_stmt(); std::ostringstream oss; oss << *s; // Check the IR we produced const std::string& verification_pattern = R"IR( # CHECK: for (int ay = 0; ay < H + 1; ay++) # CHECK: for (int ax = 0; ax < W + 1; ax++) # CHECK: A[ # CHECK: for (int by = 0; by < H + 1; by++) # CHECK: for (int bx = 0; bx < W + 1; bx++) # CHECK: B[ # CHECK: for (int cy = 0; cy < H; cy++) # CHECK: for (int cx = 0; cx < W; cx++) # CHECK: C[ # CHECK: for (int dy = 0; dy < H; dy++) # CHECK: for (int dx = 0; dx < W; dx++) # CHECK: Allocate(temp, int, {1, 1}) # CHECK-NOT: A[)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); // Now check that the loop still produces the correct result. std::vector<int> c_data(kW * kH, 0); SimpleIREvaluator cg(s, {D, W, H}); cg.call({c_data, kW, kH}); assertAllEqual(c_data, c_ref); } } void testLoopNestComputeAt_4() { // TODO: Verify that computeAt works with reduction axis } class LoopOrderHelper : public IRVisitor { std::stringstream ordering; public: std::string getOrder(Stmt* s) { ordering.str(""); s->accept(this); return ordering.str(); } void visit(const For* v) { ordering << v->var()->name_hint() << ","; IRVisitor::visit(v); } }; void testLoopNestReorderAxis1() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{2, "x"}, {3, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); Stmt* stmt1 = Stmt::clone(l.root_stmt()); std::vector<int> stmt1_output(6, 0); SimpleIREvaluator cg(stmt1, {tensor}); cg.call({stmt1_output}); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[1]); Stmt* stmt2 = Stmt::clone(l.root_stmt()); ASSERT_NE(stmt1, stmt2); LoopOrderHelper loopOrderHelper; std::string order1 = loopOrderHelper.getOrder(stmt1); std::string order2 = loopOrderHelper.getOrder(stmt2); ASSERT_EQ(order1, "x,y,"); ASSERT_EQ(order2, "y,x,"); std::vector<int> stmt2_output(6, 0); SimpleIREvaluator cg2(stmt2, {tensor}); cg.call({stmt2_output}); for (int i = 0; i < 6; ++i) { ASSERT_EQ(stmt1_output[i], stmt2_output[i]); } // Reorder them back. loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[1]); Stmt* stmt3 = l.root_stmt(); std::string order3 = loopOrderHelper.getOrder(stmt3); ASSERT_EQ(order3, order1); std::ostringstream oss1, oss2; oss1 << *stmt1; oss2 << *stmt3; // Should be identical to the unreordered statement. ASSERT_EQ(oss1.str(), oss2.str()); } void testLoopNestReorderPartialAxes() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{2, "x"}, {3, "y"}, {4, "z"}}, [](const VarHandle& x, const VarHandle& y, const VarHandle& z) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y + cast<float>(z) * z; }); LoopNest l({tensor}); LoopOrderHelper loopOrderHelper; Stmt* stmt1 = Stmt::clone(l.root_stmt()); ASSERT_EQ(loopOrderHelper.getOrder(stmt1), "x,y,z,"); std::vector<int> stmt1_output(24, 0); SimpleIREvaluator cg(stmt1, {tensor}); cg.call({stmt1_output}); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[1]); ASSERT_EQ(loopOrderHelper.getOrder(l.root_stmt()), "y,x,z,"); Stmt* stmt2 = Stmt::clone(l.root_stmt()); std::vector<int> stmt2_output(24, 0); SimpleIREvaluator cg2(stmt2, {tensor}); cg2.call({stmt2_output}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(stmt1_output[i], stmt2_output[i]); } loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[1], loops[2]); ASSERT_EQ(loopOrderHelper.getOrder(l.root_stmt()), "y,z,x,"); Stmt* stmt3 = Stmt::clone(l.root_stmt()); std::vector<int> stmt3_output(24, 0); SimpleIREvaluator cg3(stmt3, {tensor}); cg3.call({stmt3_output}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(stmt1_output[i], stmt3_output[i]); } } void testLoopNestReorderInternalAxis() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{1, "w"}, {2, "x"}, {3, "y"}, {4, "z"}}, [](const VarHandle& w, const VarHandle& x, const VarHandle& y, const VarHandle& z) { return ExprHandle(1.0f) + w + cast<float>(x) * x + cast<float>(y) * y + cast<float>(z) * z; }); LoopNest l({tensor}); LoopOrderHelper loopOrderHelper; Stmt* stmt1 = Stmt::clone(l.root_stmt()); ASSERT_EQ(loopOrderHelper.getOrder(stmt1), "w,x,y,z,"); std::vector<int> stmt1_output(24, 0); SimpleIREvaluator cg(stmt1, {tensor}); cg.call({stmt1_output}); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[2], loops[1]); ASSERT_EQ(loopOrderHelper.getOrder(l.root_stmt()), "w,y,x,z,"); Stmt* stmt2 = l.root_stmt(); std::vector<int> stmt2_output(24, 0); SimpleIREvaluator cg2(stmt2, {tensor}); cg2.call({stmt2_output}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(stmt1_output[i], stmt2_output[i]); } } void testLoopNestReorderEnclosingAxis() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{1, "w"}, {2, "x"}, {3, "y"}, {4, "z"}}, [](const VarHandle& w, const VarHandle& x, const VarHandle& y, const VarHandle& z) { return ExprHandle(1.0f) + w + cast<float>(x) * x + cast<float>(y) * y + cast<float>(z) * z; }); LoopNest l({tensor}); LoopOrderHelper loopOrderHelper; Stmt* stmt1 = Stmt::clone(l.root_stmt()); std::vector<int> stmt1_output(24, 0); SimpleIREvaluator cg(stmt1, {tensor}); cg.call({stmt1_output}); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[3]); ASSERT_EQ(loopOrderHelper.getOrder(l.root_stmt()), "z,x,y,w,"); Stmt* stmt2 = l.root_stmt(); std::vector<int> stmt2_output(24, 0); SimpleIREvaluator cg2(stmt2, {tensor}); cg2.call({stmt2_output}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(stmt1_output[i], stmt2_output[i]); } } void testLoopNestReorderSameAxis() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{2, "x"}, {3, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); Stmt* stmt1 = Stmt::clone(l.root_stmt()); auto loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[1], loops[1]); Stmt* stmt2 = Stmt::clone(l.root_stmt()); std::ostringstream oss, oss2; oss << *stmt1; oss2 << *stmt2; ASSERT_EQ(oss.str(), oss2.str()); } void testLoopNestReorderExtraStatements() { /* We're going for a structure like this: * for x in ... * Stmt 1 * for y in ... * Stmt 2 * for z in ... * Stmt 3 * Stmt 4 */ KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{2, "x"}, {3, "y"}, {4, "z"}}, [](const VarHandle& x, const VarHandle& y, const VarHandle& z) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y + cast<float>(z) * z; }); LoopNest l({tensor}); Placeholder extra(BufHandle("res", {6, 3}, kFloat)); auto loops = l.getLoopStmtsFor(tensor); VarHandle i = VarHandle(loops[0]->var()); Stmt* store_1 = Store::make(BufHandle(extra.data()), {i, 0}, ExprHandle(1.f), 1); Stmt* store_2 = Store::make(BufHandle(extra.data()), {i, 1}, ExprHandle(2.f), 1); // stmt 3 is the Function body. Stmt* store_3 = Store::make(BufHandle(extra.data()), {i, 2}, ExprHandle(4.f), 1); loops[0]->body()->prepend_stmt(store_1); loops[1]->body()->prepend_stmt(store_2); loops[1]->body()->append_stmt(store_3); Stmt* stmt1 = Stmt::clone(l.root_stmt()); std::vector<int> extra1(6, 0); std::vector<int> res1(24, 0); SimpleIREvaluator cg(stmt1, {tensor, extra}); cg.call({res1, extra1}); /* Then we reorder loop y and z, we want it to look like: * * for x in ... * Stmt 1 * for y in ... * Stmt 2 * for z in ... * for y in ... * Stmt 3 * for y in ... * Stmt 4 * * We need extra loops because we don't have dependency info about stmt 3 * and 4. * */ l.reorderAxis(loops[1], loops[2]); Stmt* stmt2 = Stmt::clone(l.root_stmt()); std::ostringstream oss; oss << *l.root_stmt(); // Check the IR we produced const std::string& verification_pattern1 = R"IR( # CHECK: for (int x # CHECK: res[x, 0] = 1 # CHECK: for (int y # CHECK: res[x, 1] = 2 # CHECK: for (int z # CHECK: for (int y # CHECK: f[ # CHECK: for (int y # CHECK: res[x, 2] = 4 )IR"; torch::jit::testing::FileCheck().run(verification_pattern1, oss.str()); std::vector<int> extra2(6, 0); std::vector<int> res2(24, 0); SimpleIREvaluator cg2(stmt2, {tensor, extra}); cg2.call({res2, extra2}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(res1[i], res2[i]); } for (int i = 0; i < 6; ++i) { ASSERT_EQ(extra1[i], extra2[i]); } /* Now reorder x and the y above stmt 3: * * * for x in ... * Stmt 1 * for y in ... * Stmt 2 * * for y in ... * for z in ... * for x in ... * Stmt 3 * * for x in ... * for y in ... * Stmt 4 * * */ loops = l.getLoopStmtsFor(tensor); l.reorderAxis(loops[0], loops[2]); Stmt* stmt3 = Stmt::clone(l.root_stmt()); std::ostringstream oss2; oss2 << *stmt3; // Check the IR we produced const std::string& verification_pattern2 = R"IR( # CHECK: for (int x # CHECK: res[x, 0] = 1 # CHECK: for (int y # CHECK: res[x, 1] = 2 # CHECK: for (int y # CHECK: for (int z # CHECK: for (int x # CHECK: f[ # CHECK: for (int x # CHECK: for (int y # CHECK: res[x, 2] = 4 )IR"; torch::jit::testing::FileCheck().run(verification_pattern2, oss2.str()); std::vector<int> extra3(6, 0); std::vector<int> res3(24, 0); SimpleIREvaluator cg3(stmt3, {tensor, extra}); cg3.call({res3, extra3}); for (int i = 0; i < 24; ++i) { ASSERT_EQ(res1[i], res3[i]); } for (int i = 0; i < 6; ++i) { ASSERT_EQ(extra1[i], extra3[i]); } } void LoopNestReorderTestHelper( bool prepend, bool append, int index1, int index2) { KernelScope kernel_scope; Tensor* c = Compute( "5d", {{2, "a"}, {3, "b"}, {2, "c"}, {3, "d"}, {2, "e"}}, [](const std::vector<VarHandle>&) { return -1; }); LoopNest l({c}); Placeholder extra(BufHandle("extra", {5}, kInt)); auto loops = l.getLoopStmtsFor(c); int j = 0; for (auto* l : loops) { // Add an increment at each layer of the loop which counts the number of // times the loop executes. Load* load = new Load(extra.data(), {new IntImm(j)}, new IntImm(1)); Add* add = new Add(load, new IntImm(1)); Stmt* store = new Store(extra.data(), {new IntImm(j)}, add, new IntImm(1)); if (prepend) { l->body()->prepend_stmt(store); } if (append) { l->body()->append_stmt(Stmt::clone(store)); } j++; } Stmt* stmt1 = Stmt::clone(l.root_stmt()); std::vector<int> extra1(5, 0); std::vector<int> res1(2 * 3 * 2 * 3 * 2, 0); SimpleIREvaluator cg(stmt1, {c, extra}); cg.call({res1, extra1}); std::vector<int> loopExtents = {2, 3, 2, 3, 2}; int expected_loops = 0; if (prepend) { expected_loops++; } if (append) { expected_loops++; } for (int i = 0; i < 5; ++i) { expected_loops *= loopExtents[i]; ASSERT_EQ(extra1[i], expected_loops); } loops = l.getLoopStmtsFor(c); l.reorderAxis(loops[index1], loops[index2]); Stmt* stmt2 = Stmt::clone(l.root_stmt()); std::ostringstream oss, oss2; oss << *stmt1; oss2 << *stmt2; ASSERT_NE(oss.str(), oss2.str()); std::vector<int> extra2(5, 0); std::vector<int> res2(2 * 3 * 2 * 3 * 2, 0); SimpleIREvaluator cg2(stmt2, {c, extra}); cg2.call({res2, extra2}); expected_loops = 0; if (prepend) { expected_loops++; } if (append) { expected_loops++; } for (int i = 0; i < 5; ++i) { expected_loops *= loopExtents[i]; ASSERT_EQ(extra2[i], expected_loops); } for (int i = 0; i < 2 * 3 * 2 * 3 * 2; ++i) { ASSERT_EQ(res2[i], res1[i]); } } void testLoopNestReorderLongStringOfPreOrphans() { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { // skip noops, since we check the loop isn't the same after reordering. if (i != j) { LoopNestReorderTestHelper(true, false, i, j); } } } } void testLoopNestReorderLongStringOfPostOrphans() { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { // skip noops, since we check the loop isn't the same after reordering. if (i != j) { LoopNestReorderTestHelper(false, true, i, j); } } } } void testLoopNestReorderLongStringFull() { for (int i = 0; i < 5; ++i) { for (int j = 0; j < 5; ++j) { // skip noops, since we check the loop isn't the same after reordering. if (i != j) { LoopNestReorderTestHelper(true, true, i, j); } } } } void testLoopNestReorderInternalLoopNest() { KernelScope kernel_scope; const int M = 4; const int N = 5; const int K = 6; Placeholder a_buf("a", kFloat, {M, N}); Placeholder b_buf("b", kFloat, {N, K}); Placeholder c_buf("c", kFloat, {M, N}); Placeholder d_buf("d", kFloat, {M, K}); Tensor* x = Compute( "x", {{M, "m1"}, {N, "n1"}, {K, "k1"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return a_buf.load(m, n) * b_buf.load(n, k); }); Tensor* y = Compute( "y", {{M, "m2"}, {N, "n2"}, {K, "k2"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return c_buf.load(m, n) * d_buf.load(m, k) + x->call(m, n, k); }); Tensor* z = Compute( "z", {{M, "m3"}, {N, "n3"}, {K, "k3"}}, [&](const VarHandle& m, const VarHandle& n, const VarHandle& k) { return x->call(m, n, k) + y->call(m, n, k); }); LoopNest l({z}); For* a = nullptr; For* b = nullptr; auto fors = NodeFinder<For>::find(l.root_stmt()); for (auto* f : fors) { if (f->var()->name_hint() == "m2") { a = f; } else if (f->var()->name_hint() == "k2") { b = f; } } l.reorderAxis(a, b); l.prepareForCodegen(); Stmt* stmt = IRSimplifier::simplify(l.root_stmt()); std::ostringstream oss; oss << *stmt; // Check the IR we produced has the 3 nests in the right order, but k and m // swapped in the middle. const std::string& verification_pattern = R"IR( # CHECK: for (int m1 # CHECK: for (int n1 # CHECK: for (int k1 # CHECK: for (int k2 # CHECK: for (int n2 # CHECK: for (int m2 # CHECK: for (int m3 # CHECK: for (int n3 # CHECK: for (int k3)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); { PaddedBuffer<float> a_v(M, N); PaddedBuffer<float> b_v(N, K); PaddedBuffer<float> c_v(M, N); PaddedBuffer<float> d_v(M, K); for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a_v(i, j) = i * i; } } for (int i = 0; i < N; i++) { for (int j = 0; j < K; j++) { b_v(i, j) = j * j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { c_v(i, j) = i + j; } } for (int i = 0; i < M; i++) { for (int j = 0; j < K; j++) { d_v(i, j) = i * j; } } PaddedBuffer<float> z_v(M, N, K); PaddedBuffer<float> z_ref(M, N, K); for (int m = 0; m < M; m++) { for (int n = 0; n < N; n++) { for (int k = 0; k < K; k++) { z_ref(m, n, k) = a_v(m, n) * b_v(n, k) * 2 + c_v(m, n) * d_v(m, k); } } } SimpleIREvaluator eval(stmt, a_buf, b_buf, c_buf, d_buf, z); eval(a_v, b_v, c_v, d_v, z_v); ExpectAllNear(z_v, z_ref, 1e-5); } } void testOuterLoopVectorization() { KernelScope kernel_scope; Tensor* tensor = Compute( "f", {{8, "X"}, {8, "y"}}, [](const VarHandle& x, const VarHandle& y) { return ExprHandle(1.0f) + cast<float>(x) * x + cast<float>(y) * y; }); LoopNest l({tensor}); l.vectorize(l.getLoopStmtsFor(tensor)[0]); Stmt* root_stmt = l.root_stmt(); Block* outer_block = dynamic_cast<Block*>(root_stmt); ASSERT_NE(outer_block, nullptr); while (Block* inner_block = dynamic_cast<Block*>(outer_block->front())) { outer_block = inner_block; } // Verify that we have only a single loop level remaining after // vectorization. ASSERT_EQ(outer_block->nstmts(), 1); For* for_loop = dynamic_cast<For*>(outer_block->front()); ASSERT_NE(for_loop, nullptr); Block* for_body = for_loop->body(); ASSERT_EQ(for_body->nstmts(), 1); ASSERT_EQ(dynamic_cast<For*>(for_body->front()), nullptr); } namespace { std::string constantUpperBoundLoopIR(int upper_bound_val) { KernelScope kernel_scope; ExprHandle upper_bound(upper_bound_val); Tensor* A = Compute( "A", {{upper_bound, "x"}}, [&](const VarHandle& x) { return x * 2; }); LoopNest l({A}); std::vector<For*> loops = l.getLoopStmtsFor(A); Stmt* unrolled = nullptr; LoopNest::unroll(loops[0], &unrolled); std::ostringstream oss; oss << *unrolled; return oss.str(); } } // namespace void testUnroll() { const std::string actual = constantUpperBoundLoopIR(3); const std::string& verification_pattern = R"IR( # CHECK: A[0] = 0; # CHECK: A[1] = 2; # CHECK: A[2] = 4)IR"; torch::jit::testing::FileCheck().run(verification_pattern, actual); } void testUnrollOuter() { KernelScope kernel_scope; ExprHandle outer_bound(3); ExprHandle inner_bound(4); Tensor* A = Compute( "A", {{outer_bound, "x"}, {inner_bound, "y"}}, [&](const VarHandle& x, const VarHandle& y) { return x + y; }); LoopNest l({A}); std::vector<For*> loops = l.getLoopStmtsFor(A); Stmt* unrolled = nullptr; LoopNest::unroll(loops[0], &unrolled); const std::string& verification_pattern = R"IR( # CHECK: for (int y = 0; y < 4; y++) { # CHECK: A[0, y] = y; # CHECK: } # CHECK: for (int y = 0; y < 4; y++) { # CHECK: A[1, y] = y + 1; # CHECK: } # CHECK: for (int y = 0; y < 4; y++) { # CHECK: A[2, y] = y + 2; # CHECK: })IR"; std::ostringstream oss; oss << *unrolled; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } void testUnrollInner() { KernelScope kernel_scope; ExprHandle outer_bound(3); ExprHandle inner_bound(4); Tensor* A = Compute( "A", {{outer_bound, "x"}, {inner_bound, "y"}}, [&](const VarHandle& x, const VarHandle& y) { return x + y; }); LoopNest l({A}); std::vector<For*> loops = l.getLoopStmtsFor(A); Stmt* unrolled = nullptr; LoopNest::unroll( static_cast<For*>(loops[0]->body()->stmts().front()), &unrolled); const std::string& verification_pattern = R"IR( # CHECK: for (int x = 0; x < 3; x++) { # CHECK: A[x, 0] = x; # CHECK: A[x, 1] = x + 1; # CHECK: A[x, 2] = x + 2; # CHECK: A[x, 3] = x + 3; # CHECK: })IR"; std::ostringstream oss; oss << *loops[0]; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } void testUnrollMultipleStatements() { KernelScope kernel_scope; const int kTotalSize = 3; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto f = For::make( x, 0, kTotalSize, Block::make({Store::make(a_buf, {x}, x * 2), Store::make(b_buf, {x}, Load::make(a_buf, {x}, 1))})); Block::make({f}); Stmt* unrolled = nullptr; LoopNest::unroll(f, &unrolled); std::ostringstream oss; oss << *unrolled; const std::string& verification_pattern = R"IR( # CHECK: A[0] = 0; # CHECK: B[0] = A[0]; # CHECK: A[1] = 2; # CHECK: B[1] = A[1]; # CHECK: A[2] = 4 # CHECK: B[2] = A[2];)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); } void testUnrollEmpty() { const std::string actual = constantUpperBoundLoopIR(0); const std::string& verification_pattern = R"IR( # CHECK-NOT: A[ )IR"; torch::jit::testing::FileCheck().run(verification_pattern, actual); } void testNoUnroll() { KernelScope kernel_scope; VarHandle upper_bound("N", kInt); Tensor* A = Compute( "A", {{upper_bound, "x"}}, [&](const VarHandle& x) { return x * 2; }); LoopNest l({A}); std::vector<For*> loops = l.getLoopStmtsFor(A); Stmt* unrolled = nullptr; ASSERT_THROWS_WITH( LoopNest::unroll(loops[0], &unrolled), "non-constant loop"); } void testUnrollWithLet() { KernelScope kernel_scope; const int kTotalSize = 3; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle e("e", kInt); VarHandle x("x", kInt); auto f = For::make( x, 0, kTotalSize, Block::make({Let::make(e, 7), Store::make(a_buf, {x}, e), Store::make(b_buf, {x}, e + 1)})); Block::make({f}); Stmt* unrolled = nullptr; LoopNest::unroll(f, &unrolled); std::ostringstream oss; oss << *unrolled; const std::string& verification_pattern = R"IR( # CHECK: int e = 7; # CHECK: A[0] = e; # CHECK: B[0] = e + 1; # CHECK: A[1] = e; # CHECK: B[1] = e + 1; # CHECK: A[2] = e; # CHECK: B[2] = e + 1;)IR"; torch::jit::testing::FileCheck().run(verification_pattern, oss.str()); std::vector<int> a_v(kTotalSize, 0); std::vector<int> b_v(kTotalSize, 0); SimpleIREvaluator eval(unrolled, a_buf, b_buf); eval(a_v, b_v); for (int i = 0; i < kTotalSize; ++i) { ASSERT_EQ(a_v[i], 7); ASSERT_EQ(b_v[i], 8); } } void testNormalizeStartPositive() { KernelScope kernel_scope; // Input IR: // for (int x = 50; x < 100; x++) { // A[x] = B[x]; // B[x] = x * 2; // } const int kTotalSize = 50; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto for_body = Block::make({Store::make(a_buf, {x}, Load::make(kInt, b_buf, {x}, 1), 1), Store::make(b_buf, {x}, x * 2)}); auto for_stmt = For::make(x, 50, 100, for_body); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 50; x++) { # CHECK: A[x + 50] = B[x + 50]; # CHECK: B[x + 50] = 2 * (x + 50); )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeStartNegative() { KernelScope kernel_scope; // Input IR: // for (int x = -50; x < 100; x++) { // A[x + 50] = B[x + 50]; // B[x + 50] = x * 2; // } const int kTotalSize = 150; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto for_body = Block::make( {Store::make(a_buf, {x + 50}, Load::make(kInt, b_buf, {x + 50}, 1), 1), Store::make(b_buf, {x + 50}, x * 2)}); auto for_stmt = For::make(x, -50, 100, for_body); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 150; x++) { # CHECK: A[x] = B[x]; # CHECK: B[x] = 2 * (x - 50); )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeStartZero() { KernelScope kernel_scope; // Input IR: // for (int x = 0; x < 100; x++) { // A[x] = B[x]; // B[x] = x * 2; // } // Should not be modified. const int kTotalSize = 100; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto for_body = Block::make({Store::make(a_buf, {x}, Load::make(kInt, b_buf, {x}, 1), 1), Store::make(b_buf, {x}, x * 2)}); auto for_stmt = For::make(x, 0, 100, for_body); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 100; x++) { # CHECK: A[x] = B[x]; # CHECK: B[x] = 2 * x; )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeStartVariable() { KernelScope kernel_scope; // Input IR: // for (int x = y; x < 100; x++) { // A[x] = B[x]; // B[x] = x * 2; // } const int kTotalSize = 100; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); BufHandle b_buf("B", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); auto for_body = Block::make({Store::make(a_buf, {x}, Load::make(kInt, b_buf, {x}, 1), 1), Store::make(b_buf, {x}, x * 2)}); auto for_stmt = For::make(x, y, 100, for_body); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 100 - y; x++) { # CHECK: A[y + x] = B[y + x]; # CHECK: B[y + x] = 2 * (y + x); )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeOnNestedOuterLoop() { KernelScope kernel_scope; // Input IR: // for (int x = 50; x < 100; x++) { // for (int y = 10; y < 100; y++) { // A[x] = A[x] + B[y] + y * 2; // } // } BufHandle a_buf("A", {ExprHandle(50)}, kInt); BufHandle b_buf("B", {ExprHandle(100)}, kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); auto inner_for_body = Store::make( a_buf, {x}, Load::make(a_buf, {x}, 1) + Load::make(b_buf, {y}, 1) + y * 2, 1); auto inner_for = For::make(y, 10, 100, inner_for_body); auto for_stmt = For::make(x, 50, 100, inner_for); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); auto result = IRSimplifier::simplify(normalized); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 0; x < 50; x++) { # CHECK: for (int y = 10; y < 100; y++) { # CHECK: A[x + 50] = ((B[y]) + (A[x + 50])) + 2 * y; )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeOnNestedInnerLoop() { KernelScope kernel_scope; // Input IR: // for (int x = 50; x < 100; x++) { // for (int y = 10; y < 100; y++) { // A[x] = A[x] + B[y] + y * 2; // } // } BufHandle a_buf("A", {ExprHandle(50)}, kInt); BufHandle b_buf("B", {ExprHandle(100)}, kInt); VarHandle x("x", kInt); VarHandle y("y", kInt); auto inner_for_body = Store::make( a_buf, {x}, Load::make(a_buf, {x}, 1) + Load::make(b_buf, {y}, 1) + y * 2, 1); auto inner_for = For::make(y, 10, 100, inner_for_body); auto for_stmt = For::make(x, 50, 100, inner_for); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(inner_for, &normalized); auto result = IRSimplifier::simplify(for_stmt); std::ostringstream oss; oss << *result; const std::string& expected_ir = R"IR( # CHECK: for (int x = 50; x < 100; x++) { # CHECK: for (int y = 0; y < 90; y++) { # CHECK: A[x] = (((B[y + 10]) + (A[x])) + 2 * y) + 20; )IR"; torch::jit::testing::FileCheck().run(expected_ir, oss.str()); } void testNormalizeAndSplitWithTail() { KernelScope kernel_scope; // Create a dummy tensor to construct LoopNest. ExprHandle n(100); Placeholder a(BufHandle("a", {n}, kFloat)); Tensor* b = Compute("b", {{n, "i"}}, [&](const VarHandle& i) { return a.load(i); }); LoopNest l({b}); // Input IR: // for (int x = 5; x < 10; x++) { // A[x] = x * 2; // } const int kTotalSize = 5; BufHandle a_buf("A", {ExprHandle(kTotalSize)}, kInt); VarHandle x("x", kInt); auto for_stmt = For::make(x, 5, 10, Store::make(a_buf, {x}, x * 2)); Block::make({for_stmt}); For* normalized = nullptr; LoopNest::normalize(for_stmt, &normalized); For* x_outer; For* x_inner; For* x_tail; l.splitWithTail(normalized, 10, &x_outer, &x_inner, &x_tail); auto x_outer_result = IRSimplifier::simplify(x_outer); std::ostringstream oss_outer; oss_outer << *x_outer_result; const std::string& expected_outer_ir = R"IR( # CHECK: { # CHECK: } )IR"; torch::jit::testing::FileCheck().run(expected_outer_ir, oss_outer.str()); auto x_tail_result = IRSimplifier::simplify(x_tail); std::ostringstream oss_tail; oss_tail << *x_tail_result; const std::string& expected_tail_ir = R"IR( # CHECK: for (int x_tail = 0; x_tail < 5; x_tail++) { # CHECK: A[x_tail + 5] = 2 * (x_tail + 5); )IR"; torch::jit::testing::FileCheck().run(expected_tail_ir, oss_tail.str()); } void testDetectInlineRankMismatch() { KernelScope kernel_scope; const int kTotalSize = 8; Placeholder a_buf(BufHandle("A", {ExprHandle(kTotalSize)}, kFloat)); Tensor* a = Compute("a", {{kTotalSize, "i"}}, [&](const VarHandle& i) { return a_buf.load(i); }); Tensor* reshape = Compute( "reshape", {{kTotalSize / 2, "i"}, {2, "j"}}, [&](const VarHandle& i, const VarHandle& j) { return a->call(i, j); }); LoopNest l({reshape}); ASSERT_THROWS_WITH( l.computeInline(l.getLoopBodyFor(a)), "Placeholder indexed access is inconsistent with its rank"); } } // namespace jit } // namespace torch
82,756
35,577
// -*-Mode: C++;-*- // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2018, Rice 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // $HeadURL$ // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** #ifndef Analysis_Args_hpp #define Analysis_Args_hpp //************************* System Include Files **************************** #include <iostream> #include <string> #include <vector> //*************************** User Include Files **************************** #include <include/uint.h> //*************************** Forward Declarations ************************** //*************************************************************************** namespace Analysis { // PathTuple: a {path, viewname} pair. // PathTuple.first = path; PathTuple.second = path target or viewname // PathTupleVec: the vector of all 'PathTuple' typedef std::pair<std::string, std::string> PathTuple; typedef std::vector<PathTuple> PathTupleVec; const std::string DefaultPathTupleTarget = "src"; } // namespace Analysis //*************************************************************************** namespace Analysis { //--------------------------------------------------------------------------- // Arguments for source code correlation //--------------------------------------------------------------------------- class Args { public: Args(); virtual ~Args(); // Dump virtual std::string toString() const; virtual void dump(std::ostream& os = std::cerr) const; void ddump() const; public: // ------------------------------------------------------- // Agent options // ------------------------------------------------------- std::string agent; // ------------------------------------------------------- // Attribution/Correlation arguments: general // ------------------------------------------------------- // Title std::string title; // Search paths //std::vector<std::string> searchPaths; PathTupleVec searchPathTpls; // Structure files std::vector<std::string> structureFiles; // Group files std::vector<std::string> groupFiles; // Replace paths std::vector<std::string> replaceInPath; std::vector<std::string> replaceOutPath; // Profile files std::vector<std::string> profileFiles; bool doNormalizeTy; // ------------------------------------------------------- // Attribution/Correlation arguments: special // ------------------------------------------------------- enum MetricFlg { MetricFlg_NULL = 0, MetricFlg_Thread = (1 << 1), MetricFlg_StatsSum = (1 << 2), MetricFlg_StatsAll = (1 << 3) }; static inline bool MetricFlg_isSet(uint flags, MetricFlg x) { return (flags & x); } static inline void MetricFlg_set(uint& flags, MetricFlg x) { flags |= x; } static inline void MetricFlg_clear(uint& flags, MetricFlg x) { flags &= ~x; } static inline bool MetricFlg_isThread(uint flags) { return MetricFlg_isSet(flags, MetricFlg_Thread); } static inline bool MetricFlg_isSum(uint flags) { return (MetricFlg_isSet(flags, MetricFlg_StatsSum) || MetricFlg_isSet(flags, MetricFlg_StatsAll)); } uint prof_metrics; // TODO: Currently this is always true even though we only need to // compute final metric values for (1) hpcproftt (flat) and (2) // hpcprof-flat when it computes derived metrics. However, at the // moment this is a sinking ship and not worth the time investment. bool profflat_computeFinalMetricValues; // ------------------------------------------------------- // Output arguments: experiment database output // ------------------------------------------------------- #define Analysis_OUT_DB_EXPERIMENT "experiment.xml" #define Analysis_OUT_DB_CSV "experiment.csv" #define Analysis_DB_DIR_pfx "hpctoolkit" #define Analysis_DB_DIR_nm "database" #define Analysis_DB_DIR "hpctoolkit-<app>-database" std::string out_db_experiment; // disable: "", stdout: "-" std::string out_db_csv; // disable: "", stdout: "-" std::string db_dir; // disable: "" bool db_copySrcFiles; std::string out_db_config; // disable: "", stdout: "-" bool db_makeMetricDB; bool db_addStructId; // ------------------------------------------------------- // Output arguments: textual output // ------------------------------------------------------- #define Analysis_OUT_TXT "" std::string out_txt; // disable: "", stdout: "-" enum TxtSum { TxtSum_NULL = 0, // individual flags TxtSum_fPgm = 0x00000001, TxtSum_fLM = 0x00000010, TxtSum_fFile = 0x00000100, TxtSum_fProc = 0x00001000, TxtSum_fLoop = 0x00010000, TxtSum_fStmt = 0x00100000, // composite flags TxtSum_ALL = (TxtSum_fPgm | TxtSum_fLM | TxtSum_fFile | TxtSum_fProc | TxtSum_fLoop | TxtSum_fStmt) }; int/*TxtSum*/ txt_summary; bool txt_srcAnnotation; std::vector<std::string> txt_srcFileGlobs; // flag to remove procedure name redundancy // this feature is not fully reliable to remove procedure // name redundancy, especially if compiled with g++ -O2 // since the compiler doesn't generate function parameters // and cannot distinguish between foo(int) and foo(int, int) bool remove_redundancy; public: // ------------------------------------------------------- // // ------------------------------------------------------- void normalizeSearchPaths(); // makes a unique database dir void makeDatabaseDir(); std::string searchPathStr() const; private: void Ctor(); }; } // namespace Analysis //*************************************************************************** #endif // Analysis_Args_hpp
7,948
2,280
/* * TurnByAngle.cpp * * Created on: Apr 14, 2018 * Author: healym */ #include "TurnByAngle.h" #include "../Robot.h" constexpr double LEFT_POWER = .25; constexpr double RIGHT_POWER = -.25; namespace { // Converts an angle (in degrees) to a value in the range [0..360). double normalizeAngle(double angleDegrees) { double result = 0; if (angleDegrees >= 0 && angleDegrees < 360) { result = angleDegrees; } else if (angleDegrees < 0) { // Angle is negative (and for now, we'll only turn to the left), so // convert it to a positive value. result = angleDegrees - (((int(angleDegrees) / 360) - 1) * 360); } else { // Angle is too big: reduce it result = angleDegrees - ((int(angleDegrees) / 360) * 360); } return result; } } TurnByAngle::TurnByAngle(double angleDegrees) : angleDegrees(normalizeAngle(angleDegrees)) { Requires (Robot::driveBase.get()); Requires (Robot::navAlt.get()); } // Called just before this Command runs the first time void TurnByAngle::Initialize() { Robot::navAlt->resetGyro(); // Note: This is going to produce pretty jerky motion, especially at // anything near full power. A better approach might be to start out at // low power, ramping up to speed (in an overload of the execute() // function), and ramping down as we get close to the end of the allotted // time. Robot::driveBase->SetPower(LEFT_POWER, RIGHT_POWER); } // Make this return true when this Command no longer needs to run execute() bool TurnByAngle::IsFinished() { return Robot::navAlt->getGyroValue() >= angleDegrees; } // Called once after isFinished returns true void TurnByAngle::End() { Robot::driveBase->Stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run void TurnByAngle::Interrupted() { End(); }
1,823
667
#include "inst.h" /**************************************************************************** * CLASS 4C ****************************************************************************/ #undef INST #define INST INST_CLASS_4C C33_OP(scan0_rd_rs) { c33word ua, ub; ua = Rs.w; for(ub = 0; ub < 8; ub++) { if(!(ua & (1 << 31))) break; ua <<= 1; } Rd.w = ub; PSR.z = ub == 0; PSR.c = ub == 8; PC.w += 2; CLK += 1; } C33_OP(scan1_rd_rs) { c33word ua, ub; ua = Rs.w; for(ub = 0; ub < 8; ub++) { if(ua & (1 << 31)) break; ua <<= 1; } Rd.w = ub; PSR.z = ub == 0; PSR.c = ub == 8; PC.w += 2; CLK += 1; } C33_OP(swap_rd_rs) { c33word ua; ua = Rs.w; Rd.w = ((ua & 0x000000ff) << 24) | ((ua & 0x0000ff00) << 8) | ((ua & 0x00ff0000) >> 8) | ((ua & 0xff000000) >> 24); PC.w += 2; CLK += 1; } C33_OP(mirror_rd_rs) { c33word ua; ua = Rs.w; Rd.w = ((ua & 0x01010101) << 7) | ((ua & 0x02020202) << 5) | ((ua & 0x04040404) << 3) | ((ua & 0x08080808) << 1) | ((ua & 0x10101010) >> 1) | ((ua & 0x20202020) >> 3) | ((ua & 0x40404040) >> 5) | ((ua & 0x80808080) >> 7); PC.w += 2; CLK += 1; } C33_OP(div0s_rs) { if(!Rs.i) core_trap(TRAP_ZERODIV, 0); AHR.w = (c33int)ALR.w >> 31; PSR.ds = ALR.w >> 31; PSR.n = Rs.w >> 31; PC.w += 2; CLK += 1; } C33_OP(div0u_rs) { if(!Rs.i) core_trap(TRAP_ZERODIV, 0); AHR.w = 0; PSR.ds = 0; PSR.n = 0; PC.w += 2; CLK += 1; } C33_OP(div1_rs) { c33int tmp; /* div0x以外では、ゼロ除算例外は発生しません。 */ AR <<= 1; if(!PSR.ds) { if(!PSR.n) { /* 正÷正 */ tmp = AHR.i - Rs.i; if(tmp <= AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } else { /* 正÷負 */ tmp = AHR.i + Rs.i; if(tmp < AHR.i) { /* C */ AHR.i = tmp; ALR.i |= 1; } } } else { if(!PSR.n) { /* 負÷正 */ tmp = AHR.i + Rs.i; if(tmp >= AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } else { /* 負÷負 */ tmp = AHR.i - Rs.i; if(tmp > AHR.i) { /* !C */ AHR.i = tmp; ALR.i |= 1; } } } PC.w += 2; CLK += 1; } C33_OP(div2s_rs) { c33word tmp; /* div0x以外では、ゼロ除算例外は発生しません。 */ if(PSR.ds) { if(!PSR.n) { tmp = AHR.i + Rs.i; } else { tmp = AHR.i - Rs.i; } if(!tmp) { AHR.i = tmp; ALR.i += 1; } } PC.w += 2; CLK += 1; } C33_OP(div3s) { /* div0x以外では、ゼロ除算例外は発生しません。 */ if(PSR.ds != PSR.n) { ALR.i = 0 - ALR.i; /* ALR = -ALR では警告になるので… */ } PC.w += 2; CLK += 1; }
2,717
1,617
#include <boost/fusion/include/at_c.hpp>
41
18
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/tabs/tab_strip_model_utils.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "components/history/core/browser/top_sites.h" #include "content/public/browser/web_contents.h" namespace chrome { void GetOpenUrls(const TabStripModel& tabs, const history::TopSites& top_sites, std::set<std::string>* urls) { for (int i = 0; i < tabs.count(); ++i) { content::WebContents* web_contents = tabs.GetWebContentsAt(i); if (web_contents) urls->insert(top_sites.GetCanonicalURLString(web_contents->GetURL())); } } } // namespace chrome
790
265
#include <bits/stdc++.h> using namespace std; int n, num, cnt; vector<pair<int, int> > arr; vector<int> ans; int main(void) { cin.tie(NULL); ios_base::sync_with_stdio(false); cin >> n; for (int i = 0; i < n; ++i) { cin >> num; arr.push_back({num, i}); } sort(arr.begin(), arr.end()); ans.assign(n, 0); ans[arr[0].second] = 0; for (int i = 1; i < arr.size(); ++i) { if (arr[i - 1].first == arr[i].first) cnt++; ans[arr[i].second] = i - cnt; } for (int i = 0; i < ans.size(); ++i) { cout << ans[i] << ' '; } }
554
257
/* * Written by Solar Designer <solar at openwall.com> in 2000-2011. * No copyright is claimed, and the software is hereby placed in the public * domain. In case this attempt to disclaim copyright and place the software * in the public domain is deemed null and void, then the software is * Copyright (c) 2000-2011 Solar Designer and it is hereby released to the * general public under the following terms: * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * See crypt_blowfish.c for more information. */ #include <stdlib.h> #include <string.h> #include <errno.h> #ifndef __set_errno #define __set_errno(val) errno = (val) #endif #ifdef TEST #include <stdio.h> #include <unistd.h> #include <signal.h> #include <time.h> #include <sys/time.h> #include <sys/times.h> #ifdef TEST_THREADS #include <pthread.h> #endif #endif #define CRYPT_OUTPUT_SIZE (7 + 22 + 31 + 1) #define CRYPT_GENSALT_OUTPUT_SIZE (7 + 22 + 1) #if defined(__GLIBC__) && defined(_LIBC) #define __SKIP_GNU #endif #include "ow-crypt.h" #include "crypt_blowfish.h" #include "crypt_gensalt.h" #if defined(__GLIBC__) && defined(_LIBC) /* crypt.h from glibc-crypt-2.1 will define struct crypt_data for us */ #include "crypt.h" extern char *__md5_crypt_r(const char *key, const char *salt, char *buffer, int buflen); /* crypt-entry.c needs to be patched to define __des_crypt_r rather than * __crypt_r, and not define crypt_r and crypt at all */ extern char *__des_crypt_r(const char *key, const char *salt, struct crypt_data *data); extern struct crypt_data _ufc_foobar; #endif static int _crypt_data_alloc(void **data, int *size, int need) { void *updated; if (*data && *size >= need) return 0; updated = realloc(*data, need); if (!updated) { #ifndef __GLIBC__ /* realloc(3) on glibc sets errno, so we don't need to bother */ __set_errno(ENOMEM); #endif return -1; } #if defined(__GLIBC__) && defined(_LIBC) if (need >= sizeof(struct crypt_data)) ((struct crypt_data *)updated)->initialized = 0; #endif *data = updated; *size = need; return 0; } static char *_crypt_retval_magic(char *retval, const char *setting, char *output, int size) { if (retval) return retval; if (_crypt_output_magic(setting, output, size)) return NULL; /* shouldn't happen */ return output; } #if defined(__GLIBC__) && defined(_LIBC) /* * Applications may re-use the same instance of struct crypt_data without * resetting the initialized field in order to let crypt_r() skip some of * its initialization code. Thus, it is important that our multiple hashing * algorithms either don't conflict with each other in their use of the * data area or reset the initialized field themselves whenever required. * Currently, the hashing algorithms simply have no conflicts: the first * field of struct crypt_data is the 128-byte large DES key schedule which * __des_crypt_r() calculates each time it is called while the two other * hashing algorithms use less than 128 bytes of the data area. */ char *__crypt_rn(__const char *key, __const char *setting, void *data, int size) { if (setting[0] == '$' && setting[1] == '2') return _crypt_blowfish_rn(key, setting, (char *)data, size); if (setting[0] == '$' && setting[1] == '1') return __md5_crypt_r(key, setting, (char *)data, size); if (setting[0] == '$' || setting[0] == '_') { __set_errno(EINVAL); return NULL; } if (size >= sizeof(struct crypt_data)) return __des_crypt_r(key, setting, (struct crypt_data *)data); __set_errno(ERANGE); return NULL; } char *__crypt_ra(__const char *key, __const char *setting, void **data, int *size) { if (setting[0] == '$' && setting[1] == '2') { if (_crypt_data_alloc(data, size, CRYPT_OUTPUT_SIZE)) return NULL; return _crypt_blowfish_rn(key, setting, (char *)*data, *size); } if (setting[0] == '$' && setting[1] == '1') { if (_crypt_data_alloc(data, size, CRYPT_OUTPUT_SIZE)) return NULL; return __md5_crypt_r(key, setting, (char *)*data, *size); } if (setting[0] == '$' || setting[0] == '_') { __set_errno(EINVAL); return NULL; } if (_crypt_data_alloc(data, size, sizeof(struct crypt_data))) return NULL; return __des_crypt_r(key, setting, (struct crypt_data *)*data); } char *__crypt_r(__const char *key, __const char *setting, struct crypt_data *data) { return _crypt_retval_magic( __crypt_rn(key, setting, data, sizeof(*data)), setting, (char *)data, sizeof(*data)); } char *__crypt(__const char *key, __const char *setting) { return _crypt_retval_magic( __crypt_rn(key, setting, &_ufc_foobar, sizeof(_ufc_foobar)), setting, (char *)&_ufc_foobar, sizeof(_ufc_foobar)); } #else char *crypt_rn(const char *key, const char *setting, void *data, int size) { return _crypt_blowfish_rn(key, setting, (char *)data, size); } char *crypt_ra(const char *key, const char *setting, void **data, int *size) { if (_crypt_data_alloc(data, size, CRYPT_OUTPUT_SIZE)) return NULL; return _crypt_blowfish_rn(key, setting, (char *)*data, *size); } char *crypt_r(const char *key, const char *setting, void *data) { return _crypt_retval_magic( crypt_rn(key, setting, data, CRYPT_OUTPUT_SIZE), setting, (char *)data, CRYPT_OUTPUT_SIZE); } char *crypt(const char *key, const char *setting) { static char output[CRYPT_OUTPUT_SIZE]; return _crypt_retval_magic( crypt_rn(key, setting, output, sizeof(output)), setting, output, sizeof(output)); } #define __crypt_gensalt_rn crypt_gensalt_rn #define __crypt_gensalt_ra crypt_gensalt_ra #define __crypt_gensalt crypt_gensalt #endif char *__crypt_gensalt_rn(const char *prefix, unsigned long count, const char *input, int size, char *output, int output_size) { char *(*use)(const char *_prefix, unsigned long _count, const char *_input, int _size, char *_output, int _output_size); /* This may be supported on some platforms in the future */ if (!input) { __set_errno(EINVAL); return NULL; } if (!strncmp(prefix, "$2a$", 4) || !strncmp(prefix, "$2y$", 4)) use = _crypt_gensalt_blowfish_rn; else if (!strncmp(prefix, "$1$", 3)) use = _crypt_gensalt_md5_rn; else if (prefix[0] == '_') use = _crypt_gensalt_extended_rn; else if (!prefix[0] || (prefix[0] && prefix[1] && memchr(_crypt_itoa64, prefix[0], 64) && memchr(_crypt_itoa64, prefix[1], 64))) use = _crypt_gensalt_traditional_rn; else { __set_errno(EINVAL); return NULL; } return use(prefix, count, input, size, output, output_size); } char *__crypt_gensalt_ra(const char *prefix, unsigned long count, const char *input, int size) { char output[CRYPT_GENSALT_OUTPUT_SIZE]; char *retval; retval = __crypt_gensalt_rn(prefix, count, input, size, output, sizeof(output)); if (retval) { retval = _strdup(retval); #ifndef __GLIBC__ /* strdup(3) on glibc sets errno, so we don't need to bother */ if (!retval) __set_errno(ENOMEM); #endif } return retval; } char *__crypt_gensalt(const char *prefix, unsigned long count, const char *input, int size) { static char output[CRYPT_GENSALT_OUTPUT_SIZE]; return __crypt_gensalt_rn(prefix, count, input, size, output, sizeof(output)); } #if defined(__GLIBC__) && defined(_LIBC) weak_alias(__crypt_rn, crypt_rn) weak_alias(__crypt_ra, crypt_ra) weak_alias(__crypt_r, crypt_r) weak_alias(__crypt, crypt) weak_alias(__crypt_gensalt_rn, crypt_gensalt_rn) weak_alias(__crypt_gensalt_ra, crypt_gensalt_ra) weak_alias(__crypt_gensalt, crypt_gensalt) weak_alias(crypt, fcrypt) #endif #ifdef TEST static const char *tests[][3] = { {"$2a$05$CCCCCCCCCCCCCCCCCCCCC.E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW", "U*U"}, {"$2a$05$CCCCCCCCCCCCCCCCCCCCC.VGOzA784oUp/Z0DY336zx7pLYAy0lwK", "U*U*"}, {"$2a$05$XXXXXXXXXXXXXXXXXXXXXOAcXxm9kjPGEMsLznoKqmqw7tc8WCx4a", "U*U*U"}, {"$2a$05$abcdefghijklmnopqrstuu5s2v8.iXieOjg/.AySBTTZIIVFJeBui", "0123456789abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" "chars after 72 are ignored"}, {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", "\xa3"}, {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", "\xff\xff\xa3"}, {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.CE5elHaaO4EbggVDjb8P19RukzXSM3e", "\xff\xff\xa3"}, {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.nqd1wy.pTMdcvrRWxyiGL2eMz.2a85.", "\xff\xff\xa3"}, {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq", "\xa3"}, {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.Sa7shbm4.OzKpvFnX1pQLmQW96oUlCq", "\xa3"}, {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi", "1\xa3" "345"}, {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi", "\xff\xa3" "345"}, {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi", "\xff\xa3" "34" "\xff\xff\xff\xa3" "345"}, {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.o./n25XVfn6oAPaUvHe.Csk4zRfsYPi", "\xff\xa3" "34" "\xff\xff\xff\xa3" "345"}, {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.ZC1JEJ8Z4gPfpe1JOr/oyPXTWl9EFd.", "\xff\xa3" "34" "\xff\xff\xff\xa3" "345"}, {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.nRht2l/HRhr6zmCp9vYUvvsqynflf9e", "\xff\xa3" "345"}, {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.nRht2l/HRhr6zmCp9vYUvvsqynflf9e", "\xff\xa3" "345"}, {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS", "\xa3" "ab"}, {"$2x$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS", "\xa3" "ab"}, {"$2y$05$/OK.fbVrR/bpIqNJ5ianF.6IflQkJytoRVc1yuaNtHfiuq.FRlSIS", "\xa3" "ab"}, {"$2x$05$6bNw2HLQYeqHYyBfLMsv/OiwqTymGIGzFsA4hOTWebfehXHNprcAS", "\xd1\x91"}, {"$2x$05$6bNw2HLQYeqHYyBfLMsv/O9LIGgn8OMzuDoHfof8AQimSGfcSWxnS", "\xd0\xc1\xd2\xcf\xcc\xd8"}, {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.swQOIzjOiJ9GHEPuhEkvqrUyvWhEMx6", "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa\xaa" "chars after 72 are ignored as usual"}, {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.R9xrDjiycxMbQE2bp.vgqlYpW5wx2yy", "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55" "\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55\xaa\x55"}, {"$2a$05$/OK.fbVrR/bpIqNJ5ianF.9tQZzcJfm3uj2NvJ/n5xkhpqLrMpWCe", "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff" "\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff\x55\xaa\xff"}, {"$2a$05$CCCCCCCCCCCCCCCCCCCCC.7uG0VCzI2bS7j6ymqJi9CdcdxiRTWNy", ""}, {"*0", "", "$2a$03$CCCCCCCCCCCCCCCCCCCCC."}, {"*0", "", "$2a$32$CCCCCCCCCCCCCCCCCCCCC."}, {"*0", "", "$2z$05$CCCCCCCCCCCCCCCCCCCCC."}, {"*0", "", "$2`$05$CCCCCCCCCCCCCCCCCCCCC."}, {"*0", "", "$2{$05$CCCCCCCCCCCCCCCCCCCCC."}, {"*1", "", "*0"}, {NULL} }; #define which tests[0] static volatile sig_atomic_t running; static void handle_timer(int signum) { (void) signum; running = 0; } static void *run(void *arg) { unsigned long count = 0; int i = 0; void *data = NULL; int size = 0x12345678; do { const char *hash = tests[i][0]; const char *key = tests[i][1]; const char *setting = tests[i][2]; if (!tests[++i][0]) i = 0; if (setting && strlen(hash) < 30) /* not for benchmark */ continue; if (strcmp(crypt_ra(key, hash, &data, &size), hash)) { printf("%d: FAILED (crypt_ra/%d/%lu)\n", (int)((char *)arg - (char *)0), i, count); free(data); return NULL; } count++; } while (running); free(data); return count + (char *)0; } int main(void) { struct itimerval it; struct tms buf; clock_t clk_tck, start_real, start_virtual, end_real, end_virtual; unsigned long count; void *data; int size; char *setting1, *setting2; int i; #ifdef TEST_THREADS pthread_t t[TEST_THREADS]; void *t_retval; #endif data = NULL; size = 0x12345678; for (i = 0; tests[i][0]; i++) { const char *hash = tests[i][0]; const char *key = tests[i][1]; const char *setting = tests[i][2]; const char *p; int ok = !setting || strlen(hash) >= 30; int o_size; char s_buf[30], o_buf[61]; if (!setting) { memcpy(s_buf, hash, sizeof(s_buf) - 1); s_buf[sizeof(s_buf) - 1] = 0; setting = s_buf; } __set_errno(0); p = crypt(key, setting); if ((!ok && !errno) || strcmp(p, hash)) { printf("FAILED (crypt/%d)\n", i); return 1; } if (ok && strcmp(crypt(key, hash), hash)) { printf("FAILED (crypt/%d)\n", i); return 1; } for (o_size = -1; o_size <= (int)sizeof(o_buf); o_size++) { int ok_n = ok && o_size == (int)sizeof(o_buf); const char *x = "abc"; strcpy(o_buf, x); if (o_size >= 3) { x = "*0"; if (setting[0] == '*' && setting[1] == '0') x = "*1"; } __set_errno(0); p = crypt_rn(key, setting, o_buf, o_size); if ((ok_n && (!p || strcmp(p, hash))) || (!ok_n && (!errno || p || strcmp(o_buf, x)))) { printf("FAILED (crypt_rn/%d)\n", i); return 1; } } __set_errno(0); p = crypt_ra(key, setting, &data, &size); if ((ok && (!p || strcmp(p, hash))) || (!ok && (!errno || p || strcmp((char *)data, hash)))) { printf("FAILED (crypt_ra/%d)\n", i); return 1; } } setting1 = crypt_gensalt(which[0], 12, data, size); if (!setting1 || strncmp(setting1, "$2a$12$", 7)) { puts("FAILED (crypt_gensalt)\n"); return 1; } setting2 = crypt_gensalt_ra(setting1, 12, data, size); if (strcmp(setting1, setting2)) { puts("FAILED (crypt_gensalt_ra/1)\n"); return 1; } (*(char *)data)++; setting1 = crypt_gensalt_ra(setting2, 12, data, size); if (!strcmp(setting1, setting2)) { puts("FAILED (crypt_gensalt_ra/2)\n"); return 1; } free(setting1); free(setting2); free(data); #if defined(_SC_CLK_TCK) || !defined(CLK_TCK) clk_tck = sysconf(_SC_CLK_TCK); #else clk_tck = CLK_TCK; #endif running = 1; signal(SIGALRM, handle_timer); memset(&it, 0, sizeof(it)); it.it_value.tv_sec = 5; setitimer(ITIMER_REAL, &it, NULL); start_real = times(&buf); start_virtual = buf.tms_utime + buf.tms_stime; count = (char *)run((char *)0) - (char *)0; end_real = times(&buf); end_virtual = buf.tms_utime + buf.tms_stime; if (end_virtual == start_virtual) end_virtual++; printf("%.1f c/s real, %.1f c/s virtual\n", (float)count * clk_tck / (end_real - start_real), (float)count * clk_tck / (end_virtual - start_virtual)); #ifdef TEST_THREADS running = 1; it.it_value.tv_sec = 60; setitimer(ITIMER_REAL, &it, NULL); start_real = times(&buf); for (i = 0; i < TEST_THREADS; i++) if (pthread_create(&t[i], NULL, run, i + (char *)0)) { perror("pthread_create"); return 1; } for (i = 0; i < TEST_THREADS; i++) { if (pthread_join(t[i], &t_retval)) { perror("pthread_join"); continue; } if (!t_retval) continue; count = (char *)t_retval - (char *)0; end_real = times(&buf); printf("%d: %.1f c/s real\n", i, (float)count * clk_tck / (end_real - start_real)); } #endif return 0; } #endif
15,265
7,631
/* Copyright(c) 2002 - 2016 Lee Salzman 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. */ // Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Nazara Engine - Network module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_ENETPEER_HPP #define NAZARA_ENETPEER_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Core/Bitset.hpp> #include <Nazara/Core/MovablePtr.hpp> #include <Nazara/Network/ENetPacket.hpp> #include <Nazara/Network/ENetProtocol.hpp> #include <Nazara/Network/IpAddress.hpp> #include <array> #include <list> #include <random> #include <vector> namespace Nz { class ENetHost; class NAZARA_NETWORK_API ENetPeer { friend ENetHost; friend struct PacketRef; public: inline ENetPeer(ENetHost* host, UInt16 peerId); ENetPeer(const ENetPeer&) = delete; ENetPeer(ENetPeer&&) = default; ~ENetPeer() = default; void Disconnect(UInt32 data); void DisconnectLater(UInt32 data); void DisconnectNow(UInt32 data); inline const IpAddress& GetAddress() const; inline UInt32 GetLastReceiveTime() const; inline UInt32 GetMtu() const; inline UInt32 GetPacketThrottleAcceleration() const; inline UInt32 GetPacketThrottleDeceleration() const; inline UInt32 GetPacketThrottleInterval() const; inline UInt16 GetPeerId() const; inline UInt32 GetRoundTripTime() const; inline ENetPeerState GetState() const; inline UInt64 GetTotalByteReceived() const; inline UInt64 GetTotalByteSent() const; inline UInt32 GetTotalPacketReceived() const; inline UInt32 GetTotalPacketLost() const; inline UInt32 GetTotalPacketSent() const; inline bool HasPendingCommands(); inline bool IsConnected() const; inline bool IsSimulationEnabled() const; void Ping(); bool Receive(ENetPacketRef* packet, UInt8* channelId); void Reset(); bool Send(UInt8 channelId, ENetPacketRef packetRef); bool Send(UInt8 channelId, ENetPacketFlags flags, NetPacket&& packet); void SimulateNetwork(double packetLossProbability, UInt16 minDelay, UInt16 maxDelay); void ThrottleConfigure(UInt32 interval, UInt32 acceleration, UInt32 deceleration); ENetPeer& operator=(const ENetPeer&) = delete; ENetPeer& operator=(ENetPeer&&) = default; private: void InitIncoming(std::size_t channelCount, const IpAddress& address, ENetProtocolConnect& incomingCommand); void InitOutgoing(std::size_t channelCount, const IpAddress& address, UInt32 connectId, UInt32 windowSize); struct Channel; struct IncomingCommmand; struct OutgoingCommand; inline void ChangeState(ENetPeerState state); bool CheckTimeouts(ENetEvent* event); void DispatchState(ENetPeerState state); void DispatchIncomingReliableCommands(Channel& channel); void DispatchIncomingUnreliableCommands(Channel& channel); bool HandleAcknowledge(const ENetProtocol* command, ENetEvent* event); bool HandleBandwidthLimit(const ENetProtocol* command); bool HandleDisconnect(const ENetProtocol* command); bool HandlePing(const ENetProtocol* command); bool HandleSendFragment(const ENetProtocol* command, UInt8** data); bool HandleSendReliable(const ENetProtocol* command, UInt8** data); bool HandleSendUnreliable(const ENetProtocol* command, UInt8** data); bool HandleSendUnreliableFragment(const ENetProtocol* command, UInt8** data); bool HandleSendUnsequenced(const ENetProtocol* command, UInt8** data); bool HandleThrottleConfigure(const ENetProtocol* command); bool HandleVerifyConnect(const ENetProtocol* command, ENetEvent* event); void OnConnect(); void OnDisconnect(); ENetProtocolCommand RemoveSentReliableCommand(UInt16 reliableSequenceNumber, UInt8 channelId); void RemoveSentUnreliableCommands(); void ResetQueues(); bool QueueAcknowledgement(ENetProtocol* command, UInt16 sentTime); IncomingCommmand* QueueIncomingCommand(const ENetProtocol& command, const void* data, std::size_t dataLength, UInt32 flags, UInt32 fragmentCount); inline void QueueOutgoingCommand(ENetProtocol& command); void QueueOutgoingCommand(ENetProtocol& command, ENetPacketRef packet, UInt32 offset, UInt16 length); void SetupOutgoingCommand(OutgoingCommand& outgoingCommand); int Throttle(UInt32 rtt); struct Acknowledgement { ENetProtocol command; UInt32 sentTime; }; struct Channel { Channel() { incomingReliableSequenceNumber = 0; incomingUnreliableSequenceNumber = 0; outgoingReliableSequenceNumber = 0; outgoingUnreliableSequenceNumber = 0; usedReliableWindows = 0; reliableWindows.fill(0); } std::array<UInt16, ENetPeer_ReliableWindows> reliableWindows; std::list<IncomingCommmand> incomingReliableCommands; std::list<IncomingCommmand> incomingUnreliableCommands; UInt16 incomingReliableSequenceNumber; UInt16 incomingUnreliableSequenceNumber; UInt16 outgoingReliableSequenceNumber; UInt16 outgoingUnreliableSequenceNumber; UInt16 usedReliableWindows; }; struct IncomingCommmand { ENetProtocol command; Bitset<> fragments; ENetPacketRef packet; UInt16 reliableSequenceNumber; UInt16 unreliableSequenceNumber; UInt32 fragmentsRemaining; }; struct OutgoingCommand { ENetProtocol command; ENetPacketRef packet; UInt16 fragmentLength; UInt16 reliableSequenceNumber; UInt16 sendAttempts; UInt16 unreliableSequenceNumber; UInt32 fragmentOffset; UInt32 roundTripTimeout; UInt32 roundTripTimeoutLimit; UInt32 sentTime; }; static constexpr std::size_t unsequencedWindow = ENetPeer_ReliableWindowSize / 32; MovablePtr<ENetHost> m_host; IpAddress m_address; //< Internet address of the peer std::array<UInt32, unsequencedWindow> m_unsequencedWindow; std::bernoulli_distribution m_packetLossProbability; std::list<IncomingCommmand> m_dispatchedCommands; std::list<OutgoingCommand> m_outgoingReliableCommands; std::list<OutgoingCommand> m_outgoingUnreliableCommands; std::list<OutgoingCommand> m_sentReliableCommands; std::list<OutgoingCommand> m_sentUnreliableCommands; std::size_t m_totalWaitingData; std::uniform_int_distribution<UInt16> m_packetDelayDistribution; std::vector<Acknowledgement> m_acknowledgements; std::vector<Channel> m_channels; ENetPeerState m_state; UInt8 m_incomingSessionID; UInt8 m_outgoingSessionID; UInt16 m_incomingPeerID; UInt16 m_incomingUnsequencedGroup; UInt16 m_outgoingPeerID; UInt16 m_outgoingReliableSequenceNumber; UInt16 m_outgoingUnsequencedGroup; UInt32 m_connectID; UInt32 m_earliestTimeout; UInt32 m_eventData; UInt32 m_highestRoundTripTimeVariance; UInt32 m_incomingBandwidth; /**< Downstream bandwidth of the client in bytes/second */ UInt32 m_incomingBandwidthThrottleEpoch; UInt32 m_incomingDataTotal; UInt32 m_lastReceiveTime; UInt32 m_lastRoundTripTime; UInt32 m_lastRoundTripTimeVariance; UInt32 m_lastSendTime; UInt32 m_lowestRoundTripTime; UInt32 m_mtu; UInt32 m_nextTimeout; UInt32 m_outgoingBandwidth; /**< Upstream bandwidth of the client in bytes/second */ UInt32 m_outgoingBandwidthThrottleEpoch; UInt32 m_outgoingDataTotal; UInt32 m_packetLoss; /**< mean packet loss of reliable packets as a ratio with respect to the constant ENET_PEER_PACKET_LOSS_SCALE */ UInt32 m_packetLossEpoch; UInt32 m_packetLossVariance; UInt32 m_packetThrottle; UInt32 m_packetThrottleAcceleration; UInt32 m_packetThrottleCounter; UInt32 m_packetThrottleDeceleration; UInt32 m_packetThrottleEpoch; UInt32 m_packetThrottleInterval; UInt32 m_packetThrottleLimit; UInt32 m_packetsLost; UInt32 m_packetsSent; UInt32 m_pingInterval; UInt32 m_reliableDataInTransit; UInt32 m_roundTripTime; /**< mean round trip time (RTT), in milliseconds, between sending a reliable packet and receiving its acknowledgment */ UInt32 m_roundTripTimeVariance; UInt32 m_timeoutLimit; UInt32 m_timeoutMaximum; UInt32 m_timeoutMinimum; UInt32 m_totalPacketReceived; UInt32 m_totalPacketLost; UInt32 m_totalPacketSent; UInt32 m_windowSize; UInt64 m_totalByteReceived; UInt64 m_totalByteSent; bool m_isSimulationEnabled; }; } #include <Nazara/Network/ENetPeer.inl> #endif // NAZARA_ENETPEER_HPP
11,421
3,851
/* Copyright 2012 - Le Padellec Sylvain 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 <stdio.h> #include <cmath> #include "EyeAnglesTester.h" #include "Misc/EntityProps.h" #include "Systems/BanRequest.h" EyeAnglesTester::EyeAnglesTester(void) : BaseTesterSystem("EyeAnglesTester"), playerdata_class(), PlayerRunCommandHookListener(), UserMessageHookListener(), Singleton() { } EyeAnglesTester::~EyeAnglesTester(void) { Unload(); } void EyeAnglesTester::Init() { InitDataStruct(); } void EyeAnglesTester::Load() { for (PlayerHandler::iterator it(PlayerHandler::begin()); it != PlayerHandler::end(); ++it) { ResetPlayerDataStructByIndex(it.GetIndex()); } PlayerRunCommandHookListener::RegisterPlayerRunCommandHookListener(this, SystemPriority::EyeAnglesTester); UserMessageHookListener::RegisterUserMessageHookListener(this); } void EyeAnglesTester::Unload() { PlayerRunCommandHookListener::RemovePlayerRunCommandHookListener(this); UserMessageHookListener::RemoveUserMessageHookListener(this); } bool EyeAnglesTester::GotJob() const { // Create a filter ProcessFilter::HumanAtLeastConnected const filter_class; // Initiate the iterator at the first match in the filter PlayerHandler::iterator it(&filter_class); // Return if we have job to do or not ... return it != PlayerHandler::end(); } PlayerRunCommandRet EyeAnglesTester::RT_PlayerRunCommandCallback(PlayerHandler::iterator ph, void *const pCmd, double const &curtime) { int const *const flags(g_EntityProps.GetPropValue<int, PROP_FLAGS>(ph->GetEdict())); EyeAngleInfoT *playerData(GetPlayerDataStructByIndex(ph.GetIndex())); playerData->x.abs_value = fabs(playerData->x.value = static_cast<SourceSdk::CUserCmd_csgo *>(pCmd)->viewangles.x); playerData->y.abs_value = fabs(playerData->y.value = static_cast<SourceSdk::CUserCmd_csgo *>(pCmd)->viewangles.y); playerData->z.abs_value = fabs(playerData->z.value = static_cast<SourceSdk::CUserCmd_csgo *>(pCmd)->viewangles.z); /* FL_FROZEN (1 << 5) FL_ATCONTROLS (1 << 6) */ if ((*flags & (3 << 5)) == 0) { if (playerData->x.abs_value > 89.0f && playerData->past_x.abs_value > 89.0f && playerData->x.value != playerData->past_x.value) { ++playerData->x.detectionsCount; //drop_cmd = PlayerRunCommandRet::INERT; if (playerData->x.lastDetectionPrintTime + ANTIFLOOD_LOGGING_TIME < curtime) { playerData->x.lastDetectionPrintTime = curtime; if (playerData->x.detectionsCount > 5) { ProcessDetectionAndTakeAction<Detection_EyeAngleX::data_type>(Detection_EyeAngleX(), playerData, ph, this); } } } if (playerData->y.abs_value > 180.0f && playerData->past_y.abs_value > 180.0f && playerData->y.value != playerData->past_y.value) { ++playerData->y.detectionsCount; //drop_cmd = PlayerRunCommandRet::INERT; if (playerData->y.lastDetectionPrintTime + ANTIFLOOD_LOGGING_TIME < curtime) { playerData->y.lastDetectionPrintTime = curtime; if (playerData->y.detectionsCount > 5) { ProcessDetectionAndTakeAction<Detection_EyeAngleY::data_type>(Detection_EyeAngleY(), playerData, ph, this); } } } if (playerData->z.abs_value > 0.5f && playerData->past_z.abs_value > 0.5f && playerData->z.value != playerData->past_z.value) { if (!Helpers::IsInt(playerData->z.value)) // Don't detect ""fun"" plugins { ++playerData->z.detectionsCount; //drop_cmd = PlayerRunCommandRet::INERT; if (playerData->z.lastDetectionPrintTime + ANTIFLOOD_LOGGING_TIME < curtime) { playerData->z.lastDetectionPrintTime = curtime; if (playerData->z.detectionsCount > 5) { ProcessDetectionAndTakeAction<Detection_EyeAngleZ::data_type>(Detection_EyeAngleZ(), playerData, ph, this); } } } } } playerData->past_x = playerData->x; playerData->past_y = playerData->y; playerData->past_z = playerData->z; return PlayerRunCommandRet::CONTINUE; } bool EyeAnglesTester::RT_SendUserMessageCallback(SourceSdk::IRecipientFilter const &filter, int const message_id, google::protobuf::Message const &buffer) { DebugMessage(Helpers::format("EyeAnglesTester::RT_SendUserMessageCallback : %d, %s", message_id, buffer.DebugString().c_str())); return false; } bool EyeAnglesTester::RT_UserMessageBeginCallback(SourceSdk::IRecipientFilter const *const filter, int const message_id) { return false; } void EyeAnglesTester::RT_MessageEndCallback(SourceSdk::IRecipientFilter const *const filter, int const message_id, SourceSdk::bf_write *buffer) { } EyeAnglesTester g_EyeAnglesTester; basic_string Detection_EyeAngle::GetDataDump() { return Helpers::format( ":::: EyeAngleInfo {\n" ":::::::: EyeAngleX {\n" ":::::::::::: Angle : %f,\n" ":::::::::::: Previous Angle : %f,\n" ":::::::::::: Detections Count : %u\n" ":::::::: }," "\n:::::::: EyeAngleY {\n" ":::::::::::: Angle : %f,\n" ":::::::::::: Previous Angle : %f,\n" ":::::::::::: Detections Count : %u\n" ":::::::: },\n" ":::::::: EyeAngleZ {\n" ":::::::::::: Angle : %f,\n" ":::::::::::: Previous Angle : %f,\n" ":::::::::::: Detections Count : %u\n" ":::::::: }\n" ":::: }", GetDataStruct()->x.value, GetDataStruct()->past_x.value, GetDataStruct()->x.detectionsCount, GetDataStruct()->y.value, GetDataStruct()->past_y.value, GetDataStruct()->y.detectionsCount, GetDataStruct()->z.value, GetDataStruct()->past_z.value, GetDataStruct()->z.detectionsCount); } basic_string Detection_EyeAngleX::GetDetectionLogMessage() { if (Helpers::IsInt(GetDataStruct()->x.value)) { return "Anti-Aim"; } else { return "No recoil"; } } basic_string Detection_EyeAngleY::GetDetectionLogMessage() { if (Helpers::IsInt(GetDataStruct()->y.value)) { return "Anti-Aim"; } else { return "No recoil"; } } basic_string Detection_EyeAngleZ::GetDetectionLogMessage() { if (Helpers::IsInt(GetDataStruct()->z.value)) { return "Anti-Aim"; } else { return "No recoil"; } }
6,483
2,609
class Solution { public: int maxSubArray(vector<int>& nums) { int maxSum = INT_MIN; int sum = 0; for (int i = 0; i < nums.size(); i++) { sum = std::max(sum + nums[i], nums[i]); maxSum = std::max(maxSum, sum); } return maxSum; } };
320
113
#pragma once #include <memory> #include <optional> #include "Interpolations.hpp" #include <glm/vec2.hpp> #include <ngf/System/TimeSpan.h> #include <ngf/Graphics/Rect.h> namespace ng { class Engine; class Camera { public: Camera(); virtual ~Camera(); /// @brief Pans the camera to the target position in a specified time using a given interpolation. /// \param target Position where the camera needs to go. /// \param time Time needed for the camera to reach the target position. /// \param interpolation Interpolation method to use between the current position and the target position. void panTo(glm::vec2 target, ngf::TimeSpan time, InterpolationMethod interpolation); /// @brief Sets the position of the camera. /// @details The position is the center of the camera. /// \param at Position of the camera to set. void at(const glm::vec2 &at); /// @brief Gets the position of the camera. /// @details The position is the center of the camera. /// \return The current position of the camera. [[nodiscard]] glm::vec2 getAt() const; /// @brief Gets the rectangle of the camera. [[nodiscard]] ngf::frect getRect() const; void move(const glm::vec2 &offset); [[nodiscard]] bool isMoving() const; void setBounds(const ngf::irect &cameraBounds); [[nodiscard]] std::optional<ngf::irect> getBounds() const; void resetBounds(); void setEngine(Engine *pEngine); void update(const ngf::TimeSpan &elapsed); private: struct Impl; std::unique_ptr<Impl> m_pImpl; }; } // namespace ng
1,528
474
class Solution { public:     bool dfs(vector<vector<char>> &board, int row, int col, string &word, int wc) {    if(wc == (int) word.length()){        return true;   }    if(row < 0 or row >= board.size() or col < 0 or col >= board[row].size() or board[row][col] != word[wc])   {        return false;   }    {        char temp = board[row][col];        board[row][col] = ' ';        bool found = (dfs(board, row+1, col, word, wc+1) || dfs(board, row-1, col, word, wc+1)                      || dfs(board, row, col+1, word, wc+1) || dfs(board, row, col-1, word, wc+1));        board[row][col] = temp;        return found;    } } ​        bool exist(vector<vector<char>>& board, string word) {                int M = board.size(), N = board[0].size();        if(board.empty()){            return false;       }        for(int row = 0; row < M; row++){            for(int col = 0; col < N; col++){                if(board[row][col] == word[0] && dfs(board, row, col, word, 0)){                    return true;               }           }       }        return false;   } };
1,110
484
#include <stdio.h> #include <iostream> #include "Graph.h" #include "IntegerSet.h" #include "Queue.h" SparseGraph::SparseGraph(int n) : Graph(n) { nodes = new Node[numNodes]; } void SparseGraph::addEdge(int v1, int v2) { nodes[v1].edge.append(v2); nodes[v2].edge.append(v1); } bool SparseGraph::isAdjacent(int v1, int v2) { List::iterator it = nodes[v1].edge.begin(); while (!it.end()) { if (it.getItem() == v2) { return true; } it.increment(); } return false; } DenseGraph::DenseGraph(int n) : Graph(n) { edges = new bool[numNodes * numNodes]; for (int i = 0; i < numNodes * numNodes; i++) edges[i] = false; } void DenseGraph::addEdge(int v1, int v2) { edges[v1 * numNodes + v2] = true; edges[v2 * numNodes + v1] = true; } bool DenseGraph::isAdjacent(int v1, int v2) { return edges[v1 * numNodes + v2]; } bool doesPathExist(Graph &g, int *path, int length) { for (int i = 0; i < length - 1; i++) { if (!g.isAdjacent(path[i], path[i + 1])) return false; } return true; } void visit(int node) { printf("%d ", node); } void BreadthFirstSearch(SparseGraph &graph, int start) { IntegerSetHT discovered(1000); Queue frontier; frontier.push(start); discovered.insert(start); while (!frontier.empty()) { int node = frontier.peek(); visit(node); SparseGraph::adjacency_iterator it = graph.getAdjacencyList(node); while (!it.end()) { int j = it.getItem(); if (!discovered.search(j)) { frontier.push(j); discovered.insert(j); } it.increment(); } frontier.pop(); } } void DepthFirstSearch(SparseGraph &g, IntegerSet &visitedSet, int node){ if ( !visitedSet.search(node) ) { visit(node); // take action upon visit to node visitedSet.insert(node); for (SparseGraph::adjacency_iterator it=g.getAdjacencyList(node); !it.end(); it.increment()) DepthFirstSearch(g,visitedSet,it.getItem()); } // end if } // end function class DepthFirstSearch { protected: SparseGraph &g; IntegerSetHT visitedSet; void dfs_helper(int node) { //modified code from prior slide if ( !visitedSet.search(node) ) { visit(node); // take action upon visit to node visitedSet.insert(node); for (SparseGraph::adjacency_iterator it=g.getAdjacencyList(node); !it.end(); it.increment()) dfs_helper(it.getItem()); } } public: DepthFirstSearch(SparseGraph &ag):g(ag),visitedSet(1000){}; void run(int start) { dfs_helper(start); } virtual void visit(int node){}// extend this class to customize visit }; class PrintDFSOrder : public DepthFirstSearch { public: PrintDFSOrder(SparseGraph &g):DepthFirstSearch(g){} void visit(int node) override { printf("%d,",node); }; }; template <class F> class DFS { protected: SparseGraph &g; IntegerSetHT visitedSet; F visit; // functor object void dfs_helper(int node) { if ( !visitedSet.search(node) ) { visit(node); // take action upon visit to node visitedSet.insert(node); for (SparseGraph::adjacency_iterator it=g.getAdjacencyList(node); !it.end(); it.increment()) dfs_helper(it.getItem()); } } public: DFS(SparseGraph &ag):g(ag),visitedSet(1000){}; void run(int start) { dfs_helper(start); } }; class Visit { public: void operator() (int node) { printf("%d-",node); } }; int main() { SparseGraph g(14); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(1, 4); g.addEdge(3, 5); g.addEdge(2, 6); g.addEdge(3, 6); g.addEdge(2, 7); g.addEdge(1, 8); g.addEdge(7, 8); g.addEdge(1, 9); g.addEdge(4, 10); g.addEdge(6, 11); g.addEdge(7, 12); g.addEdge(8, 13); /* int path[3] = {0, 1, 9}; if (doesPathExist(g, path, 3)) printf("Exists!\n");*/ printf("BFS(0)="); BreadthFirstSearch(g, 0); printf("\nBFS(13)="); BreadthFirstSearch(g, 13); IntegerSetHT set(1000); printf("\nDFS(0)="); DepthFirstSearch(g,set,0); printf("\n"); PrintDFSOrder print(g); printf("\nDFS(0)="); print.run(0); DFS<Visit> print2(g); printf("\nDFS(0)="); print2.run(0); return 0; }
4,166
1,694
#ifndef __TINYSTL_HASH_MAP__ #define __TINYSTL_HASH_MAP__ #include "hash_table.hpp" #include "allocator.hpp" #include "utils.hpp" namespace TinySTL { template <typename Key, typename Value> static bool isEqualKey(const Pair<const Key, Value> &a, const Pair<const Key, Value> &b) { return a.first == b.first; } template <typename Key, typename Value> static unsigned long hashByKey(const Pair<const Key, Value> &a) { return Hash<Key>(a.first); } template <typename Key, typename Value, class Alloc = Allocator<Pair<const Key, Value>>> class HashMap : public HashTable<Pair<const Key, Value>, Alloc> { public: class Iterator : public ForwardIterator { public: bool operator ==(const Iterator &I) { return (this->data == I.data && this->e == I.e); } bool operator !=(const Iterator &I) { return (this->data != I.data || this->e != I.e); } Pair<const Key, Value> &operator *() { return *(e.second); } Pair<const Key, Value> *operator ->() { return &(*(e.second)); } Iterator operator ++() { advance(); return *this; } Iterator operator ++(int dummy) { auto temp = *this; advance(); return temp; } Iterator(HashMap<Key, Value, Alloc> *_data, typename HashMap<Key, Value>::HashEntry _e) : data(_data), e(_e) {} private: HashMap<Key, Value, Alloc> *data; typename HashMap<Key, Value>::HashEntry e; void advance() { e = data->findNext(e); } friend class HashMap<Key, Value>; }; // iterator to the beginning Iterator begin() { return Iterator(this, base::findBegin()); } // iterator to the end Iterator end() { return Iterator(this, base::findEnd()); } // iterator to element with specific key Iterator find(const Key &k) { auto kv = MakePair<const Key, Value>(k, Value()); return Iterator(this, base::find(kv)); } // access element Value &operator [](const Key &k) { auto iter = find(k); if (iter == this->end()) { insert(k, Value()); iter = find(k); } return iter->second; } // insert wrapper void insert(const Key &k, const Value &v) { base::insert(MakePair<const Key, Value>(k, v)); } // erase wrapper void erase(const Key &k) { base::erase(MakePair<const Key, Value>(k, Value())); } // count wrapper unsigned int count(const Key &k) { return base::count(MakePair<const Key, Value>(k, Value())); } HashMap(bool (*_pred)(const Pair<const Key, Value> &a, const Pair<const Key, Value> &b) = isEqualKey<Key, Value>, unsigned long (*_hash)(const Pair<const Key, Value> &val) = hashByKey<Key, Value>, double _alpha = 1.0) : HashTable<Pair<const Key, Value>, Alloc>::HashTable(_pred, _hash, _alpha) {} private: typedef HashTable<Pair<const Key, Value>> base; friend class Iterator; }; }; #endif
3,532
976
/******************************************************************************* Copyright 2006-2012 Lukas Käll <lukas.kall@scilifelab.se> 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 <iostream> #ifdef WIN32 #include <float.h> #define isfinite _finite #endif #include <math.h> #include <vector> #include <string> using namespace std; #include "Normalizer.h" #include "StdvNormalizer.h" #include "Globals.h" StdvNormalizer::StdvNormalizer() { } StdvNormalizer::~StdvNormalizer() { } void StdvNormalizer::unnormalizeweight(const std::vector<double>& in, std::vector<double>& out) { double sum = 0; unsigned int i = 0; for (; i < numFeatures; i++) { out[i] = in[i] / div[i]; sum += sub[i] * in[i] / div[i]; } out[i] = in[i] - sum; } void StdvNormalizer::normalizeweight(const std::vector<double>& in, std::vector<double>& out) { double sum = 0; size_t i = 0; for (; i < numFeatures; i++) { out[i] = in[i] * div[i]; sum += sub[i] * in[i]; } out[i] = in[i] + sum; } void StdvNormalizer::setSet(std::vector<double*>& featuresV, std::vector<double*>& rtFeaturesV, size_t nf, size_t nrf) { numFeatures = nf; numRetentionFeatures = nrf; sub.resize(nf + nrf, 0.0); div.resize(nf + nrf, 0.0); double n = 0.0; double* features; size_t ix; vector<double*>::iterator it = featuresV.begin(); for (; it != featuresV.end(); ++it) { features = *it; n++; for (ix = 0; ix < numFeatures; ++ix) { sub[ix] += features[ix]; } } for (it = rtFeaturesV.begin(); it != rtFeaturesV.end(); ++it) { features = *it; for (ix = numFeatures; ix < numFeatures + numRetentionFeatures; ++ix) { sub[ix] += features[ix - numFeatures]; } } if (VERB > 2) { cerr.precision(2); cerr << "Normalization factors" << endl << "Avg "; } for (ix = 0; ix < numFeatures + numRetentionFeatures; ++ix) { if (n > 0.0) { sub[ix] /= n; } if (VERB > 2) { cerr << "\t" << sub[ix]; } } for (it = featuresV.begin(); it != featuresV.end(); ++it) { features = *it; for (ix = 0; ix < numFeatures; ++ix) { if (!isfinite(features[ix])) { cerr << "Reached strange feature with val=" << features[ix] << " at col=" << ix << endl; } double d = features[ix] - sub[ix]; div[ix] += d * d; } } for (it = rtFeaturesV.begin(); it != rtFeaturesV.end(); ++it) { features = *it; for (ix = numFeatures; ix < numFeatures + numRetentionFeatures; ++ix) { if (!isfinite(features[ix-numFeatures])) { cerr << "Reached strange feature with val=" << features[ix - numFeatures] << " at col=" << ix << endl; } double d = features[ix - numFeatures] - sub[ix]; div[ix] += d * d; } } if (VERB > 2) { cerr << endl << "Stdv"; } for (ix = 0; ix < numFeatures + numRetentionFeatures; ++ix) { if (div[ix] <= 0 || n == 0) { div[ix] = 1.0; } else { div[ix] = sqrt(div[ix] / n); } if (VERB > 2) { cerr << "\t" << div[ix]; } } if (VERB > 2) { cerr << endl; } } void StdvNormalizer::updateSet(vector<double*> & featuresV, size_t offset, size_t numFeatures) { double n = 0.0; double* features; size_t ix; vector<double*>::iterator it = featuresV.begin(); for (; it != featuresV.end(); ++it) { features = *it; n++; for (ix = 0; ix < numFeatures; ++ix) { sub[offset + ix] += features[ix]; } } if (VERB > 2) { cerr.precision(2); cerr << "Normalization factors" << endl << "Avg "; } for (ix = 0; ix < numFeatures; ++ix) { if (n > 0.0) { sub[offset + ix] /= n; } if (VERB > 2) { cerr << "\t" << sub[offset + ix]; } } for (it = featuresV.begin(); it != featuresV.end(); ++it) { features = *it; for (ix = 0; ix < numFeatures; ++ix) { if (!isfinite(features[ix])) { cerr << "Reached strange feature with val=" << features[ix] << " at col=" << ix << endl; } double d = features[ix] - sub[offset + ix]; div[offset + ix] += d * d; } } if (VERB > 2) { cerr << endl << "Stdv"; } for (ix = 0; ix < numFeatures; ++ix) { if (div[offset + ix] <= 0 || n == 0) { div[offset + ix] = 1.0; } else { div[offset + ix] = sqrt(div[offset + ix] / n); } if (VERB > 2) { cerr << "\t" << div[offset + ix]; } } if (VERB > 2) { cerr << endl; } }
5,115
1,981
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/iai/v20180301/model/GetPersonBaseInfoResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Iai::V20180301::Model; using namespace rapidjson; using namespace std; GetPersonBaseInfoResponse::GetPersonBaseInfoResponse() : m_personNameHasBeenSet(false), m_genderHasBeenSet(false), m_faceIdsHasBeenSet(false) { } CoreInternalOutcome GetPersonBaseInfoResponse::Deserialize(const string &payload) { Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Error("response `Response` is null or not object")); } Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("PersonName") && !rsp["PersonName"].IsNull()) { if (!rsp["PersonName"].IsString()) { return CoreInternalOutcome(Error("response `PersonName` IsString=false incorrectly").SetRequestId(requestId)); } m_personName = string(rsp["PersonName"].GetString()); m_personNameHasBeenSet = true; } if (rsp.HasMember("Gender") && !rsp["Gender"].IsNull()) { if (!rsp["Gender"].IsInt64()) { return CoreInternalOutcome(Error("response `Gender` IsInt64=false incorrectly").SetRequestId(requestId)); } m_gender = rsp["Gender"].GetInt64(); m_genderHasBeenSet = true; } if (rsp.HasMember("FaceIds") && !rsp["FaceIds"].IsNull()) { if (!rsp["FaceIds"].IsArray()) return CoreInternalOutcome(Error("response `FaceIds` is not array type")); const Value &tmpValue = rsp["FaceIds"]; for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_faceIds.push_back((*itr).GetString()); } m_faceIdsHasBeenSet = true; } return CoreInternalOutcome(true); } string GetPersonBaseInfoResponse::GetPersonName() const { return m_personName; } bool GetPersonBaseInfoResponse::PersonNameHasBeenSet() const { return m_personNameHasBeenSet; } int64_t GetPersonBaseInfoResponse::GetGender() const { return m_gender; } bool GetPersonBaseInfoResponse::GenderHasBeenSet() const { return m_genderHasBeenSet; } vector<string> GetPersonBaseInfoResponse::GetFaceIds() const { return m_faceIds; } bool GetPersonBaseInfoResponse::FaceIdsHasBeenSet() const { return m_faceIdsHasBeenSet; }
4,241
1,339
#include "pch.h" #include "LoadingWrapper.h" using namespace std; LoadingWrapper::LoadingWrapper(function<void()> ctor, function<void()> dtor) : _dtor(dtor) { Schedule(ctor); } future<void> LoadingWrapper::Schedule(function<void()> fn) { auto disp = Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher; co_await disp->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([fn]() { fn(); })); } LoadingWrapper::~LoadingWrapper() { Schedule(_dtor); }
542
185
class Solution { public: // left记录当前节点的上一个节点的值 long long left = LONG_MIN; bool XXX(TreeNode* root) { return XXX2(root, NULL, NULL); } bool XXX1(TreeNode* root) { if(!root) return true; if(XXX(root->left)) { // 如果上一个节点的值小于当前节点,说明满足升序,继续遍历,否则返回false if(root->val > left) { left = root->val; return XXX(root->right); } } return false; } bool XXX2(TreeNode* root, TreeNode* min, TreeNode* max) { if(!root) return true; if(min && root->val <= min->val) return false; if(max && root->val >= max->val) return false; // 判断左子树时,值不能超过root;判断右子树,值不能小于root return XXX2(root->left, min, root) && XXX2(root->right, root, max); } };
800
318
/* * Copyright 2011 Bjorn Fahller <bjorn@fahller.se> * All rights reserved * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <crpcut.hpp> namespace crpcut { collate_result ::collate_result(const char *refstr, std::string comp, const std::locale& l) : r(refstr), intl(comp), locale(l), side(right) { } collate_result ::collate_result(const collate_result& o) : r(o.r), intl(o.intl), locale(o.locale), side(o.side) { } collate_result ::operator const collate_result::comparator*() const { return operator()(); } const collate_result::comparator* collate_result ::operator()() const { return reinterpret_cast<const comparator*>(r ? 0 : this); } collate_result& collate_result ::set_lh() { side = left; return *this; } std::ostream &operator<<(std::ostream& os, const collate_result &obj) { static const char rs[] = "\"\n" " and right hand value = \""; os << "Failed in locale \"" << obj.locale.name() << "\"\n" " with left hand value = \""; if (obj.side == collate_result::right) { os << obj.intl << rs << obj.r << "\""; } else { os << obj.r << rs << obj.intl << "\""; } return os; } }
2,524
923
#include "stdafx.h" #include "Script.h" #include "Object.h" #include "Mesh.h" #include "Transform.h" cg::Script::Script(Object *pObj) :pObject(pObj), transform(pObj->transform), pMesh(pObj->pMesh) {}
201
85
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <af/defines.h> #include <backend.hpp> namespace cuda { template<typename T> struct Param { T *ptr; dim_type dims[4]; dim_type strides[4]; }; template<typename T> class CParam { public: const T *ptr; dim_type dims[4]; dim_type strides[4]; __DH__ CParam(const T *iptr, const dim_type *idims, const dim_type *istrides) : ptr(iptr) { for (int i = 0; i < 4; i++) { dims[i] = idims[i]; strides[i] = istrides[i]; } } __DH__ CParam(Param<T> &in) : ptr(in.ptr) { for (int i = 0; i < 4; i++) { dims[i] = in.dims[i]; strides[i] = in.strides[i]; } } __DH__ ~CParam() {} }; }
1,065
391
/* * 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 "include/core/SkTypes.h" #if defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS) #ifdef SK_BUILD_FOR_MAC #import <ApplicationServices/ApplicationServices.h> #endif #ifdef SK_BUILD_FOR_IOS #include <CoreText/CoreText.h> #include <CoreText/CTFontManager.h> #include <CoreGraphics/CoreGraphics.h> #include <CoreFoundation/CoreFoundation.h> #include <dlfcn.h> #endif #include "include/core/SkData.h" #include "include/core/SkFontArguments.h" #include "include/core/SkFontMgr.h" #include "include/core/SkFontStyle.h" #include "include/core/SkStream.h" #include "include/core/SkString.h" #include "include/core/SkTypeface.h" #include "include/ports/SkFontMgr_mac_ct.h" #include "include/private/SkFixed.h" #include "include/private/SkOnce.h" #include "include/private/SkTPin.h" #include "include/private/SkTemplates.h" #include "include/private/SkTo.h" #include "src/core/SkFontDescriptor.h" #include "src/ports/SkTypeface_mac_ct.h" #include "src/utils/SkUTF.h" #include <string.h> #include <memory> #if (defined(SK_BUILD_FOR_IOS) && defined(__IPHONE_14_0) && \ __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_14_0) || \ (defined(SK_BUILD_FOR_MAC) && defined(__MAC_11_0) && \ __MAC_OS_VERSION_MIN_REQUIRED >= __MAC_11_0) static uint32_t SkGetCoreTextVersion() { // If compiling for iOS 14.0+ or macOS 11.0+, the CoreText version number // must be derived from the OS version number. static const uint32_t kCoreTextVersionNEWER = 0x000D0000; return kCoreTextVersionNEWER; } #else static uint32_t SkGetCoreTextVersion() { // Check for CoreText availability before calling CTGetCoreTextVersion(). static const bool kCoreTextIsAvailable = (&CTGetCoreTextVersion != nullptr); if (kCoreTextIsAvailable) { return CTGetCoreTextVersion(); } // Default to a value that's smaller than any known CoreText version. static const uint32_t kCoreTextVersionUNKNOWN = 0; return kCoreTextVersionUNKNOWN; } #endif static SkUniqueCFRef<CFStringRef> make_CFString(const char s[]) { return SkUniqueCFRef<CFStringRef>(CFStringCreateWithCString(nullptr, s, kCFStringEncodingUTF8)); } /** Creates a typeface from a descriptor, searching the cache. */ static sk_sp<SkTypeface> create_from_desc(CTFontDescriptorRef desc) { SkUniqueCFRef<CTFontRef> ctFont(CTFontCreateWithFontDescriptor(desc, 0, nullptr)); if (!ctFont) { return nullptr; } return SkTypeface_Mac::Make(std::move(ctFont), OpszVariation(), nullptr); } static SkUniqueCFRef<CTFontDescriptorRef> create_descriptor(const char familyName[], const SkFontStyle& style) { SkUniqueCFRef<CFMutableDictionaryRef> cfAttributes( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); SkUniqueCFRef<CFMutableDictionaryRef> cfTraits( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); if (!cfAttributes || !cfTraits) { return nullptr; } // TODO(crbug.com/1018581) Some CoreText versions have errant behavior when // certain traits set. Temporary workaround to omit specifying trait for those // versions. // Long term solution will involve serializing typefaces instead of relying upon // this to match between processes. // // Compare CoreText.h in an up to date SDK for where these values come from. static const uint32_t kSkiaLocalCTVersionNumber10_14 = 0x000B0000; static const uint32_t kSkiaLocalCTVersionNumber10_15 = 0x000C0000; // CTFontTraits (symbolic) // macOS 14 and iOS 12 seem to behave badly when kCTFontSymbolicTrait is set. // macOS 15 yields LastResort font instead of a good default font when // kCTFontSymbolicTrait is set. if (SkGetCoreTextVersion() < kSkiaLocalCTVersionNumber10_14) { CTFontSymbolicTraits ctFontTraits = 0; if (style.weight() >= SkFontStyle::kBold_Weight) { ctFontTraits |= kCTFontBoldTrait; } if (style.slant() != SkFontStyle::kUpright_Slant) { ctFontTraits |= kCTFontItalicTrait; } SkUniqueCFRef<CFNumberRef> cfFontTraits( CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &ctFontTraits)); if (cfFontTraits) { CFDictionaryAddValue(cfTraits.get(), kCTFontSymbolicTrait, cfFontTraits.get()); } } // CTFontTraits (weight) CGFloat ctWeight = SkCTFontCTWeightForCSSWeight(style.weight()); SkUniqueCFRef<CFNumberRef> cfFontWeight( CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctWeight)); if (cfFontWeight) { CFDictionaryAddValue(cfTraits.get(), kCTFontWeightTrait, cfFontWeight.get()); } // CTFontTraits (width) CGFloat ctWidth = SkCTFontCTWidthForCSSWidth(style.width()); SkUniqueCFRef<CFNumberRef> cfFontWidth( CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctWidth)); if (cfFontWidth) { CFDictionaryAddValue(cfTraits.get(), kCTFontWidthTrait, cfFontWidth.get()); } // CTFontTraits (slant) // macOS 15 behaves badly when kCTFontSlantTrait is set. if (SkGetCoreTextVersion() != kSkiaLocalCTVersionNumber10_15) { CGFloat ctSlant = style.slant() == SkFontStyle::kUpright_Slant ? 0 : 1; SkUniqueCFRef<CFNumberRef> cfFontSlant( CFNumberCreate(kCFAllocatorDefault, kCFNumberCGFloatType, &ctSlant)); if (cfFontSlant) { CFDictionaryAddValue(cfTraits.get(), kCTFontSlantTrait, cfFontSlant.get()); } } // CTFontTraits CFDictionaryAddValue(cfAttributes.get(), kCTFontTraitsAttribute, cfTraits.get()); // CTFontFamilyName if (familyName) { SkUniqueCFRef<CFStringRef> cfFontName = make_CFString(familyName); if (cfFontName) { CFDictionaryAddValue(cfAttributes.get(), kCTFontFamilyNameAttribute, cfFontName.get()); } } return SkUniqueCFRef<CTFontDescriptorRef>( CTFontDescriptorCreateWithAttributes(cfAttributes.get())); } // Same as the above function except style is included so we can // compare whether the created font conforms to the style. If not, we need // to recreate the font with symbolic traits. This is needed due to MacOS 10.11 // font creation problem https://bugs.chromium.org/p/skia/issues/detail?id=8447. static sk_sp<SkTypeface> create_from_desc_and_style(CTFontDescriptorRef desc, const SkFontStyle& style) { SkUniqueCFRef<CTFontRef> ctFont(CTFontCreateWithFontDescriptor(desc, 0, nullptr)); if (!ctFont) { return nullptr; } const CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(ctFont.get()); CTFontSymbolicTraits expected_traits = traits; if (style.slant() != SkFontStyle::kUpright_Slant) { expected_traits |= kCTFontItalicTrait; } if (style.weight() >= SkFontStyle::kBold_Weight) { expected_traits |= kCTFontBoldTrait; } if (expected_traits != traits) { SkUniqueCFRef<CTFontRef> ctNewFont(CTFontCreateCopyWithSymbolicTraits( ctFont.get(), 0, nullptr, expected_traits, expected_traits)); if (ctNewFont) { ctFont = std::move(ctNewFont); } } return SkTypeface_Mac::Make(std::move(ctFont), OpszVariation(), nullptr); } /** Creates a typeface from a name, searching the cache. */ static sk_sp<SkTypeface> create_from_name(const char familyName[], const SkFontStyle& style) { SkUniqueCFRef<CTFontDescriptorRef> desc = create_descriptor(familyName, style); if (!desc) { return nullptr; } return create_from_desc_and_style(desc.get(), style); } static const char* map_css_names(const char* name) { static const struct { const char* fFrom; // name the caller specified const char* fTo; // "canonical" name we map to } gPairs[] = { { "sans-serif", "Helvetica" }, { "serif", "Times" }, { "monospace", "Courier" } }; for (size_t i = 0; i < SK_ARRAY_COUNT(gPairs); i++) { if (strcmp(name, gPairs[i].fFrom) == 0) { return gPairs[i].fTo; } } return name; // no change } namespace { static sk_sp<SkData> skdata_from_skstreamasset(std::unique_ptr<SkStreamAsset> stream) { size_t size = stream->getLength(); if (const void* base = stream->getMemoryBase()) { return SkData::MakeWithProc(base, size, [](const void*, void* ctx) -> void { delete (SkStreamAsset*)ctx; }, stream.release()); } return SkData::MakeFromStream(stream.get(), size); } static SkUniqueCFRef<CFDataRef> cfdata_from_skdata(sk_sp<SkData> data) { void const * const addr = data->data(); size_t const size = data->size(); CFAllocatorContext ctx = { 0, // CFIndex version data.release(), // void* info nullptr, // const void *(*retain)(const void *info); nullptr, // void (*release)(const void *info); nullptr, // CFStringRef (*copyDescription)(const void *info); nullptr, // void * (*allocate)(CFIndex size, CFOptionFlags hint, void *info); nullptr, // void*(*reallocate)(void* ptr,CFIndex newsize,CFOptionFlags hint,void* info); [](void*,void* info) -> void { // void (*deallocate)(void *ptr, void *info); SkASSERT(info); ((SkData*)info)->unref(); }, nullptr, // CFIndex (*preferredSize)(CFIndex size, CFOptionFlags hint, void *info); }; SkUniqueCFRef<CFAllocatorRef> alloc(CFAllocatorCreate(kCFAllocatorDefault, &ctx)); return SkUniqueCFRef<CFDataRef>(CFDataCreateWithBytesNoCopy( kCFAllocatorDefault, (const UInt8 *)addr, size, alloc.get())); } static SkUniqueCFRef<CTFontRef> ctfont_from_skdata(sk_sp<SkData> data, int ttcIndex) { // TODO: Use CTFontManagerCreateFontDescriptorsFromData when available. if (ttcIndex != 0) { return nullptr; } SkUniqueCFRef<CFDataRef> cfData(cfdata_from_skdata(std::move(data))); SkUniqueCFRef<CTFontDescriptorRef> desc( CTFontManagerCreateFontDescriptorFromData(cfData.get())); if (!desc) { return nullptr; } return SkUniqueCFRef<CTFontRef>(CTFontCreateWithFontDescriptor(desc.get(), 0, nullptr)); } static bool find_desc_str(CTFontDescriptorRef desc, CFStringRef name, SkString* value) { SkUniqueCFRef<CFStringRef> ref((CFStringRef)CTFontDescriptorCopyAttribute(desc, name)); if (!ref) { return false; } SkStringFromCFString(ref.get(), value); return true; } static inline int sqr(int value) { SkASSERT(SkAbs32(value) < 0x7FFF); // check for overflow return value * value; } // We normalize each axis (weight, width, italic) to be base-900 static int compute_metric(const SkFontStyle& a, const SkFontStyle& b) { return sqr(a.weight() - b.weight()) + sqr((a.width() - b.width()) * 100) + sqr((a.slant() != b.slant()) * 900); } class SkFontStyleSet_Mac : public SkFontStyleSet { public: SkFontStyleSet_Mac(CTFontDescriptorRef desc) : fArray(CTFontDescriptorCreateMatchingFontDescriptors(desc, nullptr)) , fCount(0) { if (!fArray) { fArray.reset(CFArrayCreate(nullptr, nullptr, 0, nullptr)); } fCount = SkToInt(CFArrayGetCount(fArray.get())); } int count() override { return fCount; } void getStyle(int index, SkFontStyle* style, SkString* name) override { SkASSERT((unsigned)index < (unsigned)fCount); CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), index); if (style) { *style = SkCTFontDescriptorGetSkFontStyle(desc, false); } if (name) { if (!find_desc_str(desc, kCTFontStyleNameAttribute, name)) { name->reset(); } } } SkTypeface* createTypeface(int index) override { SkASSERT((unsigned)index < (unsigned)CFArrayGetCount(fArray.get())); CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), index); return create_from_desc(desc).release(); } SkTypeface* matchStyle(const SkFontStyle& pattern) override { if (0 == fCount) { return nullptr; } return create_from_desc(findMatchingDesc(pattern)).release(); } private: SkUniqueCFRef<CFArrayRef> fArray; int fCount; CTFontDescriptorRef findMatchingDesc(const SkFontStyle& pattern) const { int bestMetric = SK_MaxS32; CTFontDescriptorRef bestDesc = nullptr; for (int i = 0; i < fCount; ++i) { CTFontDescriptorRef desc = (CTFontDescriptorRef)CFArrayGetValueAtIndex(fArray.get(), i); int metric = compute_metric(pattern, SkCTFontDescriptorGetSkFontStyle(desc, false)); if (0 == metric) { return desc; } if (metric < bestMetric) { bestMetric = metric; bestDesc = desc; } } SkASSERT(bestDesc); return bestDesc; } }; SkUniqueCFRef<CFArrayRef> SkCopyAvailableFontFamilyNames(CTFontCollectionRef collection) { // Create a CFArray of all available font descriptors. SkUniqueCFRef<CFArrayRef> descriptors( CTFontCollectionCreateMatchingFontDescriptors(collection)); // Copy the font family names of the font descriptors into a CFSet. auto addDescriptorFamilyNameToSet = [](const void* value, void* context) -> void { CTFontDescriptorRef descriptor = static_cast<CTFontDescriptorRef>(value); CFMutableSetRef familyNameSet = static_cast<CFMutableSetRef>(context); SkUniqueCFRef<CFTypeRef> familyName( CTFontDescriptorCopyAttribute(descriptor, kCTFontFamilyNameAttribute)); if (familyName) { CFSetAddValue(familyNameSet, familyName.get()); } }; SkUniqueCFRef<CFMutableSetRef> familyNameSet( CFSetCreateMutable(kCFAllocatorDefault, 0, &kCFTypeSetCallBacks)); CFArrayApplyFunction(descriptors.get(), CFRangeMake(0, CFArrayGetCount(descriptors.get())), addDescriptorFamilyNameToSet, familyNameSet.get()); // Get the set of family names into an array; this does not retain. CFIndex count = CFSetGetCount(familyNameSet.get()); std::unique_ptr<const void*[]> familyNames(new const void*[count]); CFSetGetValues(familyNameSet.get(), familyNames.get()); // Sort the array of family names (to match CTFontManagerCopyAvailableFontFamilyNames). std::sort(familyNames.get(), familyNames.get() + count, [](const void* a, const void* b){ return CFStringCompare((CFStringRef)a, (CFStringRef)b, 0) == kCFCompareLessThan; }); // Copy family names into a CFArray; this does retain. return SkUniqueCFRef<CFArrayRef>( CFArrayCreate(kCFAllocatorDefault, familyNames.get(), count, &kCFTypeArrayCallBacks)); } /** Use CTFontManagerCopyAvailableFontFamilyNames if available, simulate if not. */ SkUniqueCFRef<CFArrayRef> SkCTFontManagerCopyAvailableFontFamilyNames() { #ifdef SK_BUILD_FOR_IOS using CTFontManagerCopyAvailableFontFamilyNamesProc = CFArrayRef (*)(void); CTFontManagerCopyAvailableFontFamilyNamesProc ctFontManagerCopyAvailableFontFamilyNames; *(void**)(&ctFontManagerCopyAvailableFontFamilyNames) = dlsym(RTLD_DEFAULT, "CTFontManagerCopyAvailableFontFamilyNames"); if (ctFontManagerCopyAvailableFontFamilyNames) { return SkUniqueCFRef<CFArrayRef>(ctFontManagerCopyAvailableFontFamilyNames()); } SkUniqueCFRef<CTFontCollectionRef> collection( CTFontCollectionCreateFromAvailableFonts(nullptr)); return SkUniqueCFRef<CFArrayRef>(SkCopyAvailableFontFamilyNames(collection.get())); #else return SkUniqueCFRef<CFArrayRef>(CTFontManagerCopyAvailableFontFamilyNames()); #endif } } // namespace class SkFontMgr_Mac : public SkFontMgr { SkUniqueCFRef<CFArrayRef> fNames; int fCount; CFStringRef getFamilyNameAt(int index) const { SkASSERT((unsigned)index < (unsigned)fCount); return (CFStringRef)CFArrayGetValueAtIndex(fNames.get(), index); } static SkFontStyleSet* CreateSet(CFStringRef cfFamilyName) { SkUniqueCFRef<CFMutableDictionaryRef> cfAttr( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFDictionaryAddValue(cfAttr.get(), kCTFontFamilyNameAttribute, cfFamilyName); SkUniqueCFRef<CTFontDescriptorRef> desc( CTFontDescriptorCreateWithAttributes(cfAttr.get())); return new SkFontStyleSet_Mac(desc.get()); } public: SkUniqueCFRef<CTFontCollectionRef> fFontCollection; SkFontMgr_Mac(CTFontCollectionRef fontCollection) : fNames(fontCollection ? SkCopyAvailableFontFamilyNames(fontCollection) : SkCTFontManagerCopyAvailableFontFamilyNames()) , fCount(fNames ? SkToInt(CFArrayGetCount(fNames.get())) : 0) , fFontCollection(fontCollection ? (CTFontCollectionRef)CFRetain(fontCollection) : CTFontCollectionCreateFromAvailableFonts(nullptr)) {} protected: int onCountFamilies() const override { return fCount; } void onGetFamilyName(int index, SkString* familyName) const override { if ((unsigned)index < (unsigned)fCount) { SkStringFromCFString(this->getFamilyNameAt(index), familyName); } else { familyName->reset(); } } SkFontStyleSet* onCreateStyleSet(int index) const override { if ((unsigned)index >= (unsigned)fCount) { return nullptr; } return CreateSet(this->getFamilyNameAt(index)); } SkFontStyleSet* onMatchFamily(const char familyName[]) const override { if (!familyName) { return nullptr; } SkUniqueCFRef<CFStringRef> cfName = make_CFString(familyName); return CreateSet(cfName.get()); } SkTypeface* onMatchFamilyStyle(const char familyName[], const SkFontStyle& style) const override { SkUniqueCFRef<CTFontDescriptorRef> desc = create_descriptor(familyName, style); return create_from_desc(desc.get()).release(); } SkTypeface* onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle& style, const char* bcp47[], int bcp47Count, SkUnichar character) const override { SkUniqueCFRef<CTFontDescriptorRef> desc = create_descriptor(familyName, style); SkUniqueCFRef<CTFontRef> familyFont(CTFontCreateWithFontDescriptor(desc.get(), 0, nullptr)); // kCFStringEncodingUTF32 is BE unless there is a BOM. // Since there is no machine endian option, explicitly state machine endian. #ifdef SK_CPU_LENDIAN constexpr CFStringEncoding encoding = kCFStringEncodingUTF32LE; #else constexpr CFStringEncoding encoding = kCFStringEncodingUTF32BE; #endif SkUniqueCFRef<CFStringRef> string(CFStringCreateWithBytes( kCFAllocatorDefault, reinterpret_cast<const UInt8 *>(&character), sizeof(character), encoding, false)); // If 0xD800 <= codepoint <= 0xDFFF || 0x10FFFF < codepoint 'string' may be nullptr. // No font should be covering such codepoints (even the magic fallback font). if (!string) { return nullptr; } CFRange range = CFRangeMake(0, CFStringGetLength(string.get())); // in UniChar units. SkUniqueCFRef<CTFontRef> fallbackFont( CTFontCreateForString(familyFont.get(), string.get(), range)); return SkTypeface_Mac::Make(std::move(fallbackFont), OpszVariation(), nullptr).release(); } sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData> data, int ttcIndex) const override { if (ttcIndex != 0) { return nullptr; } SkUniqueCFRef<CTFontRef> ct = ctfont_from_skdata(data, ttcIndex); if (!ct) { return nullptr; } return SkTypeface_Mac::Make(std::move(ct), OpszVariation(), SkMemoryStream::Make(std::move(data))); } sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream, int ttcIndex) const override { if (ttcIndex != 0) { return nullptr; } sk_sp<SkData> data = skdata_from_skstreamasset(stream->duplicate()); if (!data) { return nullptr; } SkUniqueCFRef<CTFontRef> ct = ctfont_from_skdata(std::move(data), ttcIndex); if (!ct) { return nullptr; } return SkTypeface_Mac::Make(std::move(ct), OpszVariation(), std::move(stream)); } sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream, const SkFontArguments& args) const override { // TODO: Use CTFontManagerCreateFontDescriptorsFromData when available. int ttcIndex = args.getCollectionIndex(); if (ttcIndex != 0) { return nullptr; } sk_sp<SkData> data = skdata_from_skstreamasset(stream->duplicate()); if (!data) { return nullptr; } SkUniqueCFRef<CTFontRef> ct = ctfont_from_skdata(std::move(data), ttcIndex); if (!ct) { return nullptr; } SkUniqueCFRef<CFArrayRef> axes(CTFontCopyVariationAxes(ct.get())); CTFontVariation ctVariation = SkCTVariationFromSkFontArguments(ct.get(), axes.get(), args); SkUniqueCFRef<CTFontRef> ctVariant; if (ctVariation.variation) { SkUniqueCFRef<CFMutableDictionaryRef> attributes( CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)); CFDictionaryAddValue(attributes.get(), kCTFontVariationAttribute, ctVariation.variation.get()); SkUniqueCFRef<CTFontDescriptorRef> varDesc( CTFontDescriptorCreateWithAttributes(attributes.get())); ctVariant.reset(CTFontCreateCopyWithAttributes(ct.get(), 0, nullptr, varDesc.get())); } else { ctVariant.reset(ct.release()); } if (!ctVariant) { return nullptr; } return SkTypeface_Mac::Make(std::move(ctVariant), ctVariation.opsz, std::move(stream)); } sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override { if (ttcIndex != 0) { return nullptr; } sk_sp<SkData> data = SkData::MakeFromFileName(path); if (!data) { return nullptr; } return this->onMakeFromData(std::move(data), ttcIndex); } sk_sp<SkTypeface> onLegacyMakeTypeface(const char familyName[], SkFontStyle style) const override { if (familyName) { familyName = map_css_names(familyName); } sk_sp<SkTypeface> face = create_from_name(familyName, style); if (face) { return face; } static SkTypeface* gDefaultFace; static SkOnce lookupDefault; static const char FONT_DEFAULT_NAME[] = "Lucida Sans"; lookupDefault([]{ gDefaultFace = create_from_name(FONT_DEFAULT_NAME, SkFontStyle()).release(); }); return sk_ref_sp(gDefaultFace); } }; sk_sp<SkFontMgr> SkFontMgr_New_CoreText(CTFontCollectionRef fontCollection) { return sk_make_sp<SkFontMgr_Mac>(fontCollection); } #endif//defined(SK_BUILD_FOR_MAC) || defined(SK_BUILD_FOR_IOS)
24,656
7,615
/* Copyright 2002-2020 Nikolay Avrionov. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "stdafx.h" #include "TextUtil.h" #include "SplitPath.h" #include "Resource.h" #include "globals.h" void MakeUpper (CString &str) { int last = str.GetLength (); /*int ext_pos = str.ReverseFind ('.'); if (ext_pos != -1) last = ext_pos;*/ for (int i = 0; i < last; i++) str.SetAt (i, _totupper (str[i])); } void TitleCase (CString& str) { if (str.GetLength () == 0) return; str.MakeLower (); bool bNewWord = true; int last = str.GetLength (); /* int ext_pos = str.ReverseFind ('.'); if (ext_pos != -1) last = ext_pos;*/ for (int i = 0; i < last; i++) { if (_istalpha (str[i])) { if (bNewWord) { bNewWord = false; str.SetAt (i, _totupper (str[i])); } } else bNewWord = true; } } void ToggleCase (CString& str) { if (str.GetLength () == 0) return; MakeUpper (str); bool bNewWord = true; int last = str.GetLength (); /*int ext_pos = str.ReverseFind ('.'); if (ext_pos != -1) last = ext_pos;*/ for (int i = 0; i < last; i++) { if (_istalpha (str[i])) { if (bNewWord) { bNewWord = false; str.SetAt (i, _tolower (str[i])); } } else bNewWord = true; } } void SentenceCase (CString& str) { if (str.GetLength () == 0) return; str.MakeLower (); str.SetAt (0, _toupper (str[0])); } void ChangeCase (int iCmd , CString &str) { switch (iCmd) { case ID_SENTENCECASE: SentenceCase (str); break; case ID_LOWERCASE: str.MakeLower (); break; case ID_UPPERCASE: MakeUpper (str); break; case ID_TITLECASE: TitleCase (str); break; case ID_TOGGLECASE: ToggleCase (str); break; } } void Space2Underscore (CString & str) { while (str.Replace (' ','_')); } void Underscore2Space (CString & str) { while (str.Replace ('_',' ')); } void Convert202Space (CString & str) { while (str.Replace (_T("%20"), _T(" "))); } void ConvertPoint2Space (CString & str, bool bExtentions) { if (bExtentions) { CSplitPath path (str); CString tmp; tmp = path.GetDrive(); tmp += path.GetDir(); tmp += path.GetFName(); while (tmp.Replace (_T("."), _T(" "))); tmp += path.GetExt(); str = tmp; } else while (str.Replace (_T("."), _T(" "))); } void ConvertSpaces (int iCmd, CString &str, bool bExtentions) { switch (iCmd) { case ID_CONVERT20TOSPACE: Convert202Space (str); break; case ID_CONVERTUNDERSCORETOSPACE: Underscore2Space (str); break; case ID_CONVERTSPACETOUNDERSCORE: Space2Underscore (str); break; case ID_CONVERTPOINTTOSPACE: ConvertPoint2Space (str, bExtentions); break; } }
3,200
1,420
#ifndef RENDERBUFFERFORMAT_HPP_INCLUDED #define RENDERBUFFERFORMAT_HPP_INCLUDED namespace gst { // Supported renderbuffer storage formats. enum class RenderbufferFormat { DEPTH_COMPONENT16, DEPTH_COMPONENT24, DEPTH_COMPONENT32, DEPTH_COMPONENT32F }; } #endif
305
123
/********************************************************************** <BR> This file is part of Crack dot Com's free source code release of Golgotha. <a href="http://www.crack.com/golgotha_release"> <BR> for information about compiling & licensing issues visit this URL</a> <PRE> If that doesn't help, contact Jonathan Clark at golgotha_source@usa.net (Subject should have "GOLG" in it) ***********************************************************************/ #include "pch.h" #include "video/win32/dx5_util.h" #include "video/win32/dx5_mouse.h" #include "image/context.h" #include "video/win32/dx5_error.h" #include <ddraw.h> dx5_mouse_class::dx5_mouse_class(i4_bool page_flipped) : page_flipped(page_flipped) { cursor.pict=0; cursor.hot_x=0; cursor.hot_y=0; last.save_buffer=0; current.save_buffer=0; last_was_gdi=i4_T; } void dx5_mouse_class::set_cursor(i4_cursor_class * c) { /*if (cursor.pict) { delete cursor.pict; cursor.pict=0; }*/ if (c && c->pict) { int cw=c->pict->width(), ch=c->pict->height(); i4_draw_context_class context(0,0, cw-1, ch-1); i4_dx5_image_class * dx5_image=(i4_dx5_image_class *)cursor.pict; if ((!cursor.pict)||(cw!=cursor.pict->width())||ch!=cursor.pict->height()) { delete cursor.pict; cursor.pict=0; dx5_image = new i4_dx5_image_class(cw, ch, DX5_SYSTEM_RAM | DX5_CLEAR); //currently, it is not possible to use vram, as we'll lose the cursor on //DDERR_SURFACELOST cursor = *c; cursor.pict = dx5_image; } //setup the color-key value for the mouse (black) DDCOLORKEY colorkey; memset(&colorkey,0,sizeof(DDCOLORKEY)); //i4_color converted_transparent = c->pict->pal.pal->convert(c->trans,&dx5_common.i4_fmt_565); colorkey.dwColorSpaceLowValue = 0; //converted_transparent; colorkey.dwColorSpaceHighValue = 0; //converted_transparent; dx5_image->surface->SetColorKey(DDCKEY_SRCBLT,&colorkey); short w=dx5_image->width()-1; short h=dx5_image->height()-1; i4_draw_context_class ctx(0,0,w,h); //all drawing functions, including the contexts always _include_ //the rightmost pixel //so if the context and the requested operation is greater than the //image nothing is clipped away and we silently overwrite some //memory. (remove the -1 up here and see how the kernel likes you....) dx5_image->bar(0,0,w,h, 0,ctx); //change everything to black dx5_image->lock(); c->pict->put_image_trans(cursor.pict, 0,0, c->trans, context); dx5_image->unlock(); } else { delete cursor.pict; cursor.pict=0; //hide cursor } i4_bool g=primary_is_gdi(); last_was_gdi=!g; current.isgdi=g; last.isgdi=!g; } dx5_mouse_class::~dx5_mouse_class() { if (cursor.pict) { delete cursor.pict; cursor.pict=0; } } i4_bool dx5_mouse_class::primary_is_gdi() { //i4_bool ret; LPDIRECTDRAWSURFACE lpgdi=0; LPDIRECTDRAWSURFACE3 lpgdi3=0; //LPSURFACEDESC lpsd=0; //DDSCAPS caps; //dx5_common.primary_surface->GetCaps(&caps); //if (caps.dwCaps&DDSCAPS_PRIMARYSURFACE) // return i4_T; //else // return i4_F; i4_dx5_check(dx5_common.ddraw->GetGDISurface(&lpgdi)); i4_dx5_check(lpgdi->QueryInterface(IID_IDirectDrawSurface3,(void * *)&lpgdi3)); if (lpgdi) { lpgdi->Release(); } if (dx5_common.primary_surface==lpgdi3) { if (lpgdi3) { lpgdi3->Release(); } return i4_T; } else { if (lpgdi3) { lpgdi3->Release(); } return i4_F; } } void dx5_mouse_class::save_and_draw(int x, int y) { if (!cursor.pict) { return ; } // i4_bool g=primary_is_gdi(); // if (page_flipped&&(g==last_was_gdi)) //current frame buffer same as last: something has happenened // { // // } //i4_warning("TRACE: Mouse first part"); if (!current.save_buffer || current.save_buffer->width() != cursor.pict->width() || current.save_buffer->height() != cursor.pict->height()) { if (current.save_buffer) { delete current.save_buffer; } current.save_buffer=new i4_dx5_image_class(cursor.pict->width(), cursor.pict->height(), DX5_VRAM); } current.x=x - cursor.hot_x; current.y=y - cursor.hot_y; if (current.x<0) { current.x=0; } if (current.y<0) { current.y=0; } RECT src; i4_display_class * disp=i4_current_app->get_display(); //PG: Not having these two conditions allows the cursor //to move all the way to the right or bottom of the screen, //but may cause trouble with the BltFast operation if (current.x+cursor.pict->width()>disp->width()) { current.x=disp->width()-cursor.pict->width()-1; } if (current.y+cursor.pict->height()>disp->height()) { current.y=disp->height()-cursor.pict->height()-1; } src.left = current.x; src.right = current.x + cursor.pict->width(); src.top = current.y; src.bottom = current.y + cursor.pict->height(); HRESULT hr=0; //i4_warning("TRACE: Mouse second part"); //no i4_dx5_check here as we allways get an error when the cursor is outside the window if (i4_dx5_check(hr=current.save_buffer->surface->BltFast(0,0, dx5_common.back_surface, &src,DDBLTFAST_NOCOLORKEY|DDBLTFAST_WAIT))) { //i4_warning("TRACE: Mouse third part"); i4_dx5_check(dx5_common.back_surface->BltFast(current.x, current.y, ((i4_dx5_image_class *)cursor.pict)->surface,0, DDBLTFAST_SRCCOLORKEY|DDBLTFAST_WAIT)); } else { if (current.save_buffer&&current.save_buffer->surface) { current.save_buffer->surface->Restore(); } if (last.save_buffer&&last.save_buffer->surface) { last.save_buffer->surface->Restore(); } } if (page_flipped) { save_struct tmp=current; current=last; last=tmp; tmp.save_buffer=0; } } void dx5_mouse_class::restore() { if (current.save_buffer) { RECT src; src.left = 0; src.right = cursor.pict->width(); src.top = 0; src.bottom = cursor.pict->height(); i4_bool g=primary_is_gdi(); if (page_flipped&&(g==current.isgdi)) //current frame buffer same as last: something has happenened { dx5_common.primary_surface->BltFast(current.x,current.y,current.save_buffer->surface,&src, DDBLTFAST_NOCOLORKEY|DDBLTFAST_WAIT); current.isgdi=!current.isgdi; last.isgdi=!last.isgdi; } dx5_common.back_surface->BltFast(current.x, current.y, current.save_buffer->surface, &src, DDBLTFAST_NOCOLORKEY); //DDBLTFAST_NOCOLORKEY|DDBLTFAST_WAIT } }
6,560
2,876
/* * Copyright 2018 Google * * 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 "Firestore/core/src/firebase/firestore/model/document_key.h" #include <utility> #include "Firestore/core/src/firebase/firestore/util/hard_assert.h" namespace firebase { namespace firestore { namespace model { namespace { void AssertValidPath(const ResourcePath& path) { HARD_ASSERT(DocumentKey::IsDocumentKey(path), "invalid document key path: %s", path.CanonicalString()); } } // namespace DocumentKey::DocumentKey(const ResourcePath& path) : path_{std::make_shared<ResourcePath>(path)} { AssertValidPath(*path_); } DocumentKey::DocumentKey(ResourcePath&& path) : path_{std::make_shared<ResourcePath>(std::move(path))} { AssertValidPath(*path_); } const DocumentKey& DocumentKey::Empty() { static const DocumentKey empty; return empty; } util::ComparisonResult DocumentKey::CompareTo(const DocumentKey& other) const { return path().CompareTo(other.path()); } } // namespace model } // namespace firestore } // namespace firebase
1,580
477
#pragma once #include <functional> #include <memory> #include <optional> #include <vector> #include <Transform/Movable.hpp> #include <Transform/Rect.hpp> #include <Transform/UnitBasedObject.hpp> #include <Transform/UnitVector.hpp> namespace obe::Transform { class Polygon; using point_index_t = unsigned int; class PolygonPoint : public UnitVector { private: friend class Polygon; Polygon* m_parent; point_index_t rw_index; public: enum class RelativePositionFrom { Point0, Centroid }; explicit PolygonPoint(Polygon* parent, unsigned int index); explicit PolygonPoint(Polygon* parent, unsigned int index, const Transform::UnitVector& position); const point_index_t& index = rw_index; void remove() const; double distance(const Transform::UnitVector& position) const; UnitVector getRelativePosition(RelativePositionFrom from) const; void setRelativePosition(RelativePositionFrom from, const Transform::UnitVector& position); void move(const Transform::UnitVector& position); }; class PolygonSegment { public: const PolygonPoint& first; const PolygonPoint& second; double getAngle() const; double getLength() const; PolygonSegment(const PolygonPoint& first, const PolygonPoint& second); }; using PolygonPath = std::vector<std::unique_ptr<PolygonPoint>>; /** * \brief Class used for all Collisions in the engine, it's a Polygon containing n points * @Bind */ class Polygon : public Transform::UnitBasedObject, public Transform::Movable { protected: friend class PolygonPoint; PolygonPath m_points; float m_angle = 0; void resetUnit(Transform::Units unit) override; public: static constexpr double DefaultTolerance = 0.02; /** * \brief Adds a new Point to the Polygon at Position (x, y) * \param position Coordinate of the Position where to add the new Point * \param pointIndex Index where to insert the new Point, Use pointIndex = -1 <DefaultArg> to insert at the end (between last and first Point) */ void addPoint(const Transform::UnitVector& position, int pointIndex = -1); /** * \brief Finds the closest Line from the given Position * \param position Position used to get the closest Line * \return The index of the line that is the closest one of the given Position (Line between point 0 and point 1 is index 0) */ PolygonSegment findClosestSegment(const Transform::UnitVector& position); /** * \brief Find the closest Point from the given Position(x, y) * \param position Coordinate of the Position used to get the closest Point * \param neighbor Get the closest neighboor of the closest Point instead of the Point * \param excludedPoints A std::vector containing points you want to exclude from the calculus (Not used in neighboor check step) * \return The index of the Point (or one of its neighboor) that is the closest one of the given Position */ PolygonPoint& findClosestPoint(const Transform::UnitVector& position, bool neighbor = false, const std::vector<point_index_t>& excludedPoints = {}); /** * \brief Get all the Points of the Polygon * \return A Path containing all the Points of the Polygon */ PolygonPath& getAllPoints(); /** * \brief Get the position of the Master Point (centroid) of the Polygon * \return An UnitVector containing the position of the Master Point (centroid) of the Polygon */ Transform::UnitVector getCentroid() const; /** * \brief Get the number of points in the Polygon * \return An unsigned int containing the number of points of the Polygon */ unsigned int getPointsAmount() const; /** * \brief Get the Position of the first point (index 0) of the Polygon * \return An UnitVector containing the position of the first point of the Polygon */ Transform::UnitVector getPosition() const override; /** * \brief Gets the current angle of the PolygonalCollider * \return A float containing the value of the current angle of the PolygonalCollider */ float getRotation() const; /* * \brief Gets the segment of the Polygon at index segment * \param segment Index of the Segment to get * \return The segment of the Polygon at index segment */ PolygonSegment getSegment(point_index_t segment); /** * \brief Get if the Position (x, y) is on one of the side of the Polygon * \param position Coordinate of the Position to test * \param tolerance * \return An unsigned int containing the index of the side containing the position or -1 if not found */ std::optional<PolygonSegment> getSegmentContainingPoint(const Transform::UnitVector& position, double tolerance = DefaultTolerance); /** * \brief Check if the MasterPoint of the Polygon is on Position (x - tolerance <= x <= x + tolerance, y - tolerance <= tolerance <= y + tolerance) * \param position Coordinate of the Position to test * \param tolerance Position tolerance, bigger number means less precise * \return true if the MasterPoint is on the given Positon, false otherwise */ bool isCentroidAroundPosition(const Transform::UnitVector& position, const Transform::UnitVector& tolerance) const; /** * \brief Check if a point of the Polygon is on Position (x - tolerance <= x <= x + tolerance, y - tolerance <= tolerance <= y + tolerance) * \param position Coordinate of the Position to test * \param tolerance Position tolerance, bigger number means less precise * \return An unsigned int containing the index of the point containing the position or -1 if not found */ std::optional<PolygonPoint*> getPointAroundPosition(const Transform::UnitVector& position, const Transform::UnitVector& tolerance); /** * \brief Moves the Polygon (relative to the current position) * \param position UnitVector containing the offset to move the Polygon */ void move(const Transform::UnitVector& position) override; /** * \brief Adds an angle to the current angle of the PolygonalCollider (will rotate all points around the given origin) * \param angle Angle to add to the PolygonalCollider * \param origin Origin to rotate all the points around */ void rotate(float angle, Transform::UnitVector origin); /** * \brief Sets the new position of the Polygon (using the point at index 0) * \param position UnitVector containing the new Position of the Polygon */ void setPosition(const Transform::UnitVector& position) override; /** * \brief Sets the angle of the PolygonalCollider (will rotate all points around the given origin) * \param angle Angle to set to the PolygonalCollider * \param origin Origin to rotate all the points around */ void setRotation(float angle, Transform::UnitVector origin); void setPositionFromCentroid(const Transform::UnitVector& position); PolygonPoint& operator[](point_index_t i); PolygonPoint& get(point_index_t i); Rect getBoundingBox() const; }; }
7,660
1,961
/** * Upbit Open API * ## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [open-api@upbit.com] * * OpenAPI spec version: 1.0.0 * Contact: ujhin942@gmail.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ #include "SWGMarketInfo.h" #include "SWGHelpers.h" #include <QJsonDocument> #include <QJsonArray> #include <QObject> #include <QDebug> namespace Swagger { SWGMarketInfo::SWGMarketInfo(QString json) { init(); this->fromJson(json); } SWGMarketInfo::SWGMarketInfo() { init(); } SWGMarketInfo::~SWGMarketInfo() { this->cleanup(); } void SWGMarketInfo::init() { market = new QString(""); m_market_isSet = false; korean_name = new QString(""); m_korean_name_isSet = false; english_name = new QString(""); m_english_name_isSet = false; market_warning = new QString(""); m_market_warning_isSet = false; } void SWGMarketInfo::cleanup() { if(market != nullptr) { delete market; } if(korean_name != nullptr) { delete korean_name; } if(english_name != nullptr) { delete english_name; } if(market_warning != nullptr) { delete market_warning; } } SWGMarketInfo* SWGMarketInfo::fromJson(QString json) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); return this; } void SWGMarketInfo::fromJsonObject(QJsonObject pJson) { ::Swagger::setValue(&market, pJson["market"], "QString", "QString"); ::Swagger::setValue(&korean_name, pJson["korean_name"], "QString", "QString"); ::Swagger::setValue(&english_name, pJson["english_name"], "QString", "QString"); ::Swagger::setValue(&market_warning, pJson["market_warning"], "QString", "QString"); } QString SWGMarketInfo::asJson () { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject SWGMarketInfo::asJsonObject() { QJsonObject obj; if(market != nullptr && *market != QString("")){ toJsonValue(QString("market"), market, obj, QString("QString")); } if(korean_name != nullptr && *korean_name != QString("")){ toJsonValue(QString("korean_name"), korean_name, obj, QString("QString")); } if(english_name != nullptr && *english_name != QString("")){ toJsonValue(QString("english_name"), english_name, obj, QString("QString")); } if(market_warning != nullptr && *market_warning != QString("")){ toJsonValue(QString("market_warning"), market_warning, obj, QString("QString")); } return obj; } QString* SWGMarketInfo::getMarket() { return market; } void SWGMarketInfo::setMarket(QString* market) { this->market = market; this->m_market_isSet = true; } QString* SWGMarketInfo::getKoreanName() { return korean_name; } void SWGMarketInfo::setKoreanName(QString* korean_name) { this->korean_name = korean_name; this->m_korean_name_isSet = true; } QString* SWGMarketInfo::getEnglishName() { return english_name; } void SWGMarketInfo::setEnglishName(QString* english_name) { this->english_name = english_name; this->m_english_name_isSet = true; } QString* SWGMarketInfo::getMarketWarning() { return market_warning; } void SWGMarketInfo::setMarketWarning(QString* market_warning) { this->market_warning = market_warning; this->m_market_warning_isSet = true; } bool SWGMarketInfo::isSet(){ bool isObjectUpdated = false; do{ if(market != nullptr && *market != QString("")){ isObjectUpdated = true; break;} if(korean_name != nullptr && *korean_name != QString("")){ isObjectUpdated = true; break;} if(english_name != nullptr && *english_name != QString("")){ isObjectUpdated = true; break;} if(market_warning != nullptr && *market_warning != QString("")){ isObjectUpdated = true; break;} }while(false); return isObjectUpdated; } }
4,259
1,515
//============================================================================== /// /// File: EdLevelAnimationWindow.cpp /// /// Copyright (C) 2000-2014 by Smells Like Donkey Software Inc. All rights reserved. /// /// This file is subject to the terms and conditions defined in /// file 'LICENSE.txt', which is part of this source code package. /// //============================================================================== // Editor include #include "EdLevelAnimationWindow.hpp" #include "EdLevelDocument.hpp" // Qt include #include <QtWidgets/qdrawutil.h> #include <QtWidgets/QStyle> #include <QtCore/QFile> #include <QtGui/QMouseEvent> #include <QtGui/QWheelEvent> // Engine includes #include "DT3Core/Types/Utility/MoreStrings.hpp" #include "DT3Core/Objects/ObjectBase.hpp" #include "DT3Core/Scripting/ScriptingKeyframesRoot.hpp" //============================================================================== //============================================================================== using namespace DT3; //============================================================================== //============================================================================== EdLevelAnimationWindow::EdLevelAnimationWindow(QWidget *parent, QToolBar *toolbar, EdLevelDocument *document) : QWidget (parent), _font("Arial", 9), _font_bold("Arial", 9, QFont::Bold), _fm(_font), _pixels_per_second(100), _time (0.0F), _scroll (0), _root (NULL), _thumb_image (":/images/thumb.png"), _keyframe_image (":/images/keyframe.png"), _keyframe_image_selected (":/images/keyframe_selected.png") { _document = document; _toolbar = toolbar; // // Actions and toolbar // _anim_play = new QAction(tr("&Play"), this); _anim_play->setIcon(QIcon(":/images/play.png")); _anim_play->setStatusTip(tr("Play")); connect(_anim_play, SIGNAL(triggered()), this, SLOT(onScriptPlay())); _anim_stop = new QAction(tr("&Play"), this); _anim_stop->setIcon(QIcon(":/images/stop.png")); _anim_stop->setStatusTip(tr("Play")); connect(_anim_stop, SIGNAL(triggered()), this, SLOT(onScriptStop())); toolbar->addAction(_anim_play); toolbar->addAction(_anim_stop); // // Set up window // _horz_scrollbar = new QScrollBar(Qt::Horizontal, this); _horz_scrollbar->setSingleStep(20); _vert_scrollbar = new QScrollBar(Qt::Vertical, this); _vert_scrollbar->setSingleStep(10); connect( _horz_scrollbar, SIGNAL(valueChanged(int)), this, SLOT(onScrollTime(int)) ); connect( _vert_scrollbar, SIGNAL(valueChanged(int)), this, SLOT(onScroll(int)) ); _time_min = new EdLevelLineEdit(this); _time_min->setText("-1"); _time_max = new EdLevelLineEdit(this); _time_max->setText("30"); connect( _time_min, SIGNAL(editingFinished()), this, SLOT(onChangeTimeRange()) ); connect( _time_max, SIGNAL(editingFinished()), this, SLOT(onChangeTimeRange()) ); _scroll_width = _vert_scrollbar->sizeHint().width(); _scroll_height = _horz_scrollbar->sizeHint().height(); setFocusPolicy(Qt::ClickFocus); } EdLevelAnimationWindow::~EdLevelAnimationWindow (void) { } //============================================================================== //============================================================================== void EdLevelAnimationWindow::onAnimPlay (void) { //_anim_timer.start(200, this); } void EdLevelAnimationWindow::onAnimStop (void) { //_anim_timer.stop(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::scanRoot (const std::shared_ptr<ScriptingKeyframesRoot> &root, std::vector<PlugEventCache> &plug_event_cache) { _root = root; // Get all of the plugs for the current node std::list<PlugBase*> plugs; root->all_plugs(plugs); FOR_EACH (j,plugs) { // We only care about outputs if ( !(**j).is_output() ) continue; // Make sure it's hooked up if ( !(**j).has_outgoing_connection() ) continue; // Check each outgoing connection const std::vector<PlugBase*> connections = (**j).outgoing_connections(); for (int k = 0; k < connections.size(); ++k) { // Get connected keyframes std::shared_ptr<ScriptingKeyframes> keyframes = checked_cast<ScriptingKeyframes>( checked_cast<ScriptingKeyframes>(connections[k]->owner()->shared_from_this()) ); if (!keyframes) continue; // Get Keyframes output PlugBase *keyframes_out_plug = keyframes->plug_by_name("Out"); if (keyframes_out_plug) { // Make sure output is connected if (!keyframes_out_plug->has_outgoing_connection()) continue; // Get the FIRST output connection PlugBase* next_input_plug = keyframes_out_plug->outgoing_connections()[0]; // Record the nodes PlugEventCache animated_node; animated_node._node = checked_static_cast<PlugNode>(next_input_plug->owner()->shared_from_this()); animated_node._plug = next_input_plug; animated_node._keyframes = keyframes; plug_event_cache.push_back(animated_node); } // Get Keyframes output Event *keyframes_out_event = keyframes->event_by_name("Out"); if (keyframes_out_event) { // Make sure output is connected if (!keyframes_out_event->has_outgoing_connection()) continue; // Get the FIRST output connection Event* next_input_event = keyframes_out_event->outgoing_connections()[0]; // Record the nodes PlugEventCache animated_node; animated_node._node = checked_static_cast<PlugNode>(next_input_event->owner()->shared_from_this()); animated_node._event = next_input_event; animated_node._keyframes = keyframes; plug_event_cache.push_back(animated_node); } } } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::layoutItems (std::vector<PlugEventCache> &plug_event_cache) { std::shared_ptr<PlugNode> last_node; int ypos = 0; for (int i = 0; i < plug_event_cache.size(); ++i) { if (plug_event_cache[i]._node != last_node) { last_node = plug_event_cache[i]._node; PlugEventCache c; //c._node = last_node; c._title = last_node->full_name(); c._ypos = ypos; plug_event_cache.insert (plug_event_cache.begin() + i, c); ypos += NODE_ITEM_HEIGHT; ++i; } if (plug_event_cache[i]._plug) plug_event_cache[i]._title = MoreStrings::captialize_and_format(plug_event_cache[i]._plug->name()); else plug_event_cache[i]._title = MoreStrings::captialize_and_format(plug_event_cache[i]._event->name()); plug_event_cache[i]._ypos = ypos; ypos += NODE_ITEM_HEIGHT; } _nodes_height = ypos; } //============================================================================== //============================================================================== void EdLevelAnimationWindow::scanRelevantNodes (const std::list<std::shared_ptr<PlugNode>> &selection_list) { _root.reset(); // // Build a giant list of all of the relevant nodes breadth-first // std::list<std::shared_ptr<PlugNode>> visited_nodes = selection_list; std::vector<PlugEventCache> plug_event_cache; FOR_EACH (i,visited_nodes) { // Check if node is a root if ((*i)->isa(ScriptingKeyframesRoot::kind())) { std::shared_ptr<ScriptingKeyframesRoot> root = checked_static_cast<ScriptingKeyframesRoot>(*i); scanRoot (root, plug_event_cache); layoutItems (plug_event_cache); if (_plug_event_cache != plug_event_cache) { _plug_event_cache = plug_event_cache; } return; } // Special case components too if ((*i)->isa(ObjectBase::kind())) { std::shared_ptr<ObjectBase> node_base = checked_static_cast<ObjectBase>(*i); for (int i = 0; i < ComponentBase::NUM_COMPONENT_TYPES; ++i) { std::shared_ptr<ComponentBase> component_base = node_base->component_by_type ( (ComponentBase::ComponentType) i); if (component_base) { // Check if we already visited the node auto j = std::find(visited_nodes.begin(), visited_nodes.end(), component_base); if (j != visited_nodes.end()) continue; visited_nodes.push_back(component_base); } } } // Get all of the plugs for the current node std::list<PlugBase*> plugs; (**i).all_plugs(plugs); FOR_EACH (j, plugs) { // We only care about inputs if ( !(**j).is_input() ) continue; // Make sure it's hooked up if ( !(**j).has_incoming_connection() ) continue; // Get the node std::shared_ptr<PlugNode> node = checked_static_cast<PlugNode>((**j).incoming_connection()->owner()->shared_from_this()); if (!node) continue; // Check if we already visited the node auto k = std::find(visited_nodes.begin(), visited_nodes.end(), node); if (k == visited_nodes.end()) visited_nodes.push_back(node); } // Get all of the events for the current node std::list<Event*> events; (**i).all_events(events); FOR_EACH (k, events) { // We only care about inputs if ( !(**k).is_input() ) continue; // Make sure it's hooked up if ( !(**k).has_incoming_connection() ) continue; // Get the nodes const std::vector<Event*> events = (*k)->incoming_connections(); FOR_EACH (i, events) { std::shared_ptr<PlugNode> node = checked_static_cast<PlugNode>((*i)->owner()->shared_from_this()); auto k = std::find(visited_nodes.begin(), visited_nodes.end(), node); if (k == visited_nodes.end()) visited_nodes.push_back(node); } } } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::itemRect(PlugEventCache &n, QRect &tr, QRect &r) const { if (n._node) { const int INDENT = 15; tr = QRect(INDENT, n._ypos, NODE_ITEM_WIDTH-INDENT, NODE_ITEM_HEIGHT); r = QRect(0, n._ypos, NODE_ITEM_WIDTH, NODE_ITEM_HEIGHT); } else { const int INDENT = 5; tr = QRect(INDENT, n._ypos, NODE_ITEM_WIDTH-INDENT, NODE_ITEM_HEIGHT); r = QRect(0, n._ypos, NODE_ITEM_WIDTH, NODE_ITEM_HEIGHT); } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::thumbRect (QRect &r) const { if (_root) { DTfloat t = _root->time(); int xpos = timeToPosition(t); r = QRect(xpos - _thumb_image.width()/2,0, _thumb_image.width(),_thumb_image.height()); } else { r = QRect(_thumb_image.width()/2,0, _thumb_image.width(),_thumb_image.height()); } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::selectionRect (QRect &r) const { QPoint selection_start = _start_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT + _scroll); QPoint selection_end = _end_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT + _scroll); DTfloat xmin = selection_start.x(); DTfloat xmax = selection_end.x(); if (xmin > xmax) std::swap(xmin,xmax); DTfloat ymin = selection_start.y(); DTfloat ymax = selection_end.y(); if (ymin > ymax) std::swap(ymin,ymax); r = QRect( xmin, ymin, xmax - xmin, ymax - ymin); } void EdLevelAnimationWindow::keyRect (PlugEventCache &p, int k, QRect &rk) const { QRect tr, r; itemRect(p, tr, r); DTfloat kf_time = p._keyframes->key_time(k); int xpos = timeToPosition(kf_time); rk = QRect( xpos - _keyframe_image.width()/2, r.center().y() - _keyframe_image.height()/2, _keyframe_image.width(), _keyframe_image.height() ); } //============================================================================== //============================================================================== int EdLevelAnimationWindow::timeToPosition (DTfloat seconds) const { return _pixels_per_second * seconds; } DTfloat EdLevelAnimationWindow::positionToTime (int position) const { return static_cast<DTfloat>(position) / static_cast<DTfloat>(_pixels_per_second); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::onSelectionChanged (const std::list<std::shared_ptr<PlugNode>> &selection_list) { blockSignals(true); scanRelevantNodes(selection_list); blockSignals(false); update(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::resizeEvent (QResizeEvent *event) { _title = QRect(0,0,NODE_ITEM_WIDTH, TITLE_HEIGHT); _timeline = QRect(NODE_ITEM_WIDTH,0,rect().width() - NODE_ITEM_WIDTH - _scroll_width, TITLE_HEIGHT); _nodes = QRect(0,TITLE_HEIGHT, NODE_ITEM_WIDTH, rect().height() - TITLE_HEIGHT); _controls = QRect(NODE_ITEM_WIDTH, TITLE_HEIGHT, rect().width() - NODE_ITEM_WIDTH - _scroll_width, rect().height() - TITLE_HEIGHT - _scroll_height); // Place scrollbars _horz_scrollbar->setGeometry(NODE_ITEM_WIDTH, rect().height() - _scroll_height, rect().width() - NODE_ITEM_WIDTH - _scroll_width, _scroll_height); _vert_scrollbar->setGeometry(rect().width() - _scroll_width, TITLE_HEIGHT, _scroll_width, rect().height() - TITLE_HEIGHT - _scroll_height); // Scale scrollbars int page_step = rect().height() - TITLE_HEIGHT - _scroll_height; _vert_scrollbar->setPageStep(page_step); _vert_scrollbar->setRange(0,_nodes_height - page_step); // Scale fields _time_min->setGeometry(NODE_ITEM_WIDTH, rect().height() - _scroll_height - TIME_FIELD_HEIGHT, TIME_FIELD_WIDTH, TIME_FIELD_HEIGHT); _time_max->setGeometry(rect().width() - _scroll_width - TIME_FIELD_WIDTH, rect().height() - _scroll_height - TIME_FIELD_HEIGHT, TIME_FIELD_WIDTH, TIME_FIELD_HEIGHT); onChangeTimeRange(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::onScrollTime(int time) { _time = positionToTime(time); update(); } void EdLevelAnimationWindow::onScroll(int scroll) { _scroll = scroll; update(); } void EdLevelAnimationWindow::onChangeTimeRange() { _time_min_sec = _time_min->text().toFloat(); _time_max_sec = _time_max->text().toFloat(); if (_time < _time_min_sec) _time = _time_min_sec; if (_time > _time_max_sec) _time = _time_max_sec; int page_step = _controls.width(); _horz_scrollbar->setPageStep(page_step); _horz_scrollbar->setRange( timeToPosition(_time_min_sec), timeToPosition(_time_max_sec) - page_step); update(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::mouseDoubleClickEvent (QMouseEvent *event) { event->accept(); } void EdLevelAnimationWindow::mousePressEvent(QMouseEvent *event) { emit doUndoBlock(); _start_point = _last_point = _end_point = event->pos(); // Translate into timeline space QPoint local_pos = _end_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT + _scroll); // Check click in thumb if (_timeline.contains(event->pos())) { setMode(MODE_DRAGGING_THUMB); if (_root) { DTfloat t = positionToTime(local_pos.x()); emit doCommand(QString("SetProp \"") + _root->full_name().c_str() + ".Time_Out\" " + MoreStrings::cast_to_string(t).c_str()); } update(); } else if (_controls.contains(_end_point)) { if ( (event->buttons() & Qt::LeftButton) && ( (event->buttons() & Qt::MidButton) || (event->modifiers() & Qt::ALT)) ) { setMode(MODE_ZOOMING); } else { // Check all keyframes to see if one is clicked for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; for (int k = 0; k < getNumKeys(_plug_event_cache[i]); ++k) { QRect rk; keyRect (_plug_event_cache[i], k, rk); if (rk.contains(local_pos)) { int id = _plug_event_cache[i]._keyframes->key_id(k); // Check select new keyframe if (!isSelected(_plug_event_cache[i], id)) { clearSelected(); setSelected(_plug_event_cache[i], id, true); } setMode(MODE_DRAGGING); update(); return; } } } setMode(MODE_DRAG_SELECTING); } } else { setMode(MODE_NONE); } } void EdLevelAnimationWindow::mouseMoveEvent(QMouseEvent *event) { _end_point = event->pos(); //QPoint dist = _end_point - _start_point; QPoint delta = _end_point - _last_point; // Translate into timeline space QPoint local_pos = _end_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT); switch (getMode()) { case MODE_DRAGGING_THUMB: if (_root) { DTfloat t = positionToTime(local_pos.x()); emit doCommand(QString("SetProp \"") + _root->full_name().c_str() + ".Time_Out\" " + MoreStrings::cast_to_string(t).c_str()); } update(); break; case MODE_DRAG_SELECTING: update(); // Just displaying selection rect break; case MODE_DRAGGING: // Check all keyframes to see if one is clicked for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; DTfloat dt = positionToTime(delta.x()); int num_keys = getNumKeys(_plug_event_cache[i]); // Since order can flip when keys are set, we start with the farther ahead points first // depending on direction of dt if (dt < 0.0F) { for (int k = 0; k < num_keys; ++k) { int id = _plug_event_cache[i]._keyframes->key_id(k); if (isSelected(_plug_event_cache[i], id)) { DTfloat current_time = _plug_event_cache[i]._keyframes->key_time(k); std::string cmd = "SetKeyframeTimeByID " + _plug_event_cache[i]._keyframes->full_name() + " " + MoreStrings::cast_to_string(id) + " " + MoreStrings::cast_to_string(current_time + dt); emit doCommand(cmd.c_str()); } } } else { for (int k = num_keys-1; k >= 0; --k) { int id = _plug_event_cache[i]._keyframes->key_id(k); if (isSelected(_plug_event_cache[i], id)) { DTfloat current_time = _plug_event_cache[i]._keyframes->key_time(k); std::string cmd = "SetKeyframeTimeByID " + _plug_event_cache[i]._keyframes->full_name() + " " + MoreStrings::cast_to_string(id) + " " + MoreStrings::cast_to_string(current_time + dt); emit doCommand(cmd.c_str()); } } } } update(); break; case MODE_ZOOMING: { DTfloat center_time_before = (_horz_scrollbar->value() + _controls.width() / 2) / static_cast<DTfloat>(_pixels_per_second); DTfloat zoom = -delta.y(); _pixels_per_second += zoom; if (_pixels_per_second < 5) _pixels_per_second = 5; else if (_pixels_per_second > 500) _pixels_per_second = 500; DTfloat center_time_after= (_horz_scrollbar->value() + _controls.width() / 2) / static_cast<DTfloat>(_pixels_per_second); _horz_scrollbar->setValue(_horz_scrollbar->value() - (center_time_after - center_time_before) * _pixels_per_second); onChangeTimeRange(); } break; default: break; }; _last_point = _end_point; } void EdLevelAnimationWindow::mouseReleaseEvent(QMouseEvent *event) { _end_point = event->pos(); // Translate into timeline space QPoint local_pos = _end_point + QPoint(timeToPosition(_time) - NODE_ITEM_WIDTH, -TITLE_HEIGHT); switch (getMode()) { case MODE_DRAGGING_THUMB: if (_root) { DTfloat t = positionToTime(local_pos.x()); emit doCommand(QString("SetProp \"") + _root->full_name().c_str() + ".Time_Out\" " + MoreStrings::cast_to_string(t).c_str()); } update(); break; case MODE_DRAG_SELECTING: { QRect rs; selectionRect(rs); for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; // Append selection if (event->modifiers() & Qt::SHIFT) { for (int k = 0; k < getNumKeys(_plug_event_cache[i]); ++k) { QRect rk; keyRect (_plug_event_cache[i], k, rk); if (rs.intersects(rk)) { int id = _plug_event_cache[i]._keyframes->key_id(k); // Invert keyframes if (isSelected(_plug_event_cache[i], id)) setSelected(_plug_event_cache[i], id, false); else setSelected(_plug_event_cache[i], id, true); } } // New selection } else { clearSelected (_plug_event_cache[i]); for (int k = 0; k < getNumKeys(_plug_event_cache[i]); ++k) { QRect rk; keyRect (_plug_event_cache[i], k, rk); if (rs.contains(rk)) { int id = _plug_event_cache[i]._keyframes->key_id(k); setSelected(_plug_event_cache[i], id, true); } } } } update(); } break; case MODE_DRAGGING: update(); break; default: break; } setMode(MODE_NONE); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::wheelEvent (QWheelEvent *event) { int move = -event->delta(); if (event->orientation() == Qt::Horizontal) { _horz_scrollbar->setValue(_horz_scrollbar->value() + move); } else { _vert_scrollbar->setValue(_vert_scrollbar->value() + move); } update(); event->accept(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::keyPressEvent (QKeyEvent *event) { emit doUndoBlock(); int key = event->key(); if (event->matches(QKeySequence::Delete) || key == 0x1000003) { for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; std::list<int> &selected = _plug_event_cache[i]._selected_ids; FOR_EACH (j ,selected) { std::string cmd = "ClearKeyframeByID " + _plug_event_cache[i]._keyframes->full_name() + " " + MoreStrings::cast_to_string(*j); emit doCommand(cmd.c_str()); } } clearSelected(); update(); } } //============================================================================== //============================================================================== void EdLevelAnimationWindow::setSelected (PlugEventCache &p, int id, bool selected) { if (selected) { auto i = std::find(p._selected_ids.begin(), p._selected_ids.end(), id); if (i == p._selected_ids.end()) p._selected_ids.push_back(id); } else { auto i = std::find(p._selected_ids.begin(), p._selected_ids.end(), id); if (i != p._selected_ids.end()) p._selected_ids.erase(i); } } void EdLevelAnimationWindow::clearSelected (PlugEventCache &p) { p._selected_ids.clear(); } void EdLevelAnimationWindow::clearSelected (void) { for (int i = 0; i < _plug_event_cache.size(); ++i) clearSelected(_plug_event_cache[i]); } bool EdLevelAnimationWindow::isSelected (PlugEventCache &p, int id) { auto i = std::find(p._selected_ids.begin(), p._selected_ids.end(), id); if (i == p._selected_ids.end()) return false; return true; } //============================================================================== //============================================================================== void EdLevelAnimationWindow::onRefreshAnimation(void) { scanRelevantNodes( _document->selection() ); update(); } //============================================================================== //============================================================================== void EdLevelAnimationWindow::paintEvent(QPaintEvent * /* event */) { QPainter painter(this); draw(&painter); } void EdLevelAnimationWindow::draw(QPainter *painter) { painter->setRenderHint(QPainter::Antialiasing, false); painter->setClipRect(rect()); painter->setPen(Qt::NoPen); painter->setBrush(QBrush(QColor(100,100,100,255))); painter->drawRect(rect()); painter->setBrush(QBrush(QColor(95,95,95,255))); painter->drawRect(_nodes); painter->drawRect(_title); painter->drawRect(_timeline); // // Draw Node Names // painter->resetTransform (); painter->setClipRect ( _nodes ); painter->translate (0, TITLE_HEIGHT - _scroll); for (int i = 0; i < _plug_event_cache.size(); ++i) { QRect tr, r; itemRect(_plug_event_cache[i], tr, r); if (_plug_event_cache[i]._node) { painter->setPen(QPen(QColor(100,100,100,255),0)); painter->setBrush(QBrush(QColor(130,130,130,255))); painter->drawRect(r); painter->setPen(QPen(QColor(40,40,40,255),1)); painter->setFont(_font); painter->drawText(tr, Qt::AlignLeft | Qt::AlignVCenter, _plug_event_cache[i]._title.c_str() ); } else { painter->setPen(QPen(QColor(40,40,40,255),1)); painter->setFont(_font_bold); painter->drawText(tr, Qt::AlignLeft | Qt::AlignVCenter, _plug_event_cache[i]._title.c_str() ); } } // // Draw Node Keyframes // painter->resetTransform (); painter->setClipRect ( _controls ); painter->translate (NODE_ITEM_WIDTH - timeToPosition(_time), TITLE_HEIGHT - _scroll); for (int i = 0; i < _plug_event_cache.size(); ++i) { if (!_plug_event_cache[i]._node || !_plug_event_cache[i]._keyframes) continue; QRect tr, r; itemRect(_plug_event_cache[i], tr, r); // Build a new Rect based on this one r.setLeft( timeToPosition(_time_min_sec) ); r.setWidth( timeToPosition(_time_max_sec - _time_min_sec) ); painter->setPen(QPen(QColor(100,100,100,255),0)); painter->setBrush(QBrush(QColor(130,130,130,255))); painter->drawRect(r); // Draw guide line painter->setPen(QPen(QColor(100,100,100,255),1)); painter->drawLine( timeToPosition(_time_min_sec), r.center().y(), timeToPosition(_time_max_sec - _time_min_sec), r.center().y()); if (getNumKeys(_plug_event_cache[i]) > 0) { // Draw regions between keyframes for (int k = 0; k < getNumKeys(_plug_event_cache[i])-1; ++k) { QRect r1,r2; keyRect (_plug_event_cache[i], k, r1); keyRect (_plug_event_cache[i], k+1, r2); QRect r = r1.united(r2); r.adjust(_keyframe_image.width()/2, 0, -_keyframe_image.width()/2, 0); painter->setPen(Qt::NoPen); painter->setBrush(QBrush(QColor(0,0,0,30))); painter->drawRect(r); } // Draw keyframes for (int k = 0; k < getNumKeys(_plug_event_cache[i]); ++k) { QRect r; keyRect (_plug_event_cache[i], k, r); int id = _plug_event_cache[i]._keyframes->key_id(k); if (isSelected (_plug_event_cache[i], id)) painter->drawImage(r, _keyframe_image_selected); else painter->drawImage(r, _keyframe_image); } } } // Selection if (getMode() == MODE_DRAG_SELECTING) { QRect rs; selectionRect(rs); painter->setPen(QPen(QColor(53,120,255,255),2)); painter->setBrush(QBrush(QColor(0,0,0,50))); painter->drawRoundedRect(rs, 5, 5); } // // Draw Seconds // painter->resetTransform (); painter->setClipRect ( _timeline.united(_controls) ); painter->translate (NODE_ITEM_WIDTH - timeToPosition(_time), 0); painter->setFont(_font); // Milliseconds for (int t = _time_min_sec*1000; t <= _time_max_sec*1000; t += 100) { int xpos = timeToPosition(t/1000.0F); // Full second if (t % 1000 == 0) { if (t == 0) painter->setPen(QPen(QColor(75,75,75,255),3,Qt::SolidLine)); else painter->setPen(QPen(QColor(75,75,75,255),1,Qt::SolidLine)); painter->drawLine( QPoint(xpos, TITLE_HEIGHT) , QPoint(xpos, rect().height() - _scroll_height) ); QRect tr(xpos - _pixels_per_second/2,0,_pixels_per_second,TITLE_HEIGHT); painter->setPen(QPen(QColor(25,25,25,255),1,Qt::SolidLine)); std::stringstream ss; ss << (t/1000) << " s"; painter->drawText(tr, Qt::AlignHCenter | Qt::AlignBottom, ss.str().c_str()); } else { painter->setPen(QPen(QColor(90,90,90,255),1,Qt::DotLine)); painter->drawLine( QPoint(xpos, TITLE_HEIGHT) , QPoint(xpos, rect().height() - _scroll_height) ); } } // // Draw Current Time // if (_root) { painter->resetTransform (); painter->setClipRect ( _timeline.united(_controls) ); painter->translate (NODE_ITEM_WIDTH - timeToPosition(_time), 0); DTfloat t = _root->time(); int xpos = timeToPosition(t); QRect thr; thumbRect(thr); painter->drawImage(thr, _thumb_image); painter->setPen(QPen(QColor(0,255,0,255),1,Qt::SolidLine)); painter->drawLine( QPoint(xpos, TITLE_HEIGHT) , QPoint(xpos, rect().height() - _scroll_height) ); QRect tr(xpos - _pixels_per_second/2,0,_pixels_per_second,TITLE_HEIGHT); std::stringstream ss; ss << t << " s"; painter->drawText(tr, Qt::AlignHCenter | Qt::AlignTop, ss.str().c_str()); } // // Draw Separators // painter->resetTransform (); painter->setClipRect (rect()); painter->setPen(QPen(QColor(75,75,75,255),2)); painter->setBrush(QBrush(QColor(100,100,100,255))); painter->drawLine( QPoint(0, TITLE_HEIGHT), QPoint(rect().width(), TITLE_HEIGHT) ); painter->drawLine( QPoint(NODE_ITEM_WIDTH, 0), QPoint(NODE_ITEM_WIDTH, rect().height()) ); } //============================================================================== //============================================================================== #include "moc_EdLevelAnimationWindow.cpp"
35,812
10,890
/** * Copyright (C) 2018 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/db/storage/wiredtiger/wiredtiger_recovery_unit.h" #include "mongo/base/checked_cast.h" #include "mongo/db/repl/repl_settings.h" #include "mongo/db/repl/replication_coordinator_mock.h" #include "mongo/db/service_context.h" #include "mongo/db/storage/recovery_unit_test_harness.h" #include "mongo/db/storage/wiredtiger/wiredtiger_kv_engine.h" #include "mongo/db/storage/wiredtiger/wiredtiger_record_store.h" #include "mongo/db/storage/wiredtiger/wiredtiger_session_cache.h" #include "mongo/db/storage/wiredtiger/wiredtiger_util.h" #include "mongo/unittest/temp_dir.h" #include "mongo/unittest/unittest.h" #include "mongo/util/clock_source_mock.h" namespace mongo { namespace { class WiredTigerRecoveryUnitHarnessHelper final : public RecoveryUnitHarnessHelper { public: WiredTigerRecoveryUnitHarnessHelper() : _dbpath("wt_test"), _engine(kWiredTigerEngineName, // .canonicalName _dbpath.path(), // .path &_cs, // .cs "", // .extraOpenOptions 1, // .cacheSizeGB false, // .durable false, // .ephemeral false, // .repair false // .readOnly ) { repl::ReplicationCoordinator::set( getGlobalServiceContext(), std::unique_ptr<repl::ReplicationCoordinator>(new repl::ReplicationCoordinatorMock( getGlobalServiceContext(), repl::ReplSettings()))); } ~WiredTigerRecoveryUnitHarnessHelper() {} virtual std::unique_ptr<RecoveryUnit> newRecoveryUnit() final { return std::unique_ptr<RecoveryUnit>(_engine.newRecoveryUnit()); } virtual std::unique_ptr<RecordStore> createRecordStore(OperationContext* opCtx, const std::string& ns) final { std::string uri = "table:" + ns; const bool prefixed = false; StatusWith<std::string> result = WiredTigerRecordStore::generateCreateString( kWiredTigerEngineName, ns, CollectionOptions(), "", prefixed); ASSERT_TRUE(result.isOK()); std::string config = result.getValue(); { WriteUnitOfWork uow(opCtx); WiredTigerRecoveryUnit* ru = checked_cast<WiredTigerRecoveryUnit*>(opCtx->recoveryUnit()); WT_SESSION* s = ru->getSession()->getSession(); invariantWTOK(s->create(s, uri.c_str(), config.c_str())); uow.commit(); } WiredTigerRecordStore::Params params; params.ns = ns; params.uri = uri; params.engineName = kWiredTigerEngineName; params.isCapped = false; params.isEphemeral = false; params.cappedMaxSize = -1; params.cappedMaxDocs = -1; params.cappedCallback = nullptr; params.sizeStorer = nullptr; params.isReadOnly = false; auto ret = stdx::make_unique<StandardWiredTigerRecordStore>(&_engine, opCtx, params); ret->postConstructorInit(opCtx); return std::move(ret); } WiredTigerKVEngine* getEngine() { return &_engine; } private: unittest::TempDir _dbpath; ClockSourceMock _cs; WiredTigerKVEngine _engine; }; std::unique_ptr<HarnessHelper> makeHarnessHelper() { return std::make_unique<WiredTigerRecoveryUnitHarnessHelper>(); } MONGO_INITIALIZER(RegisterHarnessFactory)(InitializerContext* const) { mongo::registerHarnessHelperFactory(makeHarnessHelper); return Status::OK(); } class WiredTigerRecoveryUnitTestFixture : public unittest::Test { public: typedef std::pair<ServiceContext::UniqueClient, ServiceContext::UniqueOperationContext> ClientAndCtx; ClientAndCtx makeClientAndOpCtx(RecoveryUnitHarnessHelper* harnessHelper, const std::string& clientName) { auto sc = harnessHelper->serviceContext(); auto client = sc->makeClient(clientName); auto opCtx = client->makeOperationContext(); opCtx->setRecoveryUnit(harnessHelper->newRecoveryUnit(), WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork); return std::make_pair(std::move(client), std::move(opCtx)); } void getCursor(WiredTigerRecoveryUnit* ru, WT_CURSOR** cursor) { WT_SESSION* wt_session = ru->getSession()->getSession(); invariantWTOK(wt_session->create(wt_session, wt_uri, wt_config)); invariantWTOK(wt_session->open_cursor(wt_session, wt_uri, NULL, NULL, cursor)); } void setUp() override { harnessHelper = std::make_unique<WiredTigerRecoveryUnitHarnessHelper>(); clientAndCtx1 = makeClientAndOpCtx(harnessHelper.get(), "writer"); clientAndCtx2 = makeClientAndOpCtx(harnessHelper.get(), "reader"); ru1 = checked_cast<WiredTigerRecoveryUnit*>(clientAndCtx1.second->recoveryUnit()); ru2 = checked_cast<WiredTigerRecoveryUnit*>(clientAndCtx2.second->recoveryUnit()); } std::unique_ptr<WiredTigerRecoveryUnitHarnessHelper> harnessHelper; ClientAndCtx clientAndCtx1, clientAndCtx2; WiredTigerRecoveryUnit *ru1, *ru2; private: const char* wt_uri = "table:prepare_transaction"; const char* wt_config = "key_format=S,value_format=S"; }; TEST_F(WiredTigerRecoveryUnitTestFixture, SetReadSource) { ru1->setTimestampReadSource(RecoveryUnit::ReadSource::kProvided, Timestamp(1, 1)); ASSERT_EQ(RecoveryUnit::ReadSource::kProvided, ru1->getTimestampReadSource()); ASSERT_EQ(Timestamp(1, 1), ru1->getPointInTimeReadTimestamp()); } TEST_F(WiredTigerRecoveryUnitTestFixture, CreateAndCheckForCachePressure) { int time = 1; // Reconfigure the size of the cache to be very small so that building cache pressure is fast. WiredTigerKVEngine* engine = harnessHelper->getEngine(); std::string cacheSizeReconfig = "cache_size=1MB"; ASSERT_EQ(engine->reconfigure(cacheSizeReconfig.c_str()), 0); OperationContext* opCtx = clientAndCtx1.second.get(); std::unique_ptr<RecordStore> rs(harnessHelper->createRecordStore(opCtx, "a.b")); // Insert one document so that we can then update it in a loop to create cache pressure. // Note: inserts will not create cache pressure. WriteUnitOfWork wu(opCtx); ASSERT_OK(ru1->setTimestamp(Timestamp(time++))); std::string str = str::stream() << "foobarbaz"; StatusWith<RecordId> ress = rs->insertRecord(opCtx, str.c_str(), str.size() + 1, Timestamp()); ASSERT_OK(ress.getStatus()); auto recordId = ress.getValue(); wu.commit(); for (int j = 0; j < 1000; ++j) { // Once we hit the cache pressure threshold, i.e. have successfully created cache pressure // that is detectable, we are done. if (engine->isCacheUnderPressure(opCtx)) { invariant(j != 0); break; } try { WriteUnitOfWork wuow(opCtx); ASSERT_OK(ru1->setTimestamp(Timestamp(time++))); std::string s = str::stream() << "abcbcdcdedefefgfghghihijijkjklklmlmnmnomopopqpqrqrsrststutuv" << j; ASSERT_OK(rs->updateRecord(opCtx, recordId, s.c_str(), s.size() + 1, nullptr)); wuow.commit(); } catch (const DBException& ex) { invariant(ex.toStatus().code() == ErrorCodes::WriteConflict); } } } TEST_F(WiredTigerRecoveryUnitTestFixture, LocalReadOnADocumentBeingPreparedTriggersPrepareConflict) { // Prepare but don't commit a transaction ru1->beginUnitOfWork(clientAndCtx1.second.get()); WT_CURSOR* cursor; getCursor(ru1, &cursor); cursor->set_key(cursor, "key"); cursor->set_value(cursor, "value"); invariantWTOK(cursor->insert(cursor)); ru1->setPrepareTimestamp({1, 1}); ru1->prepareUnitOfWork(); // Transaction read default triggers WT_PREPARE_CONFLICT ru2->beginUnitOfWork(clientAndCtx2.second.get()); getCursor(ru2, &cursor); cursor->set_key(cursor, "key"); int ret = cursor->search(cursor); ASSERT_EQ(WT_PREPARE_CONFLICT, ret); ru1->abortUnitOfWork(); ru2->abortUnitOfWork(); } TEST_F(WiredTigerRecoveryUnitTestFixture, AvailableReadOnADocumentBeingPreparedDoesNotTriggerPrepareConflict) { // Prepare but don't commit a transaction ru1->beginUnitOfWork(clientAndCtx1.second.get()); WT_CURSOR* cursor; getCursor(ru1, &cursor); cursor->set_key(cursor, "key"); cursor->set_value(cursor, "value"); invariantWTOK(cursor->insert(cursor)); ru1->setPrepareTimestamp({1, 1}); ru1->prepareUnitOfWork(); // Transaction that should ignore prepared transactions won't trigger // WT_PREPARE_CONFLICT ru2->beginUnitOfWork(clientAndCtx2.second.get()); ru2->setIgnorePrepared(true); getCursor(ru2, &cursor); cursor->set_key(cursor, "key"); int ret = cursor->search(cursor); ASSERT_EQ(WT_NOTFOUND, ret); ru1->abortUnitOfWork(); ru2->abortUnitOfWork(); } TEST_F(WiredTigerRecoveryUnitTestFixture, WriteOnADocumentBeingPreparedTriggersWTRollback) { // Prepare but don't commit a transaction ru1->beginUnitOfWork(clientAndCtx1.second.get()); WT_CURSOR* cursor; getCursor(ru1, &cursor); cursor->set_key(cursor, "key"); cursor->set_value(cursor, "value"); invariantWTOK(cursor->insert(cursor)); ru1->setPrepareTimestamp({1, 1}); ru1->prepareUnitOfWork(); // Another transaction with write triggers WT_ROLLBACK ru2->beginUnitOfWork(clientAndCtx2.second.get()); getCursor(ru2, &cursor); cursor->set_key(cursor, "key"); cursor->set_value(cursor, "value2"); int ret = cursor->insert(cursor); ASSERT_EQ(WT_ROLLBACK, ret); ru1->abortUnitOfWork(); ru2->abortUnitOfWork(); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsPassedEmptyLastTimestampSetOnCommitWithNoTimestamp) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); wuow.commit(); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsPassedLastTimestampSetOnCommit) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT(!commitTs); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts2)); ASSERT(!commitTs); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsNotPassedLastTimestampSetOnAbort) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT(!commitTs); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsPassedCommitTimestamp) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsNotPassedCommitTimestampIfCleared) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); opCtx->recoveryUnit()->clearCommitTimestamp(); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); wuow.commit(); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsPassedNewestCommitTimestamp) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); opCtx->recoveryUnit()->setCommitTimestamp(ts2); ASSERT(!commitTs); opCtx->recoveryUnit()->clearCommitTimestamp(); ASSERT(!commitTs); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, ChangeIsNotPassedCommitTimestampOnAbort) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, CommitTimestampBeforeSetTimestampOnCommit) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); opCtx->recoveryUnit()->setCommitTimestamp(ts2); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts2); } ASSERT_EQ(*commitTs, ts2); opCtx->recoveryUnit()->clearCommitTimestamp(); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT_EQ(*commitTs, ts2); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, CommitTimestampAfterSetTimestampOnCommit) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts2)); ASSERT(!commitTs); wuow.commit(); ASSERT_EQ(*commitTs, ts2); } ASSERT_EQ(*commitTs, ts2); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT_EQ(*commitTs, ts2); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_EQ(*commitTs, ts2); wuow.commit(); ASSERT_EQ(*commitTs, ts1); } ASSERT_EQ(*commitTs, ts1); } TEST_F(WiredTigerRecoveryUnitTestFixture, CommitTimestampBeforeSetTimestampOnAbort) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); opCtx->recoveryUnit()->setCommitTimestamp(ts2); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); } ASSERT(!commitTs); opCtx->recoveryUnit()->clearCommitTimestamp(); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts1)); ASSERT(!commitTs); } ASSERT(!commitTs); } TEST_F(WiredTigerRecoveryUnitTestFixture, CommitTimestampAfterSetTimestampOnAbort) { boost::optional<Timestamp> commitTs = boost::none; auto opCtx = clientAndCtx1.second.get(); Timestamp ts1(5, 5); Timestamp ts2(6, 6); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); ASSERT_OK(opCtx->recoveryUnit()->setTimestamp(ts2)); ASSERT(!commitTs); } ASSERT(!commitTs); opCtx->recoveryUnit()->setCommitTimestamp(ts1); ASSERT(!commitTs); { WriteUnitOfWork wuow(opCtx); opCtx->recoveryUnit()->onCommit( [&](boost::optional<Timestamp> commitTime) { commitTs = commitTime; }); ASSERT(!commitTs); } ASSERT(!commitTs); } } // namespace } // namespace mongo
19,353
6,485
/* * Copyright 2019-present Facebook, 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. */ #include <folly/Portability.h> #if FOLLY_HAS_COROUTINES #include <folly/ScopeGuard.h> #include <folly/Traits.h> #include <folly/experimental/coro/AsyncGenerator.h> #include <folly/experimental/coro/Baton.h> #include <folly/experimental/coro/BlockingWait.h> #include <folly/experimental/coro/Collect.h> #include <folly/experimental/coro/Sleep.h> #include <folly/experimental/coro/Task.h> #include <folly/experimental/coro/WithCancellation.h> #include <folly/futures/Future.h> #include <folly/portability/GTest.h> #include <chrono> #include <map> #include <string> #include <tuple> TEST(AsyncGenerator, DefaultConstructedGeneratorIsEmpty) { folly::coro::blockingWait([]() -> folly::coro::Task<void> { folly::coro::AsyncGenerator<int> g; auto result = co_await g.next(); CHECK(!result); }()); } TEST(AsyncGenerator, GeneratorDestroyedBeforeCallingBegin) { bool started = false; auto makeGenerator = [&]() -> folly::coro::AsyncGenerator<int> { started = true; co_return; }; { auto gen = makeGenerator(); (void)gen; } CHECK(!started); } TEST(AsyncGenerator, PartiallyConsumingSequenceDestroysObjectsInScope) { bool started = false; bool destroyed = false; auto makeGenerator = [&]() -> folly::coro::AsyncGenerator<int> { SCOPE_EXIT { destroyed = true; }; started = true; co_yield 1; co_yield 2; co_return; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { { auto gen = makeGenerator(); CHECK(!started); CHECK(!destroyed); auto result = co_await gen.next(); CHECK(started); CHECK(!destroyed); CHECK(result); CHECK_EQ(1, *result); } CHECK(destroyed); }()); } TEST(AsyncGenerator, FullyConsumeSequence) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<int> { for (int i = 0; i < 4; ++i) { co_yield i; } }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK(result); CHECK_EQ(0, *result); result = co_await gen.next(); CHECK(result); CHECK_EQ(1, *result); result = co_await gen.next(); CHECK(result); CHECK_EQ(2, *result); result = co_await gen.next(); CHECK(result); CHECK_EQ(3, *result); result = co_await gen.next(); CHECK(!result); }()); } namespace { struct SomeError : std::exception {}; } // namespace TEST(AsyncGenerator, ThrowExceptionBeforeFirstYield) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<int> { if (true) { throw SomeError{}; } co_return; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); bool caughtException = false; try { (void)co_await gen.next(); CHECK(false); } catch (const SomeError&) { caughtException = true; } CHECK(caughtException); }()); } TEST(AsyncGenerator, ThrowExceptionAfterFirstYield) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<int> { co_yield 42; throw SomeError{}; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK(result); CHECK_EQ(42, *result); bool caughtException = false; try { (void)co_await gen.next(); CHECK(false); } catch (const SomeError&) { caughtException = true; } CHECK(caughtException); }()); } TEST(AsyncGenerator, ConsumingManySynchronousElementsDoesNotOverflowStack) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<std::uint64_t> { for (std::uint64_t i = 0; i < 1'000'000; ++i) { co_yield i; } }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); std::uint64_t sum = 0; while (auto result = co_await gen.next()) { sum += *result; } CHECK_EQ(499999500000u, sum); }()); } TEST(AsyncGenerator, ProduceResultsAsynchronously) { folly::coro::blockingWait([&]() -> folly::coro::Task<void> { folly::Executor* executor = co_await folly::coro::co_current_executor; auto makeGenerator = [&]() -> folly::coro::AsyncGenerator<int> { using namespace std::literals::chrono_literals; CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_await folly::coro::sleep(1ms); CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_yield 1; CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_await folly::coro::sleep(1ms); CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_yield 2; CHECK_EQ(executor, co_await folly::coro::co_current_executor); co_await folly::coro::sleep(1ms); CHECK_EQ(executor, co_await folly::coro::co_current_executor); }; auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(1, *result); result = co_await gen.next(); CHECK_EQ(2, *result); result = co_await gen.next(); CHECK(!result); }()); } struct ConvertibleToIntReference { int value; operator int&() { return value; } }; TEST(AsyncGenerator, GeneratorOfLValueReference) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<int&> { int value = 10; co_yield value; // Consumer gets a mutable reference to the value and can modify it. CHECK_EQ(20, value); // NOTE: Not allowed to yield an rvalue from an AsyncGenerator<T&>? // co_yield 30; // Compile-error co_yield ConvertibleToIntReference{30}; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(10, result.value()); *result = 20; result = co_await gen.next(); CHECK_EQ(30, result.value()); result = co_await gen.next(); CHECK(!result.has_value()); }()); } struct ConvertibleToInt { operator int() const { return 99; } }; TEST(AsyncGenerator, GeneratorOfConstLValueReference) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<const int&> { int value = 10; co_yield value; // Consumer gets a const reference to the value. // Allowed to yield an rvalue from an AsyncGenerator<const T&>. co_yield 30; co_yield ConvertibleToInt{}; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(10, *result); result = co_await gen.next(); CHECK_EQ(30, *result); result = co_await gen.next(); CHECK_EQ(99, *result); result = co_await gen.next(); CHECK(!result); }()); } TEST(AsyncGenerator, GeneratorOfRValueReference) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<std::unique_ptr<int>&&> { co_yield std::make_unique<int>(10); auto ptr = std::make_unique<int>(20); co_yield std::move(ptr); CHECK(ptr == nullptr); }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(10, **result); // Don't move it to a local var. result = co_await gen.next(); CHECK_EQ(20, **result); auto ptr = *result; // Move it to a local var. result = co_await gen.next(); CHECK(!result); }()); } struct MoveOnly { explicit MoveOnly(int value) : value_(value) {} MoveOnly(MoveOnly&& other) noexcept : value_(std::exchange(other.value_, -1)) {} ~MoveOnly() {} MoveOnly& operator=(MoveOnly&&) = delete; int value() const { return value_; } private: int value_; }; TEST(AsyncGenerator, GeneratorOfMoveOnlyType) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<MoveOnly> { MoveOnly rvalue(1); co_yield std::move(rvalue); CHECK_EQ(-1, rvalue.value()); co_yield MoveOnly(2); }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); // NOTE: It's an error to dereference using '*it' as this returns a copy // of the iterator's reference type, which in this case is 'MoveOnly'. CHECK_EQ(1, result->value()); result = co_await gen.next(); CHECK_EQ(2, result->value()); result = co_await gen.next(); CHECK(!result); }()); } TEST(AsyncGenerator, GeneratorOfConstValue) { auto makeGenerator = []() -> folly::coro::AsyncGenerator<const int> { // OK to yield prvalue co_yield 42; // OK to yield lvalue int x = 123; co_yield x; co_yield ConvertibleToInt{}; }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); CHECK_EQ(42, *result); static_assert(std::is_same_v<decltype(*result), const int&>); result = co_await gen.next(); CHECK_EQ(123, *result); result = co_await gen.next(); CHECK_EQ(99, *result); result = co_await gen.next(); CHECK(!result); }()); } TEST(AsyncGenerator, ExplicitValueType) { std::map<std::string, std::string> items; items["foo"] = "hello"; items["bar"] = "goodbye"; auto makeGenerator = [&]() -> folly::coro::AsyncGenerator< std::tuple<const std::string&, std::string&>, std::tuple<std::string, std::string>> { for (auto& [k, v] : items) { co_yield{k, v}; } }; folly::coro::blockingWait([&]() -> folly::coro::Task<void> { auto gen = makeGenerator(); auto result = co_await gen.next(); { auto [kRef, vRef] = *result; CHECK_EQ("bar", kRef); CHECK_EQ("goodbye", vRef); decltype(gen)::value_type copy = *result; vRef = "au revoir"; CHECK_EQ("goodbye", std::get<1>(copy)); CHECK_EQ("au revoir", std::get<1>(*result)); } }()); CHECK_EQ("au revoir", items["bar"]); } TEST(AsyncGenerator, InvokeLambda) { folly::coro::blockingWait([]() -> folly::coro::Task<void> { auto ptr = std::make_unique<int>(123); auto gen = folly::coro::co_invoke( [p = std::move(ptr)]() mutable -> folly::coro::AsyncGenerator<std::unique_ptr<int>&&> { co_yield std::move(p); }); auto result = co_await gen.next(); CHECK(result); ptr = *result; CHECK(ptr); CHECK(*ptr == 123); }()); } template <typename Ref, typename Value = folly::remove_cvref_t<Ref>> folly::coro::AsyncGenerator<Ref, Value> neverStream() { folly::coro::Baton baton; folly::CancellationCallback cb{ co_await folly::coro::co_current_cancellation_token, [&] { baton.post(); }}; co_await baton; } TEST(AsyncGenerator, CancellationTokenPropagatesFromConsumer) { folly::coro::blockingWait([]() -> folly::coro::Task<void> { folly::CancellationSource cancelSource; bool suspended = false; bool done = false; co_await folly::coro::collectAll( folly::coro::co_withCancellation( cancelSource.getToken(), [&]() -> folly::coro::Task<void> { auto stream = neverStream<int>(); suspended = true; auto result = co_await stream.next(); CHECK(!result.has_value()); done = true; }()), [&]() -> folly::coro::Task<void> { co_await folly::coro::co_reschedule_on_current_executor; co_await folly::coro::co_reschedule_on_current_executor; co_await folly::coro::co_reschedule_on_current_executor; CHECK(suspended); CHECK(!done); cancelSource.requestCancellation(); }()); CHECK(done); }()); } #endif
12,266
4,305
//+------------------------------------------------------------------ // // File: culong.cxx // // Contents: implementation for CUlongCmdlineObj // // Synoposis: Encapsulates a command line switch which takes an // unsigned long value, eg: /maxusers:10 // // Classes: CUlongCmdlineObj // // Functions: // // History: 06/15/92 DeanE Stolen from CIntCmdlineObj code // 07/29/92 davey Added nlsType and nlsLineArgType // 09/09/92 Lizch Changed SUCCESS to NO_ERROR // 09/18/92 Lizch Precompile headers // 11/14/92 DwightKr Updates for new version of NLS_STR // 10/14/93 DeanE Converted to NCHAR // //------------------------------------------------------------------- #include <comtpch.hxx> #pragma hdrstop #include <cmdlinew.hxx> // public cmdlinew stuff #include "_clw.hxx" // private cmdlinew stuff #include <ctype.h> // is functions INT StringToUlong(LPCNSTR pnszInt, ULONG *pUlong); LPCNSTR nszCmdlineUlong = _TEXTN("Takes an unsigned long "); LPCNSTR nszLineArgUlong = _TEXTN("<ulong> "); //+------------------------------------------------------------------ // // Member: CUlongCmdlineObj destructor // // Synoposis: Frees any memory associated with the object // // History: Added to allow casting of pValue 05/12/92 Lizch // Integrated into CUlongCmdlineObj 6/15/92 DeanE // //------------------------------------------------------------------- CUlongCmdlineObj::~CUlongCmdlineObj() { delete (ULONG *)_pValue; _pValue = NULL; } //+------------------------------------------------------------------ // // Member: CUlongCmdlineObj::SetValue, public // // Synposis: Stores the ulong value specified after the switch // string, eg. 10 for /maxusers:10 // // Effects: This implementation for the virtual method SetValue // converts the characters following the switch to an unsigned // long. It allocates memory for the ulong. // If there is no equator character, or if there // is no character following the equator character, _pValue // remains NULL. // // Arguments: [nszArg] - the string following the switch on the // command line. Includes the equator (eg. // ':' or '=' ), if any. // // Returns: CMDLINE_NO_ERROR, CMDLINE_ERROR_OUT_OF_MEMORY, // CMDLINE_ERROR_TOO_BIG, CMDLINE_ERROR_INVALID_VALUE // // History: Created 12/27/91 Lizch // Converted to NLS_STR 4/17/92 Lizch // Integrated into CUlongCmdlineObj 6/15/92 DeanE // //------------------------------------------------------------------- INT CUlongCmdlineObj::SetValue(LPCNSTR nszArg) { INT iRC; // delete any existing _pValue delete (ULONG *)_pValue; _pValue = NULL; _pValue = new ULONG; if (_pValue == NULL) { return (CMDLINE_ERROR_OUT_OF_MEMORY); } // I'm using this rather than c runtime atol so that I // can detect error conditions like overflow and non-digits. iRC = StringToUlong(nszArg, (ULONG *)_pValue); if (iRC != CMDLINE_NO_ERROR) { delete (ULONG *)_pValue; _pValue = NULL; } return(iRC); } //+------------------------------------------------------------------ // // Member: CUlongCmdlineObj::GetValue, public // // Synposis: Returns a pointer to ULONG that holds the value. // // Arguments: void // // Returns: ULONG value at *_pValue. // // History: Created 12/27/91 Lizch // Converted to NLS_STR 4/17/92 Lizch // Integrated into CUlongCmdlineObj 6/15/92 DeanE // //------------------------------------------------------------------- const ULONG *CUlongCmdlineObj::GetValue() { return((ULONG *)_pValue); } //+------------------------------------------------------------------ // // Member: CUlongCmdlineObj::DisplayValue, public // // Synoposis: Prints the stored command line value accordint to // current display method. Generally this will be to stdout. // // History: Created 12/27/91 Lizch // Converted to NLS_STR 4/17/92 Lizch // Integrated into CUlongCmdlineObj 6/15/92 DeanE // //------------------------------------------------------------------- void CUlongCmdlineObj::DisplayValue() { if (_pValue != NULL) { _sNprintf(_nszErrorBuf, _TEXTN("Command line switch %s has value %lu\n"), _pnszSwitch, *(ULONG *)_pValue); (*_pfnDisplay)(_nszErrorBuf); } else { DisplayNoValue(); } } //+------------------------------------------------------------------ // // Function: StringToUlong // // Synoposis: Converts given string to unsigned long, checking for // overflow and illegal characters. Only +, - and digits // are accepted. // // Arguments: [nszUlong] - string to convert // [pUlong] - pointer to converted unsigned long // // Returns: CMDLINE_NO_ERROR, CMDLINE_ERROR_INVALID_VALUE, // CMDLINE_ERROR_TOO_BIG // // History: Created 12/17/91 Lizch // Converted to AsciiToUlong 6/15/92 DeanE // Added in conversion of Hex 12/27/94 DaveY // // Notes: I'm using this rather than c runtime atoi so that I // can detect error conditions like overflow and non-digits. // The sign is checked for and stored, although it is not // used - so a negative value will still be converted to // an unsigned equivalent. // //------------------------------------------------------------------- INT StringToUlong(LPCNSTR nszUlong, ULONG *pUlong) { short sNegator = 1; ULONG ulResult = 0; INT iRC = CMDLINE_NO_ERROR; // Skip any leading spaces - these can occur if the command line // switch incorporates spaces, eg "/a: 123" // while (_isnspace(*nszUlong)) { nszUlong++; } // Get sign - ignore for now switch (*nszUlong) { case '-': sNegator = -1; nszUlong++; break; case '+': sNegator = 1; nszUlong++; break; default: break; } // see if using hex values if ((*nszUlong == _TEXTN('0')) && ((*(nszUlong+1) == _TEXTN('x')) || (*(nszUlong+1) == _TEXTN('X')))) { nszUlong += 2; // pass the "0x" int max = sizeof(ULONG) << 1; // number of hex digits possible for(int i=0; *nszUlong != NULL && i < max; i++, nszUlong++) { if ((_TEXTN('0') <= *nszUlong ) && (*nszUlong <= _TEXTN('9'))) { ulResult = ulResult * 16 + (*nszUlong - _TEXTN('0')); } else if ((_TEXTN('A') <= *nszUlong ) && (*nszUlong <= _TEXTN('F'))) { ulResult = ulResult * 16 + 10 + (*nszUlong - _TEXTN('A')); } else if ((_TEXTN('a') <= *nszUlong) && (*nszUlong <= _TEXTN('f'))) { ulResult = ulResult * 16 + 10 + (*nszUlong - _TEXTN('a')); } else { iRC = CMDLINE_ERROR_INVALID_VALUE; ulResult = 0; break; } } if ((i >= max) && (*nszUlong != NULL)) { iRC = CMDLINE_ERROR_INVALID_VALUE; ulResult = 0; } *pUlong = ulResult; return iRC; } // must be decimal for (;*nszUlong != L'\0'; nszUlong++) { if (!_isndigit(*nszUlong)) { ulResult = 0; iRC = CMDLINE_ERROR_INVALID_VALUE; break; } ULONG ulPrevious = ulResult; ulResult = (ulResult * 10) + (*nszUlong - '0'); // Check for overflow by checking that the previous result is less // than the current result - if the previous one was bigger, we've // overflowed! // if (ulResult < ulPrevious) { ulResult = 0; iRC = CMDLINE_ERROR_TOO_BIG; break; } } *pUlong = ulResult; return(iRC); } //+------------------------------------------------------------------- // // Method: CUlongCmdlineObj::QueryCmdlineType, protected, const // // Synoposis: returns a character pointer to the cmdline type. // // Arguments: None. // // Returns: const NCHAR pointer to string. // // History: 28-Jul-92 davey Created. // //-------------------------------------------------------------------- LPCNSTR CUlongCmdlineObj::QueryCmdlineType() const { return(nszCmdlineUlong); } //+------------------------------------------------------------------- // // Method: CUlongCmdlineObj::QueryLineArgType, protected, const // // Synoposis: returns a character pointer to the line arg type. // // Arguments: None. // // Returns: const NLS_STR reference to string. // // History: 28-Jul-92 davey Created. // //-------------------------------------------------------------------- LPCNSTR CUlongCmdlineObj::QueryLineArgType() const { // if user has not defined one then give default one if (_pnszLineArgType == NULL) { return(nszLineArgUlong); } else { return(_pnszLineArgType); } }
9,922
3,197
//===- BinaryReader.cpp ---------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <mcld/LD/BinaryReader.h> using namespace mcld; //===----------------------------------------------------------------------===// // BinaryReader //===----------------------------------------------------------------------===// BinaryReader::~BinaryReader() { }
600
130
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #ifndef TURI_SGRAPH_TEST_DEGREE_COUNT_HPP #define TURI_SGRAPH_TEST_DEGREE_COUNT_HPP #include <sgraph/sgraph.hpp> #include "sgraph_test_util.hpp" using namespace turi; typedef std::function< std::vector<std::pair<flexible_type, flexible_type>>(sgraph&, sgraph::edge_direction)> degree_count_fn_type; // Takes a degree count function (graph, DIR) -> [(id, degree), (id_degree)] // Check it computes the right degree on various of graphs void check_degree_count(degree_count_fn_type degree_count_fn) { size_t n_vertex = 1000; size_t n_partition = 4; typedef sgraph::edge_direction edge_direction; { // for single directional ring graph sgraph g = create_ring_graph(n_vertex, n_partition, false /* one direction */); std::vector<std::pair<flexible_type, flexible_type>> in_degree = degree_count_fn(g, edge_direction::IN_EDGE); std::vector<std::pair<flexible_type, flexible_type>> out_degree = degree_count_fn(g, edge_direction::OUT_EDGE); std::vector<std::pair<flexible_type, flexible_type>> total_degree = degree_count_fn(g, edge_direction::ANY_EDGE); TS_ASSERT_EQUALS(in_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(out_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(total_degree.size(), g.num_vertices()); for (size_t i = 0; i < g.num_vertices(); ++i) { TS_ASSERT_EQUALS((int)out_degree[i].second, 1); TS_ASSERT_EQUALS((int)in_degree[i].second, 1); TS_ASSERT_EQUALS((int)total_degree[i].second, 2); TS_ASSERT_EQUALS((int)out_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)in_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)total_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); } } { // for bi-directional ring graph sgraph g = create_ring_graph(n_vertex, n_partition, true /* bi direction */); std::vector<std::pair<flexible_type, flexible_type>> in_degree = degree_count_fn(g, edge_direction::IN_EDGE); std::vector<std::pair<flexible_type, flexible_type>> out_degree = degree_count_fn(g, edge_direction::OUT_EDGE); std::vector<std::pair<flexible_type, flexible_type>> total_degree = degree_count_fn(g, edge_direction::ANY_EDGE); TS_ASSERT_EQUALS(in_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(out_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(total_degree.size(), g.num_vertices()); for (size_t i = 0; i < g.num_vertices(); ++i) { TS_ASSERT_EQUALS((int)out_degree[i].second, 2); TS_ASSERT_EQUALS((int)in_degree[i].second, 2); TS_ASSERT_EQUALS((int)total_degree[i].second, 4); TS_ASSERT_EQUALS((int)out_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)in_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)total_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); } } { // for star graph sgraph g = create_star_graph(n_vertex, n_partition); std::vector<std::pair<flexible_type, flexible_type>> in_degree = degree_count_fn(g, edge_direction::IN_EDGE); std::vector<std::pair<flexible_type, flexible_type>> out_degree = degree_count_fn(g, edge_direction::OUT_EDGE); std::vector<std::pair<flexible_type, flexible_type>> total_degree = degree_count_fn(g, edge_direction::ANY_EDGE); TS_ASSERT_EQUALS(in_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(out_degree.size(), g.num_vertices()); TS_ASSERT_EQUALS(total_degree.size(), g.num_vertices()); for (size_t i = 0; i < g.num_vertices(); ++i) { TS_ASSERT_EQUALS((int)in_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)out_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); TS_ASSERT_EQUALS((int)total_degree[i].second.get_type(), (int)flex_type_enum::INTEGER); if (in_degree[i].first == 0) { TS_ASSERT_EQUALS((int)in_degree[i].second, n_vertex -1); } else { TS_ASSERT_EQUALS((int)in_degree[i].second, 0); } if (out_degree[i].first == 0) { TS_ASSERT_EQUALS((int)out_degree[i].second, 0); } else { TS_ASSERT_EQUALS((int)out_degree[i].second, 1); } if (total_degree[i].first == 0) { TS_ASSERT_EQUALS((int)total_degree[i].second, n_vertex -1); } else { TS_ASSERT_EQUALS((int)total_degree[i].second, 1); } } } } #endif
4,698
1,916
#include <../../nrnconf.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #include <unistd.h> #include "mos2nrn.h" static void getdname(char* dname); #include <string.h> const char* back2forward(const char*); const char* basefile(const char*); int main(int argc, char** argv) { char buf[256]; char dname[256]; if (argc != 2 ) { fprintf(stderr, "Usage: mos2nrn [hocfile | nrnzipfile]\n"); return 1; } FILE* f = fopen(argv[1], "r"); if (!f) { return 1; } if (fread(buf, 1, 5, f) < 2) { return 1; } fclose(f); if (strncmp(buf, "PK", 2) == 0) { // its a nrnzip file getdname(dname); assert(snprintf(buf, 256, "xterm -sb -e %s/mos2nrn2.sh %s %s %d", NEURON_BIN_DIR, argv[1], dname, 0) < 256); int i = system(buf); if (i) { return i; } }else{ // its a hoc file sprintf(buf, "xterm -sb -e %s/nrniv %s -", NEURON_BIN_DIR, argv[1]); int i = system(buf); if (i) { return i; } } return 0; } const char* back2forward(const char* back) { static char forward[256]; char *cp; strcpy(forward, back); for (cp = forward; *cp; ++cp) { if (*cp == '\\') { *cp = '/'; } } return forward; } const char* basefile(const char* path) { const char* cp; for (cp = path + strlen(path) - 1; cp >= path; --cp) { if (*cp == '\\' || *cp == ':' || *cp == '/') { return cp+1; } } return path; } static void getdname(char* dname) { int fd; const char* tdir; if ((tdir = getenv("TEMP")) == NULL) { tdir = "/tmp"; } sprintf(dname, "%s/nrnXXXXXX", tdir); #if HAVE_MKSTEMP fd = mkstemp(dname); close(fd); #else mktemp(dname); #endif }
1,591
777
#include "./cells.hpp" namespace GS_DDMRM { namespace S_IceRay { namespace S_material { namespace S_pattern { namespace S_noise { GS_DDMRM::S_IceRay::S_utility::S_table::GC_value<3,1> GC_cells::M2s_table; } } } } }
320
132
/* * Copyright 2016 The Cartographer Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cartographer_ros/ros_log_sink.h" #include <chrono> #include <cstring> #include <string> #include <thread> #include "glog/log_severity.h" #include "ros/console.h" namespace cartographer_ros { namespace { const char* GetBasename(const char* filepath) { const char* base = std::strrchr(filepath, '/'); return base ? (base + 1) : filepath; } } // namespace ScopedRosLogSink::ScopedRosLogSink() : will_die_(false) { AddLogSink(this); } ScopedRosLogSink::~ScopedRosLogSink() { RemoveLogSink(this); } void ScopedRosLogSink::send(const ::google::LogSeverity severity, const char* const filename, const char* const base_filename, const int line, const struct std::tm* const tm_time, const char* const message, const size_t message_len) { const std::string message_string = ::google::LogSink::ToString( severity, GetBasename(filename), line, tm_time, message, message_len); switch (severity) { case ::google::GLOG_INFO: ROS_INFO_STREAM(message_string); break; case ::google::GLOG_WARNING: ROS_WARN_STREAM(message_string); break; case ::google::GLOG_ERROR: ROS_ERROR_STREAM(message_string); break; case ::google::GLOG_FATAL: ROS_FATAL_STREAM(message_string); will_die_ = true; break; } } void ScopedRosLogSink::WaitTillSent() { if (will_die_) { // Give ROS some time to actually publish our message. std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } } } // namespace cartographer_ros
2,260
738
/*********************************************************************************************************************** * * * ANTIKERNEL v0.1 * * * * Copyright (c) 2012-2020 Andrew D. Zonenberg * * 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 author nor the names of any contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHORS "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 AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * ***********************************************************************************************************************/ #include "scopeprotocols.h" #include "FIRFilter.h" #include <immintrin.h> using namespace std; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Construction / destruction FIRFilter::FIRFilter(const string& color) : Filter( OscilloscopeChannel::CHANNEL_TYPE_ANALOG, color, CAT_MATH, "kernels/FIRFilter.cl", "FIRFilter") , m_filterTypeName("Filter Type") , m_filterLengthName("Length") , m_stopbandAttenName("Stopband Attenuation") , m_freqLowName("Frequency Low") , m_freqHighName("Frequency High") { CreateInput("in"); m_range = 1; m_offset = 0; m_min = FLT_MAX; m_max = -FLT_MAX; m_parameters[m_filterTypeName] = FilterParameter(FilterParameter::TYPE_ENUM, Unit(Unit::UNIT_COUNTS)); m_parameters[m_filterTypeName].AddEnumValue("Low pass", FILTER_TYPE_LOWPASS); m_parameters[m_filterTypeName].AddEnumValue("High pass", FILTER_TYPE_HIGHPASS); m_parameters[m_filterTypeName].AddEnumValue("Band pass", FILTER_TYPE_BANDPASS); m_parameters[m_filterTypeName].AddEnumValue("Notch", FILTER_TYPE_NOTCH); m_parameters[m_filterTypeName].SetIntVal(FILTER_TYPE_LOWPASS); m_parameters[m_filterLengthName] = FilterParameter(FilterParameter::TYPE_INT, Unit(Unit::UNIT_SAMPLEDEPTH)); m_parameters[m_filterLengthName].SetIntVal(0); m_parameters[m_stopbandAttenName] = FilterParameter(FilterParameter::TYPE_FLOAT, Unit(Unit::UNIT_DB)); m_parameters[m_stopbandAttenName].SetFloatVal(60); m_parameters[m_freqLowName] = FilterParameter(FilterParameter::TYPE_FLOAT, Unit(Unit::UNIT_HZ)); m_parameters[m_freqLowName].SetFloatVal(0); m_parameters[m_freqHighName] = FilterParameter(FilterParameter::TYPE_FLOAT, Unit(Unit::UNIT_HZ)); m_parameters[m_freqHighName].SetFloatVal(100e6); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Factory methods bool FIRFilter::ValidateChannel(size_t i, StreamDescriptor stream) { if(stream.m_channel == NULL) return false; if( (i == 0) && (stream.m_channel->GetType() == OscilloscopeChannel::CHANNEL_TYPE_ANALOG) ) return true; return false; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Accessors void FIRFilter::ClearSweeps() { m_range = 1; m_offset = 0; m_min = FLT_MAX; m_max = -FLT_MAX; } void FIRFilter::SetDefaultName() { char hwname[256]; auto type = static_cast<FilterType>(m_parameters[m_filterTypeName].GetIntVal()); switch(type) { case FILTER_TYPE_LOWPASS: snprintf(hwname, sizeof(hwname), "LPF(%s, %s)", GetInputDisplayName(0).c_str(), m_parameters[m_freqHighName].ToString().c_str()); break; case FILTER_TYPE_HIGHPASS: snprintf(hwname, sizeof(hwname), "HPF(%s, %s)", GetInputDisplayName(0).c_str(), m_parameters[m_freqLowName].ToString().c_str()); break; case FILTER_TYPE_BANDPASS: snprintf(hwname, sizeof(hwname), "BPF(%s, %s, %s)", GetInputDisplayName(0).c_str(), m_parameters[m_freqLowName].ToString().c_str(), m_parameters[m_freqHighName].ToString().c_str()); break; case FILTER_TYPE_NOTCH: snprintf(hwname, sizeof(hwname), "Notch(%s, %s, %s)", GetInputDisplayName(0).c_str(), m_parameters[m_freqLowName].ToString().c_str(), m_parameters[m_freqHighName].ToString().c_str()); break; } m_hwname = hwname; m_displayname = m_hwname; } string FIRFilter::GetProtocolName() { return "FIR Filter"; } bool FIRFilter::IsOverlay() { //we create a new analog channel return false; } bool FIRFilter::NeedsConfig() { return true; } double FIRFilter::GetVoltageRange() { return m_range; } double FIRFilter::GetOffset() { return m_offset; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Actual decoder logic void FIRFilter::Refresh() { //Sanity check if(!VerifyAllInputsOKAndAnalog()) { SetData(NULL, 0); return; } //Get input data auto din = GetAnalogInputWaveform(0); //Assume the input is dense packed, get the sample frequency int64_t fs_per_sample = din->m_timescale; float sample_hz = FS_PER_SECOND / fs_per_sample; //Calculate limits for our filter float nyquist = sample_hz / 2; float flo = m_parameters[m_freqLowName].GetFloatVal(); float fhi = m_parameters[m_freqHighName].GetFloatVal(); auto type = static_cast<FilterType>(m_parameters[m_filterTypeName].GetIntVal()); if(type == FILTER_TYPE_LOWPASS) flo = 0; else if(type == FILTER_TYPE_HIGHPASS) fhi = nyquist; else { //Swap high/low if they get swapped if(fhi < flo) { float ftmp = flo; flo = fhi; fhi = ftmp; } } flo = max(flo, 0.0f); fhi = min(fhi, nyquist); //Calculate filter order size_t filterlen = m_parameters[m_filterLengthName].GetIntVal(); float atten = m_parameters[m_stopbandAttenName].GetFloatVal(); if(filterlen == 0) filterlen = (atten / 22) * (sample_hz / (fhi - flo) ); filterlen |= 1; //force length to be odd //Create the filter coefficients (TODO: cache this) vector<float> coeffs; coeffs.resize(filterlen); CalculateFilterCoefficients( coeffs, flo / nyquist, fhi / nyquist, atten, type ); //Set up output m_xAxisUnit = m_inputs[0].m_channel->GetXAxisUnits(); m_yAxisUnit = m_inputs[0].m_channel->GetYAxisUnits(); size_t radius = (filterlen - 1) / 2; auto cap = SetupOutputWaveform(din, 0, 0, filterlen); //Run the actual filter float vmin; float vmax; DoFilterKernel(coeffs, din, cap, vmin, vmax); //Shift output to compensate for filter group delay cap->m_triggerPhase = (radius * fs_per_sample) + din->m_triggerPhase; //Calculate bounds m_max = max(m_max, vmax); m_min = min(m_min, vmin); m_range = (m_max - m_min) * 1.05; m_offset = -( (m_max - m_min)/2 + m_min ); } void FIRFilter::DoFilterKernel( vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { #ifdef HAVE_OPENCL if(g_clContext && m_kernel) DoFilterKernelOpenCL(coefficients, din, cap, vmin, vmax); else #endif if(g_hasAvx512F) DoFilterKernelAVX512F(coefficients, din, cap, vmin, vmax); else if(g_hasAvx2) DoFilterKernelAVX2(coefficients, din, cap, vmin, vmax); else DoFilterKernelGeneric(coefficients, din, cap, vmin, vmax); } #ifdef HAVE_OPENCL void FIRFilter::DoFilterKernelOpenCL( std::vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { //Setup size_t len = din->m_samples.size(); size_t filterlen = coefficients.size(); size_t end = len - filterlen; //Round size up to next multiple of block size //(must equal BLOCK_SIZE in kernel) const size_t blocksize = 1024; size_t globalsize = (end + blocksize); globalsize -= (globalsize % blocksize); //Allocate min/max buffer (first stage reduction on GPU, rest on CPU) size_t nblocks = globalsize / blocksize; vector<float> minmax; minmax.resize(2 * nblocks); try { //Allocate memory and copy to the GPU cl::Buffer inbuf(*g_clContext, din->m_samples.begin(), din->m_samples.end(), true, true, NULL); cl::Buffer coeffbuf(*g_clContext, coefficients.begin(), coefficients.end(), true, true, NULL); cl::Buffer outbuf(*g_clContext, cap->m_samples.begin(), cap->m_samples.end(), false, true, NULL); cl::Buffer minmaxbuf(*g_clContext, minmax.begin(), minmax.end(), false, true, NULL); //Run the filter cl::CommandQueue queue(*g_clContext, g_contextDevices[0], 0); m_kernel->setArg(0, inbuf); m_kernel->setArg(1, coeffbuf); m_kernel->setArg(2, outbuf); m_kernel->setArg(3, filterlen); m_kernel->setArg(4, end); m_kernel->setArg(5, minmaxbuf); queue.enqueueNDRangeKernel( *m_kernel, cl::NullRange, cl::NDRange(globalsize, 1), cl::NDRange(blocksize, 1), NULL); //Map/unmap the buffer to synchronize output with the CPU void* ptr = queue.enqueueMapBuffer(outbuf, true, CL_MAP_READ, 0, end * sizeof(float)); void* ptr2 = queue.enqueueMapBuffer(minmaxbuf, true, CL_MAP_READ, 0, 2 * nblocks * sizeof(float)); queue.enqueueUnmapMemObject(outbuf, ptr); queue.enqueueUnmapMemObject(minmaxbuf, ptr2); } catch(const cl::Error& e) { LogFatal("OpenCL error: %s (%d)\n", e.what(), e.err() ); } //Final reduction stage CPU-side vmin = FLT_MAX; vmax = -FLT_MAX; for(size_t i=0; i<nblocks; i++) { vmin = min(vmin, minmax[i*2]); vmax = max(vmax, minmax[i*2 + 1]); } } #endif /** @brief Performs a FIR filter (does not assume symmetric) */ void FIRFilter::DoFilterKernelGeneric( vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { //Setup vmin = FLT_MAX; vmax = -FLT_MAX; size_t len = din->m_samples.size(); size_t filterlen = coefficients.size(); size_t end = len - filterlen; //Do the filter for(size_t i=0; i<end; i++) { float v = 0; for(size_t j=0; j<filterlen; j++) v += din->m_samples[i + j] * coefficients[j]; vmin = min(vmin, v); vmax = max(vmax, v); cap->m_samples[i] = v; } } /** @brief Optimized FIR implementation Uses AVX2, but not AVX512 or FMA. */ __attribute__((target("avx2"))) void FIRFilter::DoFilterKernelAVX2( vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { __m256 vmin_x8 = { FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX }; __m256 vmax_x8 = { -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX }; //Save some pointers and sizes size_t len = din->m_samples.size(); size_t filterlen = coefficients.size(); size_t end = len - filterlen; size_t end_rounded = end - (end % 64); float* pin = (float*)&din->m_samples[0]; float* pout = (float*)&cap->m_samples[0]; //Vectorized and unrolled outer loop size_t i=0; for(; i<end_rounded; i += 64) { float* base = pin + i; //First tap __m256 coeff = _mm256_set1_ps(coefficients[0]); __m256 vin_a = _mm256_loadu_ps(base + 0); __m256 vin_b = _mm256_loadu_ps(base + 8); __m256 vin_c = _mm256_loadu_ps(base + 16); __m256 vin_d = _mm256_loadu_ps(base + 24); __m256 vin_e = _mm256_loadu_ps(base + 32); __m256 vin_f = _mm256_loadu_ps(base + 40); __m256 vin_g = _mm256_loadu_ps(base + 48); __m256 vin_h = _mm256_loadu_ps(base + 56); __m256 v_a = _mm256_mul_ps(coeff, vin_a); __m256 v_b = _mm256_mul_ps(coeff, vin_b); __m256 v_c = _mm256_mul_ps(coeff, vin_c); __m256 v_d = _mm256_mul_ps(coeff, vin_d); __m256 v_e = _mm256_mul_ps(coeff, vin_e); __m256 v_f = _mm256_mul_ps(coeff, vin_f); __m256 v_g = _mm256_mul_ps(coeff, vin_g); __m256 v_h = _mm256_mul_ps(coeff, vin_h); //Subsequent taps for(size_t j=1; j<filterlen; j++) { coeff = _mm256_set1_ps(coefficients[j]); vin_a = _mm256_loadu_ps(base + j + 0); vin_b = _mm256_loadu_ps(base + j + 8); vin_c = _mm256_loadu_ps(base + j + 16); vin_d = _mm256_loadu_ps(base + j + 24); vin_e = _mm256_loadu_ps(base + j + 32); vin_f = _mm256_loadu_ps(base + j + 40); vin_g = _mm256_loadu_ps(base + j + 48); vin_h = _mm256_loadu_ps(base + j + 56); __m256 prod_a = _mm256_mul_ps(coeff, vin_a); __m256 prod_b = _mm256_mul_ps(coeff, vin_b); __m256 prod_c = _mm256_mul_ps(coeff, vin_c); __m256 prod_d = _mm256_mul_ps(coeff, vin_d); __m256 prod_e = _mm256_mul_ps(coeff, vin_e); __m256 prod_f = _mm256_mul_ps(coeff, vin_f); __m256 prod_g = _mm256_mul_ps(coeff, vin_g); __m256 prod_h = _mm256_mul_ps(coeff, vin_h); v_a = _mm256_add_ps(prod_a, v_a); v_b = _mm256_add_ps(prod_b, v_b); v_c = _mm256_add_ps(prod_c, v_c); v_d = _mm256_add_ps(prod_d, v_d); v_e = _mm256_add_ps(prod_e, v_e); v_f = _mm256_add_ps(prod_f, v_f); v_g = _mm256_add_ps(prod_g, v_g); v_h = _mm256_add_ps(prod_h, v_h); } //Store the output _mm256_store_ps(pout + i + 0, v_a); _mm256_store_ps(pout + i + 8, v_b); _mm256_store_ps(pout + i + 16, v_c); _mm256_store_ps(pout + i + 24, v_d); _mm256_store_ps(pout + i + 32, v_e); _mm256_store_ps(pout + i + 40, v_f); _mm256_store_ps(pout + i + 48, v_g); _mm256_store_ps(pout + i + 56, v_h); //Calculate min/max: First level __m256 min_ab = _mm256_min_ps(v_a, v_b); __m256 min_cd = _mm256_min_ps(v_c, v_d); __m256 min_ef = _mm256_min_ps(v_e, v_f); __m256 min_gh = _mm256_min_ps(v_g, v_h); __m256 max_ab = _mm256_max_ps(v_a, v_b); __m256 max_cd = _mm256_max_ps(v_c, v_d); __m256 max_ef = _mm256_max_ps(v_e, v_f); __m256 max_gh = _mm256_max_ps(v_g, v_h); //Min/max: second level __m256 min_abcd = _mm256_min_ps(min_ab, min_cd); __m256 min_efgh = _mm256_min_ps(min_ef, min_gh); __m256 max_abcd = _mm256_max_ps(max_ab, max_cd); __m256 max_efgh = _mm256_max_ps(max_ef, max_gh); //Min/max: third level __m256 min_l3 = _mm256_min_ps(min_abcd, min_efgh); __m256 max_l3 = _mm256_max_ps(max_abcd, max_efgh); //Min/max: final reduction vmin_x8 = _mm256_min_ps(vmin_x8, min_l3); vmax_x8 = _mm256_max_ps(vmax_x8, max_l3); } //Horizontal reduction of vector min/max float tmp_min[8] __attribute__((aligned(32))); float tmp_max[8] __attribute__((aligned(32))); _mm256_store_ps(tmp_min, vmin_x8); _mm256_store_ps(tmp_max, vmax_x8); for(int j=0; j<8; j++) { vmin = min(vmin, tmp_min[j]); vmax = max(vmax, tmp_max[j]); } //Catch any stragglers for(; i<end_rounded; i++) { float v = 0; for(size_t j=0; j<filterlen; j++) v += din->m_samples[i + j] * coefficients[j]; vmin = min(vmin, v); vmax = max(vmax, v); cap->m_samples[i] = v; } } /** @brief Optimized AVX512F implementation */ __attribute__((target("avx512f"))) void FIRFilter::DoFilterKernelAVX512F( vector<float>& coefficients, AnalogWaveform* din, AnalogWaveform* cap, float& vmin, float& vmax) { __m512 vmin_x16 = _mm512_set1_ps(FLT_MAX); __m512 vmax_x16 = _mm512_set1_ps(-FLT_MAX); //Save some pointers and sizes size_t len = din->m_samples.size(); size_t filterlen = coefficients.size(); size_t end = len - filterlen; size_t end_rounded = end - (end % 64); float* pin = (float*)&din->m_samples[0]; float* pout = (float*)&cap->m_samples[0]; //Vectorized and unrolled outer loop size_t i=0; for(; i<end_rounded; i += 64) { float* base = pin + i; //First tap __m512 coeff = _mm512_set1_ps(coefficients[0]); __m512 vin_a = _mm512_loadu_ps(base + 0); __m512 vin_b = _mm512_loadu_ps(base + 16); __m512 vin_c = _mm512_loadu_ps(base + 32); __m512 vin_d = _mm512_loadu_ps(base + 48); __m512 v_a = _mm512_mul_ps(coeff, vin_a); __m512 v_b = _mm512_mul_ps(coeff, vin_b); __m512 v_c = _mm512_mul_ps(coeff, vin_c); __m512 v_d = _mm512_mul_ps(coeff, vin_d); //Subsequent taps for(size_t j=1; j<filterlen; j++) { coeff = _mm512_set1_ps(coefficients[j]); vin_a = _mm512_loadu_ps(base + j + 0); vin_b = _mm512_loadu_ps(base + j + 16); vin_c = _mm512_loadu_ps(base + j + 32); vin_d = _mm512_loadu_ps(base + j + 48); v_a = _mm512_fmadd_ps(coeff, vin_a, v_a); v_b = _mm512_fmadd_ps(coeff, vin_b, v_b); v_c = _mm512_fmadd_ps(coeff, vin_c, v_c); v_d = _mm512_fmadd_ps(coeff, vin_d, v_d); } //Store the output _mm512_store_ps(pout + i + 0, v_a); _mm512_store_ps(pout + i + 16, v_b); _mm512_store_ps(pout + i + 32, v_c); _mm512_store_ps(pout + i + 48, v_d); //Calculate min/max: First level __m512 min_ab = _mm512_min_ps(v_a, v_b); __m512 min_cd = _mm512_min_ps(v_c, v_d); __m512 max_ab = _mm512_max_ps(v_a, v_b); __m512 max_cd = _mm512_max_ps(v_c, v_d); //Min/max: second level __m512 min_abcd = _mm512_min_ps(min_ab, min_cd); __m512 max_abcd = _mm512_max_ps(max_ab, max_cd); //Min/max: final reduction vmin_x16 = _mm512_min_ps(vmin_x16, min_abcd); vmax_x16 = _mm512_max_ps(vmax_x16, max_abcd); } //Horizontal reduction of vector min/max float tmp_min[16] __attribute__((aligned(64))); float tmp_max[16] __attribute__((aligned(64))); _mm512_store_ps(tmp_min, vmin_x16); _mm512_store_ps(tmp_max, vmax_x16); for(int j=0; j<16; j++) { vmin = min(vmin, tmp_min[j]); vmax = max(vmax, tmp_max[j]); } //Catch any stragglers for(; i<end_rounded; i++) { float v = 0; for(size_t j=0; j<filterlen; j++) v += din->m_samples[i + j] * coefficients[j]; vmin = min(vmin, v); vmax = max(vmax, v); cap->m_samples[i] = v; } } /** @brief Calculates FIR coefficients Based on public domain code at https://www.arc.id.au/FilterDesign.html Cutoff frequencies are specified in fractions of the Nyquist limit (Fsample/2). @param coefficients Output buffer @param fa Left side passband (0 for LPF) @param fb Right side passband (1 for HPF) @param stopbandAtten Stop-band attenuation, in dB @param type Type of filter */ void FIRFilter::CalculateFilterCoefficients( vector<float>& coefficients, float fa, float fb, float stopbandAtten, FilterType type) { //Calculate the impulse response of the filter size_t len = coefficients.size(); size_t np = (len - 1) / 2; vector<float> impulse; impulse.push_back(fb-fa); for(size_t j=1; j<=np; j++) impulse.push_back( (sin(j*M_PI*fb) - sin(j*M_PI*fa)) /(j*M_PI) ); //Calculate window scaling factor for stopband attenuation float alpha = 0; if(stopbandAtten < 21) alpha = 0; else if(stopbandAtten > 50) alpha = 0.1102 * (stopbandAtten - 8.7); else alpha = 0.5842 * pow(stopbandAtten-21, 0.4) + 0.07886*(stopbandAtten-21); //Final windowing (Kaiser-Bessel) float ia = Bessel(alpha); if(type == FILTER_TYPE_NOTCH) { for(size_t j=0; j<=np; j++) coefficients[np+j] = -impulse[j] * Bessel(alpha * sqrt(1 - ((j*j*1.0)/(np*np)))) / ia; coefficients[np] += 1; } else { for(size_t j=0; j<=np; j++) coefficients[np+j] = impulse[j] * Bessel(alpha * sqrt(1 - ((j*j*1.0)/(np*np)))) / ia; } for(size_t j=0; j<=np; j++) coefficients[j] = coefficients[len-1-j]; } /** @brief 0th order Bessel function */ float FIRFilter::Bessel(float x) { float d = 0; float ds = 1; float s = 1; while(ds > s*1e-6) { d += 2; ds *= (x*x)/(d*d); s += ds; } return s; }
21,479
9,458
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #include <algorithm> #include <cstring> #include <numeric> #include <benchmark/benchmark.h> #include <seqan3/alphabet/all.hpp> #include <seqan3/test/seqan2.hpp> #if SEQAN3_HAS_SEQAN2 #include <seqan/align.h> #include <seqan/basic.h> #include <seqan/modifier.h> #endif template <seqan3::alphabet alphabet_t> void assign_char(benchmark::State & state) { using char_t = seqan3::alphabet_char_t<alphabet_t>; std::array<char_t, 256> chars{}; std::iota(chars.begin(), chars.end(), 0); alphabet_t a{}; for (auto _ : state) for (char_t c : chars) benchmark::DoNotOptimize(seqan3::assign_char_to(c, a)); } /* regular alphabets, sorted by size */ BENCHMARK_TEMPLATE(assign_char, seqan3::gap); BENCHMARK_TEMPLATE(assign_char, seqan3::dna4); BENCHMARK_TEMPLATE(assign_char, seqan3::rna4); BENCHMARK_TEMPLATE(assign_char, seqan3::dna5); BENCHMARK_TEMPLATE(assign_char, seqan3::rna5); BENCHMARK_TEMPLATE(assign_char, seqan3::dna15); BENCHMARK_TEMPLATE(assign_char, seqan3::rna15); BENCHMARK_TEMPLATE(assign_char, seqan3::aa20); BENCHMARK_TEMPLATE(assign_char, seqan3::aa27); BENCHMARK_TEMPLATE(assign_char, seqan3::phred42); BENCHMARK_TEMPLATE(assign_char, seqan3::phred63); /* adaptations */ BENCHMARK_TEMPLATE(assign_char, char); BENCHMARK_TEMPLATE(assign_char, char32_t); /* alphabet variant */ BENCHMARK_TEMPLATE(assign_char, seqan3::gapped<seqan3::dna4>); BENCHMARK_TEMPLATE(assign_char, seqan3::alphabet_variant<seqan3::gap, seqan3::dna4, seqan3::dna5, seqan3::dna15, seqan3::rna15, seqan3::rna4, seqan3::rna5>); BENCHMARK_TEMPLATE(assign_char, seqan3::alphabet_variant<seqan3::dna4, char>); /* alphabet tuple */ BENCHMARK_TEMPLATE(assign_char, seqan3::masked<seqan3::dna4>); BENCHMARK_TEMPLATE(assign_char, seqan3::qualified<seqan3::dna4, seqan3::phred42>); BENCHMARK_TEMPLATE(assign_char, seqan3::qualified<seqan3::dna5, seqan3::phred63>); #if SEQAN3_HAS_SEQAN2 template <typename alphabet_t> void assign_char_seqan2(benchmark::State & state) { std::array<char, 256> chars{}; std::iota(chars.begin(), chars.end(), 0); alphabet_t a{}; for (auto _ : state) for (char c : chars) benchmark::DoNotOptimize(a = c); } BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Dna); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Rna); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Dna5); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Rna5); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Iupac); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::AminoAcid); BENCHMARK_TEMPLATE(assign_char_seqan2, seqan::Dna5Q); BENCHMARK_TEMPLATE(assign_char_seqan2, typename seqan::GappedValueType<seqan::Dna>::Type); #endif BENCHMARK_MAIN();
3,295
1,405
/*========================================================================= Program: Visualization Toolkit Module: vtkPointHandleRepresentation3D.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 "vtkPointHandleRepresentation3D.h" #include "vtkActor.h" #include "vtkAssemblyPath.h" #include "vtkCamera.h" #include "vtkCellPicker.h" #include "vtkCoordinate.h" #include "vtkCursor3D.h" #include "vtkEventData.h" #include "vtkFocalPlanePointPlacer.h" #include "vtkInteractorObserver.h" #include "vtkLine.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPickingManager.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include <assert.h> vtkStandardNewMacro(vtkPointHandleRepresentation3D); vtkCxxSetObjectMacro(vtkPointHandleRepresentation3D, Property, vtkProperty); vtkCxxSetObjectMacro(vtkPointHandleRepresentation3D, SelectedProperty, vtkProperty); //---------------------------------------------------------------------- vtkPointHandleRepresentation3D::vtkPointHandleRepresentation3D() { // Initialize state this->InteractionState = vtkHandleRepresentation::Outside; // Represent the line this->Cursor3D = vtkCursor3D::New(); this->Cursor3D->AllOff(); this->Cursor3D->AxesOn(); this->Cursor3D->TranslationModeOn(); this->Mapper = vtkPolyDataMapper::New(); this->Mapper->SetInputConnection(this->Cursor3D->GetOutputPort()); // Set up the initial properties this->CreateDefaultProperties(); this->Actor = vtkActor::New(); this->Actor->SetMapper(this->Mapper); this->Actor->SetProperty(this->Property); // Manage the picking stuff this->CursorPicker = vtkCellPicker::New(); this->CursorPicker->PickFromListOn(); this->CursorPicker->AddPickList(this->Actor); this->CursorPicker->SetTolerance(0.01); // need some fluff // Override superclass' this->PlaceFactor = 1.0; // The size of the hot spot this->HotSpotSize = 0.05; this->WaitingForMotion = 0; this->ConstraintAxis = -1; // Current handle size this->HandleSize = 15.0; // in pixels this->CurrentHandleSize = this->HandleSize; // Translation control this->TranslationMode = 1; vtkFocalPlanePointPlacer* pointPlacer = vtkFocalPlanePointPlacer::New(); this->SetPointPlacer(pointPlacer); pointPlacer->Delete(); // Continuous moves this->SmoothMotion = 1; } //---------------------------------------------------------------------- vtkPointHandleRepresentation3D::~vtkPointHandleRepresentation3D() { this->Cursor3D->Delete(); this->CursorPicker->Delete(); this->Mapper->Delete(); this->Actor->Delete(); this->Property->Delete(); this->SelectedProperty->Delete(); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::RegisterPickers() { vtkPickingManager* pm = this->GetPickingManager(); if (!pm) { return; } pm->AddPicker(this->CursorPicker, this); } //------------------------------------------------------------------------- void vtkPointHandleRepresentation3D::PlaceWidget(double bds[6]) { int i; double bounds[6], center[3]; this->AdjustBounds(bds, bounds, center); this->Cursor3D->SetModelBounds(bounds); this->SetWorldPosition(center); for (i = 0; i < 6; i++) { this->InitialBounds[i] = bounds[i]; } this->InitialLength = sqrt((bounds[1] - bounds[0]) * (bounds[1] - bounds[0]) + (bounds[3] - bounds[2]) * (bounds[3] - bounds[2]) + (bounds[5] - bounds[4]) * (bounds[5] - bounds[4])); } //------------------------------------------------------------------------- double* vtkPointHandleRepresentation3D::GetBounds() { return this->Cursor3D->GetModelBounds(); } //------------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetWorldPosition(double p[3]) { if (this->Renderer && this->PointPlacer) { if (this->PointPlacer->ValidateWorldPosition(p)) { this->Cursor3D->SetFocalPoint(p); // this may clamp the point this->WorldPosition->SetValue(this->Cursor3D->GetFocalPoint()); this->WorldPositionTime.Modified(); } } else { this->Cursor3D->SetFocalPoint(p); // this may clamp the point this->WorldPosition->SetValue(this->Cursor3D->GetFocalPoint()); this->WorldPositionTime.Modified(); } } //------------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetDisplayPosition(double p[3]) { if (this->Renderer && this->PointPlacer) { if (this->PointPlacer->ValidateDisplayPosition(this->Renderer, p)) { double worldPos[3], worldOrient[9]; if (this->PointPlacer->ComputeWorldPosition(this->Renderer, p, worldPos, worldOrient)) { this->DisplayPosition->SetValue(p); this->WorldPosition->SetValue(worldPos); this->DisplayPositionTime.Modified(); this->SetWorldPosition(this->WorldPosition->GetValue()); } } } else { this->DisplayPosition->SetValue(p); this->DisplayPositionTime.Modified(); } } //------------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetHandleSize(double size) { this->Superclass::SetHandleSize(size); this->CurrentHandleSize = this->HandleSize; } //------------------------------------------------------------------------- int vtkPointHandleRepresentation3D ::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { this->VisibilityOn(); // actor must be on to be picked // First make sure that the cursor is within the bounding sphere of the // representation in display space. double d[3], bounds[6]; this->Cursor3D->GetModelBounds(bounds); this->GetDisplayPosition(d); if (!this->NearbyEvent(X, Y, bounds)) { this->InteractionState = vtkHandleRepresentation::Outside; return this->InteractionState; } // Now see if anything is picked vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->CursorPicker); if (path != nullptr) { this->InteractionState = vtkHandleRepresentation::Nearby; } else { this->InteractionState = vtkHandleRepresentation::Outside; if (this->ActiveRepresentation) { this->VisibilityOff(); } } return this->InteractionState; } //------------------------------------------------------------------------- int vtkPointHandleRepresentation3D::ComputeComplexInteractionState( vtkRenderWindowInteractor*, vtkAbstractWidget*, unsigned long, void* calldata, int) { this->VisibilityOn(); // actor must be on to be picked vtkEventData* edata = static_cast<vtkEventData*>(calldata); vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (edd) { double pos[3]; edd->GetWorldPosition(pos); vtkAssemblyPath* path = this->GetAssemblyPath3DPoint(pos, this->CursorPicker); double focus[3]; this->Cursor3D->GetFocalPoint(focus); double d[3]; this->GetDisplayPosition(d); if (path != nullptr) { this->InteractionState = vtkHandleRepresentation::Nearby; } else { this->InteractionState = vtkHandleRepresentation::Outside; if (this->ActiveRepresentation) { this->VisibilityOff(); } } } return this->InteractionState; } //------------------------------------------------------------------------- int vtkPointHandleRepresentation3D::DetermineConstraintAxis( int constraint, double* x, double* startPickPoint) { // Look for trivial cases if (!this->Constrained) { return -1; } else if (constraint >= 0 && constraint < 3) { return constraint; } // Okay, figure out constraint. First see if the choice is // outside the hot spot if (!x) { double p[3], d2, tol; this->CursorPicker->GetPickPosition(p); d2 = vtkMath::Distance2BetweenPoints(p, this->LastPickPosition); tol = this->HotSpotSize * this->InitialLength; if (d2 > (tol * tol)) { this->WaitingForMotion = 0; return this->CursorPicker->GetCellId(); } else { this->WaitingForMotion = 1; this->WaitCount = 0; return -1; } } else if (x) { this->WaitingForMotion = 0; double v[3]; v[0] = fabs(x[0] - startPickPoint[0]); v[1] = fabs(x[1] - startPickPoint[1]); v[2] = fabs(x[2] - startPickPoint[2]); return (v[0] > v[1] ? (v[0] > v[2] ? 0 : 2) : (v[1] > v[2] ? 1 : 2)); } else { return -1; } } //---------------------------------------------------------------------- // Record the current event position, and the translation state void vtkPointHandleRepresentation3D::StartWidgetInteraction(double startEventPos[2]) { this->StartEventPosition[0] = startEventPos[0]; this->StartEventPosition[1] = startEventPos[1]; this->StartEventPosition[2] = 0.0; this->LastEventPosition[0] = startEventPos[0]; this->LastEventPosition[1] = startEventPos[1]; // Make sure events are close to widget and something is picked double bounds[6]; this->Cursor3D->GetModelBounds(bounds); bool nearby = this->NearbyEvent(startEventPos[0], startEventPos[1], bounds); vtkAssemblyPath* path = this->GetAssemblyPath(startEventPos[0], startEventPos[1], 0., this->CursorPicker); if (nearby && path != nullptr) { this->InteractionState = vtkHandleRepresentation::Nearby; this->ConstraintAxis = -1; this->CursorPicker->GetPickPosition(this->LastPickPosition); } else { this->InteractionState = vtkHandleRepresentation::Outside; this->ConstraintAxis = -1; } this->Cursor3D->SetTranslationMode(this->TranslationMode); this->WaitCount = 0; } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::StartComplexInteraction( vtkRenderWindowInteractor*, vtkAbstractWidget*, unsigned long, void* calldata) { vtkEventData* edata = static_cast<vtkEventData*>(calldata); vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (edd) { edd->GetWorldPosition(this->StartEventPosition); this->LastEventPosition[0] = this->StartEventPosition[0]; this->LastEventPosition[1] = this->StartEventPosition[1]; this->LastEventPosition[2] = this->StartEventPosition[2]; double bounds[6]; this->Cursor3D->GetModelBounds(bounds); bool nearby = this->NearbyEvent(this->StartEventPosition[0], this->StartEventPosition[1], bounds); vtkAssemblyPath* path = this->GetAssemblyPath3DPoint(this->StartEventPosition, this->CursorPicker); if (nearby && path != nullptr) { this->InteractionState = vtkHandleRepresentation::Nearby; this->ConstraintAxis = -1; this->CursorPicker->GetPickPosition(this->LastPickPosition); } else { this->InteractionState = vtkHandleRepresentation::Outside; this->ConstraintAxis = -1; } this->Cursor3D->SetTranslationMode(this->TranslationMode); this->WaitCount = 0; } } //---------------------------------------------------------------------- // Based on the displacement vector (computed in display coordinates) and // the cursor state (which corresponds to which part of the widget has been // selected), the widget points are modified. // First construct a local coordinate system based on the display coordinates // of the widget. void vtkPointHandleRepresentation3D::WidgetInteraction(double eventPos[2]) { // Do different things depending on state // Calculations everybody does double focalPoint[4], pickPoint[4], prevPickPoint[4], startPickPoint[4], z; // Compute the two points defining the motion vector vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer, this->LastPickPosition[0], this->LastPickPosition[1], this->LastPickPosition[2], focalPoint); z = focalPoint[2]; vtkInteractorObserver::ComputeDisplayToWorld( this->Renderer, this->LastEventPosition[0], this->LastEventPosition[1], z, prevPickPoint); vtkInteractorObserver::ComputeDisplayToWorld( this->Renderer, eventPos[0], eventPos[1], z, pickPoint); // Process the motion if (this->InteractionState == vtkHandleRepresentation::Selecting || this->InteractionState == vtkHandleRepresentation::Translating) { this->WaitCount++; if (this->WaitCount > 3 || !this->Constrained) { vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer, this->StartEventPosition[0], this->StartEventPosition[1], z, startPickPoint); this->ConstraintAxis = this->DetermineConstraintAxis(this->ConstraintAxis, pickPoint, startPickPoint); if (this->InteractionState == vtkHandleRepresentation::Selecting && !this->TranslationMode) { vtkDebugMacro(<< "Processing widget interaction for Select mode"); // If we are doing axis constrained motion, ignore the placer. // Can't have both the placer and an axis constraint dictating // handle placement. if (this->ConstraintAxis >= 0 || this->Constrained || !this->PointPlacer) { this->MoveFocus(prevPickPoint, pickPoint); } else { double newCenterPointRequested[3]; // displayPosition double newCenterPoint[3], worldOrient[9]; // Make a request for the new position. this->MoveFocusRequest(prevPickPoint, pickPoint, eventPos, newCenterPointRequested); vtkFocalPlanePointPlacer* fPlacer = vtkFocalPlanePointPlacer::SafeDownCast(this->PointPlacer); if (fPlacer) { // Offset the placer plane to one that passes through the current // world position and is parallel to the focal plane. Offset = // the distance currentWorldPos is from the focal plane // double currentWorldPos[3], projDir[3], fp[3]; this->GetWorldPosition(currentWorldPos); this->Renderer->GetActiveCamera()->GetFocalPoint(fp); double vec[3] = { currentWorldPos[0] - fp[0], currentWorldPos[1] - fp[1], currentWorldPos[2] - fp[2] }; this->Renderer->GetActiveCamera()->GetDirectionOfProjection(projDir); fPlacer->SetOffset(vtkMath::Dot(vec, projDir)); } vtkDebugMacro(<< "Request for computing world position at " << "display position of " << newCenterPointRequested[0] << "," << newCenterPointRequested[1]); // See what the placer says. if (this->PointPlacer->ComputeWorldPosition( this->Renderer, newCenterPointRequested, newCenterPoint, worldOrient)) { // Once the placer has validated us, update the handle position this->SetWorldPosition(newCenterPoint); } } } else { vtkDebugMacro(<< "Processing widget interaction for translate"); // If we are doing axis constrained motion, ignore the placer. // Can't have both the placer and the axis constraint dictating // handle placement. if (this->ConstraintAxis >= 0 || this->Constrained || !this->PointPlacer) { this->Translate(prevPickPoint, pickPoint); } else { double newCenterPointRequested[3]; // displayPosition double newCenterPoint[3], worldOrient[9]; // Make a request for the new position. this->MoveFocusRequest(prevPickPoint, pickPoint, eventPos, newCenterPointRequested); vtkFocalPlanePointPlacer* fPlacer = vtkFocalPlanePointPlacer::SafeDownCast(this->PointPlacer); if (fPlacer) { // Offset the placer plane to one that passes through the current // world position and is parallel to the focal plane. Offset = // the distance currentWorldPos is from the focal plane // double currentWorldPos[3], projDir[3], fp[3]; this->GetWorldPosition(currentWorldPos); this->Renderer->GetActiveCamera()->GetFocalPoint(fp); double vec[3] = { currentWorldPos[0] - fp[0], currentWorldPos[1] - fp[1], currentWorldPos[2] - fp[2] }; this->Renderer->GetActiveCamera()->GetDirectionOfProjection(projDir); fPlacer->SetOffset(vtkMath::Dot(vec, projDir)); } vtkDebugMacro(<< "Request for computing world position at " << "display position of " << newCenterPointRequested[0] << "," << newCenterPointRequested[1]); // See what the placer says. if (this->PointPlacer->ComputeWorldPosition( this->Renderer, newCenterPointRequested, newCenterPoint, worldOrient)) { // Once the placer has validated us, update the handle // position and its bounds. double* p = this->GetWorldPosition(); // Get the motion vector double v[3] = { newCenterPoint[0] - p[0], newCenterPoint[1] - p[1], newCenterPoint[2] - p[2] }; double *bounds = this->Cursor3D->GetModelBounds(), newBounds[6]; for (int i = 0; i < 3; i++) { newBounds[2 * i] = bounds[2 * i] + v[i]; newBounds[2 * i + 1] = bounds[2 * i + 1] + v[i]; } this->Cursor3D->SetModelBounds(newBounds); this->SetWorldPosition(newCenterPoint); } } } } } else if (this->InteractionState == vtkHandleRepresentation::Scaling) { // Scaling does not change the position of the handle, we needn't // ask the placer.. this->Scale(prevPickPoint, pickPoint, eventPos); } // Book keeping this->LastEventPosition[0] = eventPos[0]; this->LastEventPosition[1] = eventPos[1]; this->Modified(); } void vtkPointHandleRepresentation3D::ComplexInteraction( vtkRenderWindowInteractor*, vtkAbstractWidget*, unsigned long, void* calldata) { vtkEventData* edata = static_cast<vtkEventData*>(calldata); vtkEventDataDevice3D* edd = edata->GetAsEventDataDevice3D(); if (edd) { double eventPos[3]; edd->GetWorldPosition(eventPos); // Process the motion if (this->InteractionState == vtkHandleRepresentation::Selecting || this->InteractionState == vtkHandleRepresentation::Translating) { this->WaitCount++; if (this->WaitCount > 3 || !this->Constrained) { this->ConstraintAxis = this->DetermineConstraintAxis(this->ConstraintAxis, eventPos, this->StartEventPosition); if (this->InteractionState == vtkHandleRepresentation::Selecting && !this->TranslationMode) { vtkDebugMacro(<< "Processing widget interaction for Select mode"); this->MoveFocus(this->LastEventPosition, eventPos); } else { vtkDebugMacro(<< "Processing widget interaction for translate"); this->Translate(this->LastEventPosition, eventPos); } } } // Book keeping this->LastEventPosition[0] = eventPos[0]; this->LastEventPosition[1] = eventPos[1]; this->LastEventPosition[2] = eventPos[2]; this->Modified(); } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D ::MoveFocusRequest( const double* p1, const double* p2, const double eventPos[2], double center[3]) { if (this->SmoothMotion) { double focus[4], v[3]; this->Cursor3D->GetFocalPoint(focus); this->GetTranslationVector(p1, p2, v); // Move the center of the handle along the motion vector focus[0] += v[0]; focus[1] += v[1]; focus[2] += v[2]; focus[3] = 1.0; // Get the display position that this center would fall on. this->Renderer->SetWorldPoint(focus); this->Renderer->WorldToDisplay(); this->Renderer->GetDisplayPoint(center); } else { center[0] = eventPos[0]; center[1] = eventPos[1]; center[2] = 1.0; } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::MoveFocus(const double* p1, const double* p2) { this->Translate(p1, p2); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetTranslationMode(vtkTypeBool mode) { if (this->TranslationMode != mode) { this->TranslationMode = mode; // Pass new setting to Cursor3D, otherwise PlaceWidget will not work // as it should when TranslationMode is off. this->Cursor3D->SetTranslationMode(mode); this->Modified(); } } //---------------------------------------------------------------------- // Translate everything void vtkPointHandleRepresentation3D::Translate(const double* p1, const double* p2) { double v[3] = { 0, 0, 0 }; vtkHandleRepresentation::Translate(p1, p2); this->GetTranslationVector(p1, p2, v); double* bounds = this->Cursor3D->GetModelBounds(); double* pos = this->Cursor3D->GetFocalPoint(); double newBounds[6], newFocus[3]; int i; if (this->ConstraintAxis >= 0) { // move along axis for (i = 0; i < 3; i++) { if (i != this->ConstraintAxis) { v[i] = 0.0; } } } for (i = 0; i < 3; i++) { newBounds[2 * i] = bounds[2 * i] + v[i]; newBounds[2 * i + 1] = bounds[2 * i + 1] + v[i]; newFocus[i] = pos[i] + v[i]; } this->Cursor3D->SetModelBounds(newBounds); this->Cursor3D->SetFocalPoint(newFocus); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SizeBounds() { // Only change the size of the bounding box if translation mode is on. if (this->TranslationMode) { double center[3], bounds[6]; this->Cursor3D->GetFocalPoint(center); double radius = this->SizeHandlesInPixels(1.0, center); radius *= this->CurrentHandleSize / this->HandleSize; for (int i = 0; i < 3; i++) { bounds[2 * i] = center[i] - radius; bounds[2 * i + 1] = center[i] + radius; } this->Cursor3D->SetModelBounds(bounds); } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::Scale( const double* p1, const double* p2, const double eventPos[2]) { // Get the motion vector double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; double* bounds = this->Cursor3D->GetModelBounds(); // Compute the scale factor double sf = vtkMath::Norm(v) / sqrt((bounds[1] - bounds[0]) * (bounds[1] - bounds[0]) + (bounds[3] - bounds[2]) * (bounds[3] - bounds[2]) + (bounds[5] - bounds[4]) * (bounds[5] - bounds[4])); if (eventPos[1] > this->LastEventPosition[1]) { sf = 1.0 + sf; } else { sf = 1.0 - sf; } this->CurrentHandleSize *= sf; this->CurrentHandleSize = (this->CurrentHandleSize < 0.001 ? 0.001 : this->CurrentHandleSize); this->SizeBounds(); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::Highlight(int highlight) { if (highlight) { this->Actor->SetProperty(this->SelectedProperty); } else { this->Actor->SetProperty(this->Property); } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::CreateDefaultProperties() { this->Property = vtkProperty::New(); this->Property->SetAmbient(1.0); this->Property->SetAmbientColor(1.0, 1.0, 1.0); this->Property->SetLineWidth(0.5); this->SelectedProperty = vtkProperty::New(); this->SelectedProperty->SetAmbient(1.0); this->SelectedProperty->SetAmbientColor(0.0, 1.0, 0.0); this->SelectedProperty->SetLineWidth(2.0); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::SetVisibility(vtkTypeBool visible) { this->Actor->SetVisibility(visible); // Forward to superclass this->Superclass::SetVisibility(visible); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::BuildRepresentation() { // The net effect is to resize the handle if (this->GetMTime() > this->BuildTime || (this->Renderer && this->Renderer->GetVTKWindow() && this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime)) { if (!this->Placed) { this->ValidPick = 1; this->Placed = 1; } this->SizeBounds(); this->Cursor3D->Update(); this->BuildTime.Modified(); } } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::ShallowCopy(vtkProp* prop) { vtkPointHandleRepresentation3D* rep = vtkPointHandleRepresentation3D::SafeDownCast(prop); if (rep) { this->SetOutline(rep->GetOutline()); this->SetXShadows(rep->GetXShadows()); this->SetYShadows(rep->GetYShadows()); this->SetZShadows(rep->GetZShadows()); this->SetTranslationMode(rep->GetTranslationMode()); this->SetProperty(rep->GetProperty()); this->Actor->SetProperty(rep->GetProperty()); this->SetSelectedProperty(rep->GetSelectedProperty()); this->SetHotSpotSize(rep->GetHotSpotSize()); } this->Superclass::ShallowCopy(prop); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::DeepCopy(vtkProp* prop) { vtkPointHandleRepresentation3D* rep = vtkPointHandleRepresentation3D::SafeDownCast(prop); if (rep) { this->SetOutline(rep->GetOutline()); this->SetXShadows(rep->GetXShadows()); this->SetYShadows(rep->GetYShadows()); this->SetZShadows(rep->GetZShadows()); this->SetTranslationMode(rep->GetTranslationMode()); this->SetProperty(rep->GetProperty()); this->Actor->SetProperty(rep->GetProperty()); this->SetSelectedProperty(rep->GetSelectedProperty()); this->SetHotSpotSize(rep->GetHotSpotSize()); } this->Superclass::DeepCopy(prop); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::GetActors(vtkPropCollection* pc) { this->Actor->GetActors(pc); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::ReleaseGraphicsResources(vtkWindow* win) { this->Actor->ReleaseGraphicsResources(win); } //---------------------------------------------------------------------- int vtkPointHandleRepresentation3D::RenderOpaqueGeometry(vtkViewport* viewport) { this->BuildRepresentation(); // Sanity check double worldPos[3]; this->GetWorldPosition(worldPos); if (worldPos[0] == VTK_DOUBLE_MAX) { return 0; } return this->Actor->RenderOpaqueGeometry(viewport); } //----------------------------------------------------------------------------- int vtkPointHandleRepresentation3D::RenderTranslucentPolygonalGeometry(vtkViewport* viewport) { this->BuildRepresentation(); // Sanity check double worldPos[3]; this->GetWorldPosition(worldPos); if (worldPos[0] == VTK_DOUBLE_MAX) { return 0; } return this->Actor->RenderTranslucentPolygonalGeometry(viewport); } //----------------------------------------------------------------------------- vtkTypeBool vtkPointHandleRepresentation3D::HasTranslucentPolygonalGeometry() { this->BuildRepresentation(); return this->Actor->HasTranslucentPolygonalGeometry(); } //---------------------------------------------------------------------- void vtkPointHandleRepresentation3D::PrintSelf(ostream& os, vtkIndent indent) { // Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os, indent); os << indent << "Hot Spot Size: " << this->HotSpotSize << "\n"; if (this->Property) { os << indent << "Property: " << this->Property << "\n"; } else { os << indent << "Property: (none)\n"; } if (this->SelectedProperty) { os << indent << "Selected Property: " << this->SelectedProperty << "\n"; } else { os << indent << "Selected Property: (none)\n"; } os << indent << "Outline: " << (this->GetOutline() ? "On\n" : "Off\n"); os << indent << "XShadows: " << (this->GetXShadows() ? "On\n" : "Off\n"); os << indent << "YShadows: " << (this->GetYShadows() ? "On\n" : "Off\n"); os << indent << "ZShadows: " << (this->GetZShadows() ? "On\n" : "Off\n"); os << indent << "Translation Mode: " << (this->TranslationMode ? "On\n" : "Off\n"); os << indent << "SmoothMotion: " << this->SmoothMotion << endl; }
28,923
9,007
/* $Author = Sargis Ananyan; $Corp = RedM Inc; $Web = https://redm.pro/; $Lincese = BSD 3; $Name = mLang; $Description = A programming language for web programming.; */ #pragma once bool empty_bool __attribute__ ((weak)); int empty_int __attribute__ ((weak)); double empty_float __attribute__ ((weak)); string empty_string __attribute__ ((weak)); char empty_array_var_storage[sizeof (array <var>)] __attribute__ ((weak)); array <var> *empty_array_var __attribute__ ((weak)) = reinterpret_cast <array <var> *> (empty_array_var_storage); var empty_var __attribute__ ((weak)); void var::copy_from (const var &other) { switch (other.type) { case NULL_TYPE: break; case BOOLEAN_TYPE: b = other.b; break; case INTEGER_TYPE: i = other.i; break; case FLOAT_TYPE: f = other.f; break; case STRING_TYPE: new (&s) string (*STRING(other.s)); break; case ARRAY_TYPE: new (&a) array <var> (*ARRAY(other.a)); break; case OBJECT_TYPE: new (&o) object (*OBJECT(other.o)); break; } type = other.type; } var::var (void): type (NULL_TYPE) { } var::var (const Unknown &u): type (NULL_TYPE) { php_assert ("Unknown used!!!" && 0); } var::var (bool b): type (BOOLEAN_TYPE), b (b) { } var::var (int i): type (INTEGER_TYPE), i (i) { } var::var (double f): type (FLOAT_TYPE), f (f) { } var::var (const string &s_): type (STRING_TYPE) { new (&s) string (s_); } var::var (const char *s_, int len): type (STRING_TYPE) { new (&s) string (s_, len); } template <class T> var::var (const array <T> &a_): type (ARRAY_TYPE) { new (&a) array <var> (a_); } template <class T> var::var (const object_ptr <T> &o_): type (OBJECT_TYPE) { new (&o) object (o_); } var::var (const OrFalse <int> &v) { if (likely (v.bool_value)) { type = INTEGER_TYPE; i = v.value; } else { type = BOOLEAN_TYPE; b = false; } } var::var (const OrFalse <double> &v) { if (likely (v.bool_value)) { type = FLOAT_TYPE; f = v.value; } else { type = BOOLEAN_TYPE; b = false; } } var::var (const OrFalse <string> &v) { if (likely (v.bool_value)) { type = STRING_TYPE; new (&s) string (v.value); } else { type = BOOLEAN_TYPE; b = false; } } template <class T> var::var (const OrFalse <array <T> > &v) { if (likely (v.bool_value)) { type = ARRAY_TYPE; new (&a) array <var> (v.value); } else { type = BOOLEAN_TYPE; b = false; } } template <class T> var::var (const OrFalse <object_ptr <T> > &v) { if (likely (v.bool_value)) { type = OBJECT_TYPE; new (&o) object (v.value); } else { type = BOOLEAN_TYPE; b = false; } } var::var (const var &v) { copy_from (v); } var& var::operator = (bool other) { switch (type) { case NULL_TYPE: type = BOOLEAN_TYPE; b = other; return *this; case BOOLEAN_TYPE: b = other; return *this; case INTEGER_TYPE: type = BOOLEAN_TYPE; b = other; return *this; case FLOAT_TYPE: type = BOOLEAN_TYPE; b = other; return *this; case STRING_TYPE: STRING(s)->~string(); type = BOOLEAN_TYPE; b = other; return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = BOOLEAN_TYPE; b = other; return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = BOOLEAN_TYPE; b = other; return *this; default: php_assert (0); exit (1); } } var& var::operator = (int other) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = other; return *this; case BOOLEAN_TYPE: type = INTEGER_TYPE; i = other; return *this; case INTEGER_TYPE: i = other; return *this; case FLOAT_TYPE: type = INTEGER_TYPE; i = other; return *this; case STRING_TYPE: STRING(s)->~string(); type = INTEGER_TYPE; i = other; return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = INTEGER_TYPE; i = other; return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = INTEGER_TYPE; i = other; return *this; default: php_assert (0); exit (1); } } var& var::operator = (double other) { switch (type) { case NULL_TYPE: type = FLOAT_TYPE; f = other; return *this; case BOOLEAN_TYPE: type = FLOAT_TYPE; f = other; return *this; case INTEGER_TYPE: type = FLOAT_TYPE; f = other; return *this; case FLOAT_TYPE: f = other; return *this; case STRING_TYPE: STRING(s)->~string(); type = FLOAT_TYPE; f = other; return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = FLOAT_TYPE; f = other; return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = FLOAT_TYPE; f = other; return *this; default: php_assert (0); exit (1); } } var& var::operator = (const string &other) { switch (type) { case NULL_TYPE: type = STRING_TYPE; new (&s) string (other); return *this; case BOOLEAN_TYPE: type = STRING_TYPE; new (&s) string (other); return *this; case INTEGER_TYPE: type = STRING_TYPE; new (&s) string (other); return *this; case FLOAT_TYPE: type = STRING_TYPE; new (&s) string (other); return *this; case STRING_TYPE: *STRING(s) = other; return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = STRING_TYPE; new (&s) string (other); return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = STRING_TYPE; new (&s) string (other); return *this; default: php_assert (0); exit (1); } } var& var::assign (const char *other, int len) { switch (type) { case NULL_TYPE: type = STRING_TYPE; new (&s) string (other, len); return *this; case BOOLEAN_TYPE: type = STRING_TYPE; new (&s) string (other, len); return *this; case INTEGER_TYPE: type = STRING_TYPE; new (&s) string (other, len); return *this; case FLOAT_TYPE: type = STRING_TYPE; new (&s) string (other, len); return *this; case STRING_TYPE: STRING(s)->assign (other, len); return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = STRING_TYPE; new (&s) string (other, len); return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = STRING_TYPE; new (&s) string (other, len); return *this; default: php_assert (0); exit (1); } } template <class T> var& var::operator = (const array <T> &other) { switch (type) { case NULL_TYPE: type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case BOOLEAN_TYPE: type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case INTEGER_TYPE: type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case FLOAT_TYPE: type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case STRING_TYPE: STRING(s)->~string(); type = ARRAY_TYPE; new (&a) array <var> (other); return *this; case ARRAY_TYPE: *ARRAY(a) = other; return *this; case OBJECT_TYPE: OBJECT(o)->~object(); type = ARRAY_TYPE; new (&a) array <var> (other); return *this; default: php_assert (0); exit (1); } } template <class T> var& var::operator = (const object_ptr <T> &other) { switch (type) { case NULL_TYPE: type = OBJECT_TYPE; new (&o) object (other); return *this; case BOOLEAN_TYPE: type = OBJECT_TYPE; new (&o) object (other); return *this; case INTEGER_TYPE: type = OBJECT_TYPE; new (&o) object (other); return *this; case FLOAT_TYPE: type = OBJECT_TYPE; new (&o) object (other); return *this; case STRING_TYPE: STRING(s)->~string(); type = OBJECT_TYPE; new (&o) object (other); return *this; case ARRAY_TYPE: ARRAY(a)->~array <var>(); type = OBJECT_TYPE; new (&o) object (other); return *this; case OBJECT_TYPE: *OBJECT(o) = other; return *this; default: php_assert (0); exit (1); } } var& var::operator = (const var &other) { if (this != &other) { destroy(); copy_from (other); } return *this; /* switch (other.type) { case NULL_TYPE: destroy(); type = NULL_TYPE; return *this; case BOOLEAN_TYPE: return *this = other.b; case INTEGER_TYPE: return *this = other.i; case FLOAT_TYPE: return *this = other.f; case STRING_TYPE: return *this = *STRING(other.s); case ARRAY_TYPE: return *this = *ARRAY(other.a); case OBJECT_TYPE: return *this = *OBJECT(other.o); default: php_assert (0); exit (1); }*/ } var& var::operator = (const OrFalse <int> &other) { destroy(); if (likely (other.bool_value)) { type = INTEGER_TYPE; i = other.value; } else { type = BOOLEAN_TYPE; b = false; } return *this; } var& var::operator = (const OrFalse <double> &other) { destroy(); if (likely (other.bool_value)) { type = FLOAT_TYPE; f = other.value; } else { type = BOOLEAN_TYPE; b = false; } return *this; } var& var::operator = (const OrFalse <string> &other) { if (likely (other.bool_value)) { *this = other.value; } else { destroy(); type = BOOLEAN_TYPE; b = false; } return *this; } template <class T> var& var::operator = (const OrFalse <array <T> > &other) { if (likely (other.bool_value)) { *this = other.value; } else { destroy(); type = BOOLEAN_TYPE; b = false; } return *this; } template <class T> var& var::operator = (const OrFalse <object_ptr <T> > &other) { if (likely (other.bool_value)) { *this = other.value; } else { destroy(); type = BOOLEAN_TYPE; b = false; } return *this; } const var var::operator - (void) const { var arg1 = to_numeric(); if (arg1.type == INTEGER_TYPE) { arg1.i = -arg1.i; } else { arg1.f = -arg1.f; } return arg1; } const var var::operator + (void) const { return to_numeric(); } int var::operator ~(void) const { return ~to_int(); } var& var::operator += (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { i += other.i; return *this; } if (unlikely (type == ARRAY_TYPE || other.type == ARRAY_TYPE)) { if (type == ARRAY_TYPE && other.type == ARRAY_TYPE) { *ARRAY(a) += *ARRAY(other.a); } else { php_warning ("Unsupported operand types for operator += (%s and %s)", get_type_c_str(), other.get_type_c_str()); } return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { i += arg2.i; } else { type = FLOAT_TYPE; f = i + arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f += arg2.i; } else { f += arg2.f; } } return *this; } var& var::operator -= (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { i -= other.i; return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { i -= arg2.i; } else { type = FLOAT_TYPE; f = i - arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f -= arg2.i; } else { f -= arg2.f; } } return *this; } var& var::operator *= (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { i *= other.i; return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { i *= arg2.i; } else { type = FLOAT_TYPE; f = i * arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f *= arg2.i; } else { f *= arg2.f; } } return *this; } var& var::operator /= (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { if (i % other.i == 0) { i /= other.i; } else { type = FLOAT_TYPE; f = (double)i / other.i; } return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (arg2.type == INTEGER_TYPE) { if (arg2.i == 0) { php_warning ("Integer division by zero"); type = BOOLEAN_TYPE; b = false; return *this; } if (type == INTEGER_TYPE) { if (i % arg2.i == 0) { i /= arg2.i; } else { type = FLOAT_TYPE; f = (double)i / other.i; } } else { f /= arg2.i; } } else { if (arg2.f == 0) { php_warning ("Float division by zero"); type = BOOLEAN_TYPE; b = false; return *this; } if (type == INTEGER_TYPE) { type = FLOAT_TYPE; f = i / arg2.f; } else { f /= arg2.f; } } return *this; } var& var::operator %= (const var &other) { int div = other.to_int(); if (div == 0) { php_warning ("Modulo by zero"); *this = false; return *this; } convert_to_int(); i %= div; return *this; } var& var::operator &= (const var &other) { convert_to_int(); i &= other.to_int(); return *this; } var& var::operator |= (const var &other) { convert_to_int(); i |= other.to_int(); return *this; } var& var::operator ^= (const var &other) { convert_to_int(); i ^= other.to_int(); return *this; } var& var::operator <<= (const var &other) { convert_to_int(); i <<= other.to_int(); return *this; } var& var::operator >>= (const var &other) { convert_to_int(); i >>= other.to_int(); return *this; } var& var::safe_set_add (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { ::safe_set_add (i, other.i); return *this; } if (unlikely (type == ARRAY_TYPE || other.type == ARRAY_TYPE)) { if (type == ARRAY_TYPE && other.type == ARRAY_TYPE) { *ARRAY(a) += *ARRAY(other.a); } else { php_warning ("Unsupported operand types for operator += (%s and %s)", get_type_c_str(), other.get_type_c_str()); } return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { ::safe_set_add (i, arg2.i); } else { type = FLOAT_TYPE; f = i + arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f += arg2.i; } else { f += arg2.f; } } return *this; } var& var::safe_set_sub (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { ::safe_set_sub (i, other.i); return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { ::safe_set_sub (i, arg2.i); } else { type = FLOAT_TYPE; f = i - arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f -= arg2.i; } else { f -= arg2.f; } } return *this; } var& var::safe_set_mul (const var &other) { if (likely (type == INTEGER_TYPE && other.type == INTEGER_TYPE)) { ::safe_set_mul (i, other.i); return *this; } convert_to_numeric(); const var arg2 = other.to_numeric(); if (type == INTEGER_TYPE) { if (arg2.type == INTEGER_TYPE) { ::safe_set_mul (i, arg2.i); } else { type = FLOAT_TYPE; f = i * arg2.f; } } else { if (arg2.type == INTEGER_TYPE) { f *= arg2.i; } else { f *= arg2.f; } } return *this; } var& var::safe_set_shl (const var &other) { safe_convert_to_int(); ::safe_set_shl (i, other.safe_to_int()); return *this; } var& var::operator ++ (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 1; return *this; case BOOLEAN_TYPE: php_warning ("Can't apply operator ++ to boolean"); return *this; case INTEGER_TYPE: ++i; return *this; case FLOAT_TYPE: f += 1; return *this; case STRING_TYPE: *this = STRING(s)->to_numeric(); return ++(*this); case ARRAY_TYPE: php_warning ("Can't apply operator ++ to array"); return *this; case OBJECT_TYPE: php_warning ("Can't apply operator ++ to object"); return *this; default: php_assert (0); exit (1); } } const var var::operator ++ (int) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 1; return var(); case BOOLEAN_TYPE: php_warning ("Can't apply operator ++ to boolean"); return b; case INTEGER_TYPE: { var res (i); ++i; return res; } case FLOAT_TYPE: { var res (f); f += 1; return res; } case STRING_TYPE: { var res (*STRING(s)); *this = STRING(s)->to_numeric(); (*this)++; return res; } case ARRAY_TYPE: php_warning ("Can't apply operator ++ to array"); return *ARRAY(a); case OBJECT_TYPE: php_warning ("Can't apply operator ++ to object"); return *this; default: php_assert (0); exit (1); } } var& var::operator -- (void) { if (likely (type == INTEGER_TYPE)) { --i; return *this; } switch (type) { case NULL_TYPE: php_warning ("Can't apply operator -- to null"); return *this; case BOOLEAN_TYPE: php_warning ("Can't apply operator -- to boolean"); return *this; case INTEGER_TYPE: --i; return *this; case FLOAT_TYPE: f -= 1; return *this; case STRING_TYPE: *this = STRING(s)->to_numeric(); return --(*this); case ARRAY_TYPE: php_warning ("Can't apply operator -- to array"); return *this; case OBJECT_TYPE: php_warning ("Can't apply operator -- to object"); return *this; default: php_assert (0); exit (1); } } const var var::operator -- (int) { if (likely (type == INTEGER_TYPE)) { var res (i); --i; return res; } switch (type) { case NULL_TYPE: php_warning ("Can't apply operator -- to null"); return var(); case BOOLEAN_TYPE: php_warning ("Can't apply operator -- to boolean"); return b; case INTEGER_TYPE: { var res (i); --i; return res; } case FLOAT_TYPE: { var res (f); f -= 1; return res; } case STRING_TYPE: { var res (*STRING(s)); *this = STRING(s)->to_numeric(); (*this)--; return res; } case ARRAY_TYPE: php_warning ("Can't apply operator -- to array"); return *ARRAY(a); case OBJECT_TYPE: php_warning ("Can't apply operator -- to object"); return *this; default: php_assert (0); exit (1); } } var& var::safe_incr_pre (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 1; return *this; case BOOLEAN_TYPE: php_warning ("Can't apply operator ++ to boolean"); return *this; case INTEGER_TYPE: ::safe_incr_pre (i); return *this; case FLOAT_TYPE: f += 1; return *this; case STRING_TYPE: *this = STRING(s)->to_numeric(); return safe_incr_pre(); case ARRAY_TYPE: php_warning ("Can't apply operator ++ to array"); return *this; case OBJECT_TYPE: php_warning ("Can't apply operator ++ to object"); return *this; default: php_assert (0); exit (1); } } const var var::safe_incr_post (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 1; return var(); case BOOLEAN_TYPE: php_warning ("Can't apply operator ++ to boolean"); return b; case INTEGER_TYPE: { var res (i); ::safe_incr_post (i); return res; } case FLOAT_TYPE: { var res (f); f += 1; return res; } case STRING_TYPE: { var res (*STRING(s)); *this = STRING(s)->to_numeric(); safe_incr_post(); return res; } case ARRAY_TYPE: php_warning ("Can't apply operator ++ to array"); return *ARRAY(a); case OBJECT_TYPE: php_warning ("Can't apply operator ++ to object"); return *this; default: php_assert (0); exit (1); } } var& var::safe_decr_pre (void) { switch (type) { case NULL_TYPE: php_warning ("Can't apply operator -- to null"); return *this; case BOOLEAN_TYPE: php_warning ("Can't apply operator -- to boolean"); return *this; case INTEGER_TYPE: ::safe_decr_pre (i); return *this; case FLOAT_TYPE: f -= 1; return *this; case STRING_TYPE: *this = STRING(s)->to_numeric(); return safe_decr_pre(); case ARRAY_TYPE: php_warning ("Can't apply operator -- to array"); return *this; case OBJECT_TYPE: php_warning ("Can't apply operator -- to object"); return *this; default: php_assert (0); exit (1); } } const var var::safe_decr_post (void) { switch (type) { case NULL_TYPE: php_warning ("Can't apply operator -- to null"); return var(); case BOOLEAN_TYPE: php_warning ("Can't apply operator -- to boolean"); return b; case INTEGER_TYPE: { var res (i); ::safe_decr_post (i); return res; } case FLOAT_TYPE: { var res (f); f -= 1; return res; } case STRING_TYPE: { var res (*STRING(s)); *this = STRING(s)->to_numeric(); safe_decr_post(); return res; } case ARRAY_TYPE: php_warning ("Can't apply operator -- to array"); return *ARRAY(a); case OBJECT_TYPE: php_warning ("Can't apply operator -- to object"); return *this; default: php_assert (0); exit (1); } } bool var::operator ! (void) const { return !to_bool(); } var& var::append (const string &v) { if (unlikely (type != STRING_TYPE)) { convert_to_string(); } STRING(s)->append (v); return *this; } void var::destroy (void) { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: break; case STRING_TYPE: STRING(s)->~string(); break; case ARRAY_TYPE: ARRAY(a)->~array <var>(); break; case OBJECT_TYPE: OBJECT(o)->~object(); break; default: php_assert (0); exit (1); } } var::~var (void) { destroy(); type = NULL_TYPE; } const var var::to_numeric (void) const { switch (type) { case NULL_TYPE: return 0; case BOOLEAN_TYPE: return (b ? 1 : 0); case INTEGER_TYPE: return i; case FLOAT_TYPE: return f; case STRING_TYPE: return STRING(s)->to_numeric(); case ARRAY_TYPE: php_warning ("Wrong convertion from array to number"); return ARRAY(a)->to_int(); case OBJECT_TYPE: php_warning ("Wrong convertion from object to number"); return 1; default: php_assert (0); exit (1); } } bool var::to_bool (void) const { switch (type) { case NULL_TYPE: return false; case BOOLEAN_TYPE: return b; case INTEGER_TYPE: return (bool)i; case FLOAT_TYPE: return (bool)f; case STRING_TYPE: return STRING(s)->to_bool(); case ARRAY_TYPE: return !ARRAY(a)->empty(); case OBJECT_TYPE: return true; default: php_assert (0); exit (1); } } int var::to_int (void) const { switch (type) { case NULL_TYPE: return 0; case BOOLEAN_TYPE: return (int)b; case INTEGER_TYPE: return i; case FLOAT_TYPE: return (int)f; case STRING_TYPE: return STRING(s)->to_int(); case ARRAY_TYPE: php_warning ("Wrong convertion from array to int"); return ARRAY(a)->to_int(); case OBJECT_TYPE: php_warning ("Wrong convertion from object to int"); return 1; default: php_assert (0); exit (1); } } double var::to_float (void) const { switch (type) { case NULL_TYPE: return 0.0; case BOOLEAN_TYPE: return (b ? 1.0 : 0.0); case INTEGER_TYPE: return (double)i; case FLOAT_TYPE: return f; case STRING_TYPE: return STRING(s)->to_float(); case ARRAY_TYPE: php_warning ("Wrong convertion from array to float"); return ARRAY(a)->to_float(); case OBJECT_TYPE: php_warning ("Wrong convertion from object to float"); return 1.0; default: php_assert (0); exit (1); } } const string var::to_string (void) const { switch (type) { case NULL_TYPE: return string(); case BOOLEAN_TYPE: return (b ? string ("1", 1) : string()); case INTEGER_TYPE: return string (i); case FLOAT_TYPE: return string (f); case STRING_TYPE: return *STRING(s); case ARRAY_TYPE: php_warning ("Convertion from array to string"); return string ("Array", 5); case OBJECT_TYPE: return OBJECT(o)->to_string(); default: php_assert (0); exit (1); } } const array <var> var::to_array (void) const { switch (type) { case NULL_TYPE: return array <var>(); case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: { array <var> res (array_size (1, 0, true)); res.push_back (*this); return res; } case ARRAY_TYPE: return *ARRAY(a); case OBJECT_TYPE: return OBJECT(o)->to_array(); default: php_assert (0); exit (1); } } const object var::to_object (void) const { switch (type) { case NULL_TYPE: return object(); case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: { object res; res.set (string ("scalar", 6), *this); return res; } case ARRAY_TYPE: return ARRAY(a)->to_object(); case OBJECT_TYPE: return *OBJECT(o); default: php_assert (0); exit (1); } } int var::safe_to_int (void) const { switch (type) { case NULL_TYPE: return 0; case BOOLEAN_TYPE: return (int)b; case INTEGER_TYPE: return i; case FLOAT_TYPE: if (fabs (f) > 2147483648) { php_warning ("Wrong convertion from double %.6lf to int", f); } return (int)f; case STRING_TYPE: return STRING(s)->safe_to_int(); case ARRAY_TYPE: php_warning ("Wrong convertion from array to int"); return ARRAY(a)->to_int(); case OBJECT_TYPE: php_warning ("Wrong convertion from object to int"); return 1; default: php_assert (0); exit (1); } } void var::convert_to_numeric (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 0; return; case BOOLEAN_TYPE: type = INTEGER_TYPE; i = b; return; case INTEGER_TYPE: case FLOAT_TYPE: return; case STRING_TYPE: *this = STRING(s)->to_numeric(); return; case ARRAY_TYPE: { php_warning ("Wrong convertion from array to number"); int int_val = ARRAY(a)->to_int(); ARRAY(a)->~array <var>(); type = INTEGER_TYPE; i = int_val; return; } case OBJECT_TYPE: php_warning ("Wrong convertion from object to number"); OBJECT(o)->~object(); type = INTEGER_TYPE; i = 1; return; default: php_assert (0); exit (1); } } void var::convert_to_bool (void) { switch (type) { case NULL_TYPE: type = BOOLEAN_TYPE; b = 0; return; case BOOLEAN_TYPE: return; case INTEGER_TYPE: type = BOOLEAN_TYPE; b = (bool)i; return; case FLOAT_TYPE: type = BOOLEAN_TYPE; b = (bool)f; return; case STRING_TYPE: { bool bool_val = STRING(s)->to_bool(); STRING(s)->~string(); type = BOOLEAN_TYPE; b = bool_val; return; } case ARRAY_TYPE: { bool bool_val = ARRAY(a)->to_bool(); ARRAY(a)->~array <var>(); type = BOOLEAN_TYPE; b = bool_val; return; } case OBJECT_TYPE: OBJECT(o)->~object(); type = BOOLEAN_TYPE; b = true; return; default: php_assert (0); exit (1); } } void var::convert_to_int (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 0; return; case BOOLEAN_TYPE: type = INTEGER_TYPE; i = b; return; case INTEGER_TYPE: return; case FLOAT_TYPE: type = INTEGER_TYPE; i = (int)f; return; case STRING_TYPE: { int int_val = STRING(s)->to_int(); STRING(s)->~string(); type = INTEGER_TYPE; i = int_val; return; } case ARRAY_TYPE: { php_warning ("Wrong convertion from array to int"); int int_val = ARRAY(a)->to_int(); ARRAY(a)->~array <var>(); type = INTEGER_TYPE; i = int_val; return; } case OBJECT_TYPE: php_warning ("Wrong convertion from object to int"); OBJECT(o)->~object(); type = INTEGER_TYPE; i = 1; return; default: php_assert (0); exit (1); } } void var::convert_to_float (void) { switch (type) { case NULL_TYPE: type = FLOAT_TYPE; f = 0.0; return; case BOOLEAN_TYPE: type = FLOAT_TYPE; f = b; return; case INTEGER_TYPE: type = FLOAT_TYPE; f = (double)i; return; case FLOAT_TYPE: return; case STRING_TYPE: { double float_val = STRING(s)->to_float(); STRING(s)->~string(); type = FLOAT_TYPE; f = float_val; return; } case ARRAY_TYPE: { php_warning ("Wrong convertion from array to float"); double float_val = ARRAY(a)->to_float(); ARRAY(a)->~array <var>(); type = FLOAT_TYPE; f = float_val; return; } case OBJECT_TYPE: php_warning ("Wrong convertion from object to float"); OBJECT(o)->~object(); type = FLOAT_TYPE; f = 1.0; return; default: php_assert (0); exit (1); } } void var::convert_to_string (void) { switch (type) { case NULL_TYPE: type = STRING_TYPE; new (&s) string(); return; case BOOLEAN_TYPE: type = STRING_TYPE; if (b) { new (&s) string ("1", 1); } else { new (&s) string(); } return; case INTEGER_TYPE: type = STRING_TYPE; new (&s) string (i); return; case FLOAT_TYPE: type = STRING_TYPE; new (&s) string (f); return; case STRING_TYPE: return; case ARRAY_TYPE: php_warning ("Converting from array to string"); ARRAY(a)->~array <var>(); type = STRING_TYPE; new (&s) string ("Array", 5); return; case OBJECT_TYPE: { string res = OBJECT(o)->to_string(); OBJECT(o)->~object(); type = STRING_TYPE; new (&s) string (res); return; } default: php_assert (0); exit (1); } } void var::safe_convert_to_int (void) { switch (type) { case NULL_TYPE: type = INTEGER_TYPE; i = 0; return; case BOOLEAN_TYPE: type = INTEGER_TYPE; i = (int)b; return; case INTEGER_TYPE: return; case FLOAT_TYPE: type = INTEGER_TYPE; if (fabs (f) > 2147483648) { php_warning ("Wrong convertion from double %.6lf to int", f); } i = (int)f; return; case STRING_TYPE: { int int_val = STRING(s)->safe_to_int(); STRING(s)->~string(); type = INTEGER_TYPE; i = int_val; return; } case ARRAY_TYPE: { php_warning ("Wrong convertion from array to int"); int int_val = ARRAY(a)->to_int(); ARRAY(a)->~array <var>(); type = INTEGER_TYPE; i = int_val; return; } case OBJECT_TYPE: php_warning ("Wrong convertion from object to int"); OBJECT(o)->~object(); type = INTEGER_TYPE; i = 1; return; default: php_assert (0); exit (1); } } const bool& var::as_bool (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be boolean, %s is given", function, parameter_num, get_type_c_str()); empty_bool = false; return empty_bool; case BOOLEAN_TYPE: return b; default: php_assert (0); exit (1); } } const int& var::as_int (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case FLOAT_TYPE: case STRING_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be int, %s is given", function, parameter_num, get_type_c_str()); empty_int = 0; return empty_int; case INTEGER_TYPE: return i; default: php_assert (0); exit (1); } } const double& var::as_float (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case STRING_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be float, %s is given", function, parameter_num, get_type_c_str()); empty_float = 0; return empty_float; case FLOAT_TYPE: return f; default: php_assert (0); exit (1); } } const string& var::as_string (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be string, %s is given", function, parameter_num, get_type_c_str()); empty_string = string(); return empty_string; case STRING_TYPE: return *STRING(s); default: php_assert (0); exit (1); } } const array <var>& var::as_array (const char *function, int parameter_num) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be array, %s is given", function, parameter_num, get_type_c_str()); *empty_array_var = array <var>(); return *empty_array_var; case ARRAY_TYPE: return *ARRAY(a); default: php_assert (0); exit (1); } } bool& var::as_bool (const char *function, int parameter_num) { switch (type) { case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be boolean, %s is given", function, parameter_num, get_type_c_str()); empty_bool = false; return empty_bool; case NULL_TYPE: convert_to_bool(); case BOOLEAN_TYPE: return b; default: php_assert (0); exit (1); } } int& var::as_int (const char *function, int parameter_num) { switch (type) { case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be int, %s is given", function, parameter_num, get_type_c_str()); empty_int = 0; return empty_int; case NULL_TYPE: case BOOLEAN_TYPE: case FLOAT_TYPE: case STRING_TYPE: convert_to_int(); case INTEGER_TYPE: return i; default: php_assert (0); exit (1); } } double& var::as_float (const char *function, int parameter_num) { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case STRING_TYPE: convert_to_float(); case FLOAT_TYPE: return f; case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be float, %s is given", function, parameter_num, get_type_c_str()); empty_float = 0; return empty_float; default: php_assert (0); exit (1); } } string& var::as_string (const char *function, int parameter_num) { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: convert_to_string(); case STRING_TYPE: return *STRING(s); case ARRAY_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be string, %s is given", function, parameter_num, get_type_c_str()); empty_string = string(); return empty_string; default: php_assert (0); exit (1); } } array <var>& var::as_array (const char *function, int parameter_num) { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: case OBJECT_TYPE: php_warning ("%s() expects parameter %d to be array, %s is given", function, parameter_num, get_type_c_str()); *empty_array_var = array <var>(); return *empty_array_var; case ARRAY_TYPE: return *ARRAY(a); default: php_assert (0); exit (1); } } bool var::is_numeric (void) const { switch (type) { case NULL_TYPE: case BOOLEAN_TYPE: return false; case INTEGER_TYPE: case FLOAT_TYPE: return true; case STRING_TYPE: return STRING(s)->is_numeric(); case ARRAY_TYPE: case OBJECT_TYPE: return false; default: php_assert (0); exit (1); } } bool var::is_scalar (void) const { return type != NULL_TYPE && type != ARRAY_TYPE && type != OBJECT_TYPE; } bool var::is_null (void) const { return type == NULL_TYPE; } bool var::is_bool (void) const { return type == BOOLEAN_TYPE; } bool var::is_int (void) const { return type == INTEGER_TYPE; } bool var::is_float (void) const { return type == FLOAT_TYPE; } bool var::is_string (void) const { return type == STRING_TYPE; } bool var::is_array (void) const { return type == ARRAY_TYPE; } bool var::is_object (void) const { return type == OBJECT_TYPE; } inline const char *var::get_type_c_str (void) const { switch (type) { case NULL_TYPE: return "NULL"; case BOOLEAN_TYPE: return "boolean"; case INTEGER_TYPE: return "integer"; case FLOAT_TYPE: return "double"; case STRING_TYPE: return "string"; case ARRAY_TYPE: return "array"; case OBJECT_TYPE: return "object"; default: php_assert (0); exit (1); } } inline const string var::get_type (void) const { const char *result = get_type_c_str(); return string (result, (dl::size_type)strlen (result)); } bool var::empty (void) const { return !to_bool(); } int var::count (void) const { switch (type) { case NULL_TYPE: return 0; case BOOLEAN_TYPE: case INTEGER_TYPE: case FLOAT_TYPE: case STRING_TYPE: return 1; case ARRAY_TYPE: return ARRAY(a)->count(); case OBJECT_TYPE: return 1; default: php_assert (0); exit (1); } } void var::swap (var &other) { ::swap (type, other.type); ::swap (f, other.f); } var& var::operator[] (int int_key) { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { php_warning ("Lvalue string offset doesn't supported"); empty_var = var(); return empty_var; } if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %d", to_string().c_str(), get_type_c_str(), int_key); empty_var = var(); return empty_var; } } return (*ARRAY(a))[int_key]; } var& var::operator[] (const string &string_key) { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { php_warning ("Lvalue string offset doesn't supported"); empty_var = var(); return empty_var; } if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string().c_str(), get_type_c_str(), string_key.c_str()); empty_var = var(); return empty_var; } } return (*ARRAY(a))[string_key]; } var& var::operator[] (const var &v) { switch (v.type) { case NULL_TYPE: return (*this)[string()]; case BOOLEAN_TYPE: return (*this)[v.b]; case INTEGER_TYPE: return (*this)[v.i]; case FLOAT_TYPE: return (*this)[(int)v.f]; case STRING_TYPE: return (*this)[*STRING(v.s)]; case ARRAY_TYPE: php_warning ("Illegal offset type %s", v.get_type_c_str()); return (*this)[ARRAY(v.a)->to_int()]; case OBJECT_TYPE: php_warning ("Illegal offset type %s", v.get_type_c_str()); return (*this)[1]; default: php_assert (0); exit (1); } } var& var::operator[] (const array <var>::const_iterator &it) { return (*ARRAY(a))[it]; } var& var::operator[] (const array <var>::iterator &it) { return (*ARRAY(a))[it]; } void var::set_value (int int_key, const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { char c = (v.to_string())[0]; if (int_key >= 0) { int l = STRING(s)->size(); if (int_key >= l) { STRING(s)->append (int_key + 1 - l, ' '); } else { STRING(s)->make_not_shared(); } (*STRING(s))[int_key] = c; } else { php_warning ("Illegal string offset %d", int_key); } return; } if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %d", to_string().c_str(), get_type_c_str(), int_key); return; } } return ARRAY(a)->set_value (int_key, v); } void var::set_value (const string &string_key, const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { int int_val; if (!string_key.try_to_int (&int_val)) { php_warning ("Illegal string offset \"%s\"", string_key.c_str()); int_val = string_key.to_int(); } if (int_val < 0) { return; } char c = (v.to_string())[0]; int l = STRING(s)->size(); if (int_val >= l) { STRING(s)->append (int_val + 1 - l, ' '); } else { STRING(s)->make_not_shared(); } (*STRING(s))[int_val] = c; return; } if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string().c_str(), get_type_c_str(), string_key.c_str()); return; } } return ARRAY(a)->set_value (string_key, v); } void var::set_value (const var &v, const var &value) { switch (v.type) { case NULL_TYPE: return set_value (string(), value); case BOOLEAN_TYPE: return set_value (v.b, value); case INTEGER_TYPE: return set_value (v.i, value); case FLOAT_TYPE: return set_value ((int)v.f, value); case STRING_TYPE: return set_value (*STRING(v.s), value); case ARRAY_TYPE: php_warning ("Illegal offset type array"); return; case OBJECT_TYPE: php_warning ("Illegal offset type object"); return; default: php_assert (0); exit (1); } } void var::set_value (const array <var>::const_iterator &it) { return ARRAY(a)->set_value (it); } void var::set_value (const array <var>::iterator &it) { return ARRAY(a)->set_value (it); } const var var::get_value (int int_key) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { if ((dl::size_type)int_key >= STRING(s)->size()) { return string(); } return string (1, (*STRING(s))[int_key]); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %d", to_string().c_str(), get_type_c_str(), int_key); } return var(); } return ARRAY(a)->get_value (int_key); } const var var::get_value (const string &string_key) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { int int_val; if (!string_key.try_to_int (&int_val)) { php_warning ("Illegal string offset \"%s\"", string_key.c_str()); int_val = string_key.to_int(); } if ((dl::size_type)int_val >= STRING(s)->size()) { return string(); } return string (1, (*STRING(s))[int_val]); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use a value \"%s\" of type %s as an array, index = %s", to_string().c_str(), get_type_c_str(), string_key.c_str()); } return var(); } return ARRAY(a)->get_value (string_key); } const var var::get_value (const var &v) const { switch (v.type) { case NULL_TYPE: return get_value (string()); case BOOLEAN_TYPE: return get_value (v.b); case INTEGER_TYPE: return get_value (v.i); case FLOAT_TYPE: return get_value ((int)v.f); case STRING_TYPE: return get_value (*STRING(v.s)); case ARRAY_TYPE: php_warning ("Illegal offset type %s", v.get_type_c_str()); return var(); case OBJECT_TYPE: php_warning ("Illegal offset type %s", v.get_type_c_str()); return var(); default: php_assert (0); exit (1); } } const var var::get_value (const array <var>::const_iterator &it) const { return ARRAY(a)->get_value (it); } const var var::get_value (const array <var>::iterator &it) const { return ARRAY(a)->get_value (it); } void var::push_back (const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("[] operator not supported for type %s", get_type_c_str()); return; } } return ARRAY(a)->push_back (v); } const var var::push_back_return (const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type == NULL_TYPE || (type == BOOLEAN_TYPE && !b)) { type = ARRAY_TYPE; new (&a) array <var>(); } else { php_warning ("[] operator not supported for type %s", get_type_c_str()); empty_var = var(); return empty_var; } } return ARRAY(a)->push_back_return (v); } bool var::isset (int int_key) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { return (dl::size_type)int_key < STRING(s)->size(); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in isset", get_type_c_str()); } return false; } return ARRAY(a)->isset (int_key); } bool var::isset (const string &string_key) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { int int_val; if (!string_key.try_to_int (&int_val)) { php_warning ("Illegal string offset \"%s\"", string_key.c_str()); int_val = string_key.to_int(); } return (dl::size_type)int_val < STRING(s)->size(); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in isset", get_type_c_str()); } return false; } return ARRAY(a)->isset (string_key); } bool var::isset (const var &v) const { if (unlikely (type != ARRAY_TYPE)) { if (type == STRING_TYPE) { return (dl::size_type)(v.to_int()) < STRING(s)->size(); } if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in isset", get_type_c_str()); } return false; } switch (v.type) { case NULL_TYPE: return ARRAY(a)->isset (string()); case BOOLEAN_TYPE: return ARRAY(a)->isset (v.b); case INTEGER_TYPE: return ARRAY(a)->isset (v.i); case FLOAT_TYPE: return ARRAY(a)->isset ((int)v.f); case STRING_TYPE: return ARRAY(a)->isset (*STRING(v.s)); case ARRAY_TYPE: php_warning ("Illegal offset type array"); return false; case OBJECT_TYPE: php_warning ("Illegal offset type object"); return false; default: php_assert (0); exit (1); } } bool var::isset (const array <var>::const_iterator &it) const { return ARRAY(a)->isset (it); } bool var::isset (const array <var>::iterator &it) const { return ARRAY(a)->isset (it); } void var::unset (int int_key) { if (unlikely (type != ARRAY_TYPE)) { if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in unset", get_type_c_str()); } return; } return ARRAY(a)->unset (int_key); } void var::unset (const string &string_key) { if (unlikely (type != ARRAY_TYPE)) { if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in unset", get_type_c_str()); } return; } return ARRAY(a)->unset (string_key); } void var::unset (const var &v) { if (unlikely (type != ARRAY_TYPE)) { if (type != NULL_TYPE && (type != BOOLEAN_TYPE || b)) { php_warning ("Cannot use variable of type %s as array in unset", get_type_c_str()); } return; } switch (v.type) { case NULL_TYPE: return ARRAY(a)->unset (string()); case BOOLEAN_TYPE: return ARRAY(a)->unset (v.b); case INTEGER_TYPE: return ARRAY(a)->unset (v.i); case FLOAT_TYPE: return ARRAY(a)->unset ((int)v.f); case STRING_TYPE: return ARRAY(a)->unset (*STRING(v.s)); case ARRAY_TYPE: php_warning ("Illegal offset type array"); return; case OBJECT_TYPE: php_warning ("Illegal offset type object"); return; default: php_assert (0); exit (1); } } void var::unset (const array <var>::const_iterator &it) { return ARRAY(a)->unset (it); } void var::unset (const array <var>::iterator &it) { return ARRAY(a)->unset (it); } array <var>::const_iterator var::begin (void) const { if (likely (type == ARRAY_TYPE)) { return CONST_ARRAY(a)->begin(); } php_warning ("Invalid argument supplied for foreach(), %s \"%s\" is given", get_type_c_str(), to_string().c_str()); return array <var>::const_iterator(); } array <var>::const_iterator var::end (void) const { if (likely (type == ARRAY_TYPE)) { return CONST_ARRAY(a)->end(); } return array <var>::const_iterator(); } array <var>::iterator var::begin (void) { if (likely (type == ARRAY_TYPE)) { return ARRAY(a)->begin(); } php_warning ("Invalid argument supplied for foreach(), %s \"%s\" is given", get_type_c_str(), to_string().c_str()); return array <var>::iterator(); } array <var>::iterator var::end (void) { if (likely (type == ARRAY_TYPE)) { return ARRAY(a)->end(); } return array <var>::iterator(); } int var::get_reference_counter (void) const { switch (type) { case NULL_TYPE: return -1; case BOOLEAN_TYPE: return -2; case INTEGER_TYPE: return -3; case FLOAT_TYPE: return -4; case STRING_TYPE: return STRING(s)->get_reference_counter(); case ARRAY_TYPE: return ARRAY(a)->get_reference_counter(); case OBJECT_TYPE: return OBJECT(o)->get_reference_counter(); default: php_assert (0); exit (1); } } const var operator + (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return lhs.i + rhs.i; } if (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE) { return *ARRAY(lhs.a) + *ARRAY(rhs.a); } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return arg1.i + arg2.i; } else { return arg1.i + arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f + arg2.i; } else { return arg1.f + arg2.f; } } } const var operator - (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return lhs.i - rhs.i; } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return arg1.i - arg2.i; } else { return arg1.i - arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f - arg2.i; } else { return arg1.f - arg2.f; } } } const var operator * (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return lhs.i * rhs.i; } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return arg1.i * arg2.i; } else { return arg1.i * arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f * arg2.i; } else { return arg1.f * arg2.f; } } } const var operator / (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { if (rhs.i == 0) { php_warning ("Integer division by zero"); return false; } if (lhs.i % rhs.i == 0) { return lhs.i / rhs.i; } return (double)lhs.i / rhs.i; } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg2.type == var::INTEGER_TYPE) { if (arg2.i == 0) { php_warning ("Integer division by zero"); return false; } if (arg1.type == var::INTEGER_TYPE) { if (arg1.i % arg2.i == 0) { return arg1.i / arg2.i; } return (double)arg1.i / arg2.i; } else { return arg1.f / arg2.i; } } else { if (arg2.f == 0.0) { php_warning ("Float division by zero"); return false; } if (arg1.type == var::INTEGER_TYPE) { return arg1.i / arg2.f; } else { return arg1.f / arg2.f; } } } const var operator % (const var &lhs, const var &rhs) { int div = rhs.to_int(); if (div == 0) { php_warning ("Modulo by zero"); return false; } return lhs.to_int() % div; } const var operator - (const string &lhs) { var arg1 = lhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { arg1.i = -arg1.i; } else { arg1.f = -arg1.f; } return arg1; } const var operator + (const string &lhs) { return lhs.to_numeric(); } int operator & (const var &lhs, const var &rhs) { return lhs.to_int() & rhs.to_int(); } int operator | (const var &lhs, const var &rhs) { return lhs.to_int() | rhs.to_int(); } int operator ^ (const var &lhs, const var &rhs) { return lhs.to_int() ^ rhs.to_int(); } int operator << (const var &lhs, const var &rhs) { return lhs.to_int() << rhs.to_int(); } int operator >> (const var &lhs, const var &rhs) { return lhs.to_int() >> rhs.to_int(); } const var safe_add (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return safe_add (lhs.i, rhs.i); } if (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE) { return *ARRAY(lhs.a) + *ARRAY(rhs.a); } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return safe_add (arg1.i, arg2.i); } else { return arg1.i + arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f + arg2.i; } else { return arg1.f + arg2.f; } } } const var safe_sub (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return safe_sub (lhs.i, rhs.i); } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return safe_sub (arg1.i, arg2.i); } else { return arg1.i - arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f - arg2.i; } else { return arg1.f - arg2.f; } } } const var safe_mul (const var &lhs, const var &rhs) { if (likely (lhs.type == var::INTEGER_TYPE && rhs.type == var::INTEGER_TYPE)) { return safe_mul (lhs.i, rhs.i); } const var arg1 = lhs.to_numeric(); const var arg2 = rhs.to_numeric(); if (arg1.type == var::INTEGER_TYPE) { if (arg2.type == var::INTEGER_TYPE) { return safe_mul (arg1.i, arg2.i); } else { return arg1.i * arg2.f; } } else { if (arg2.type == var::INTEGER_TYPE) { return arg1.f * arg2.i; } else { return arg1.f * arg2.f; } } } const var safe_shl (const var &lhs, const var &rhs) { return safe_shl (lhs.safe_to_int(), rhs.safe_to_int()); } bool eq2 (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { return eq2 (*STRING(lhs.s), *STRING(rhs.s)); } else if (unlikely (rhs.type == var::NULL_TYPE)) { return STRING(lhs.s)->size() == 0; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return STRING(rhs.s)->size() == 0; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() == rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return eq2 (*ARRAY(lhs.a), *ARRAY(rhs.a)); } php_warning ("Unsupported operand types for operator == (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return false; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { if (likely (lhs.type == var::OBJECT_TYPE && rhs.type == var::OBJECT_TYPE)) { return eq2 (*OBJECT(lhs.o), *OBJECT(rhs.o)); } php_warning ("Unsupported operand types for operator == (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return false; } return lhs.to_float() == rhs.to_float(); } bool neq2 (const var &lhs, const var &rhs) { return !eq2 (lhs, rhs); } bool operator <= (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { if (STRING(lhs.s)[0][0] <= '9' && STRING(rhs.s)[0][0] <= '9') { int lhs_int_val, rhs_int_val; if (STRING(lhs.s)->try_to_int (&lhs_int_val) && STRING(rhs.s)->try_to_int (&rhs_int_val)) { return lhs_int_val <= rhs_int_val; } double lhs_float_val, rhs_float_val; if (STRING(lhs.s)->try_to_float (&lhs_float_val) && STRING(rhs.s)->try_to_float (&rhs_float_val)) { STRING(lhs.s)->warn_on_float_conversion(); STRING(rhs.s)->warn_on_float_conversion(); if (is_ok_float (lhs_float_val) && is_ok_float (rhs_float_val)) { return lhs_float_val <= rhs_float_val; } } } return STRING(lhs.s)->compare (*STRING(rhs.s)) <= 0; } else if (unlikely (rhs.type == var::NULL_TYPE)) { return STRING(lhs.s)->size() == 0; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return true; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() <= rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return ARRAY(lhs.a)->count() <= ARRAY(rhs.a)->count(); } php_warning ("Unsupported operand types for operator <= (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return rhs.type == var::ARRAY_TYPE; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { php_warning ("Unsupported operand types for operator <= (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return rhs.type == var::OBJECT_TYPE; } return lhs.to_float() <= rhs.to_float(); } bool operator >= (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { if (STRING(lhs.s)[0][0] <= '9' && STRING(rhs.s)[0][0] <= '9') { int lhs_int_val, rhs_int_val; if (STRING(lhs.s)->try_to_int (&lhs_int_val) && STRING(rhs.s)->try_to_int (&rhs_int_val)) { return lhs_int_val >= rhs_int_val; } double lhs_float_val, rhs_float_val; if (STRING(lhs.s)->try_to_float (&lhs_float_val) && STRING(rhs.s)->try_to_float (&rhs_float_val)) { STRING(lhs.s)->warn_on_float_conversion(); STRING(rhs.s)->warn_on_float_conversion(); if (is_ok_float (lhs_float_val) && is_ok_float (rhs_float_val)) { return lhs_float_val >= rhs_float_val; } } } return STRING(lhs.s)->compare (*STRING(rhs.s)) >= 0; } else if (unlikely (rhs.type == var::NULL_TYPE)) { return true; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return STRING(rhs.s)->size() == 0; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() >= rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return ARRAY(lhs.a)->count() >= ARRAY(rhs.a)->count(); } php_warning ("Unsupported operand types for operator >= (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return lhs.type == var::ARRAY_TYPE; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { php_warning ("Unsupported operand types for operator >= (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return lhs.type == var::OBJECT_TYPE; } return lhs.to_float() >= rhs.to_float(); } bool operator < (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { if (STRING(lhs.s)[0][0] <= '9' && STRING(rhs.s)[0][0] <= '9') { int lhs_int_val, rhs_int_val; if (STRING(lhs.s)->try_to_int (&lhs_int_val) && STRING(rhs.s)->try_to_int (&rhs_int_val)) { return lhs_int_val < rhs_int_val; } double lhs_float_val, rhs_float_val; if (STRING(lhs.s)->try_to_float (&lhs_float_val) && STRING(rhs.s)->try_to_float (&rhs_float_val)) { STRING(lhs.s)->warn_on_float_conversion(); STRING(rhs.s)->warn_on_float_conversion(); if (is_ok_float (lhs_float_val) && is_ok_float (rhs_float_val)) { return lhs_float_val < rhs_float_val; } } } return STRING(lhs.s)->compare (*STRING(rhs.s)) < 0; } else if (unlikely (rhs.type == var::NULL_TYPE)) { return false; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return STRING(rhs.s)->size() != 0; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() < rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return ARRAY(lhs.a)->count() < ARRAY(rhs.a)->count(); } php_warning ("Unsupported operand types for operator < (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return lhs.type != var::ARRAY_TYPE; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { php_warning ("Unsupported operand types for operator < (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return lhs.type != var::OBJECT_TYPE; } return lhs.to_float() < rhs.to_float(); } bool operator > (const var &lhs, const var &rhs) { if (unlikely (lhs.type == var::STRING_TYPE)) { if (likely (rhs.type == var::STRING_TYPE)) { if (STRING(lhs.s)[0][0] <= '9' && STRING(rhs.s)[0][0] <= '9') { int lhs_int_val, rhs_int_val; if (STRING(lhs.s)->try_to_int (&lhs_int_val) && STRING(rhs.s)->try_to_int (&rhs_int_val)) { return lhs_int_val > rhs_int_val; } double lhs_float_val, rhs_float_val; if (STRING(lhs.s)->try_to_float (&lhs_float_val) && STRING(rhs.s)->try_to_float (&rhs_float_val)) { STRING(lhs.s)->warn_on_float_conversion(); STRING(rhs.s)->warn_on_float_conversion(); if (is_ok_float (lhs_float_val) && is_ok_float (rhs_float_val)) { return lhs_float_val > rhs_float_val; } } } return STRING(lhs.s)->compare (*STRING(rhs.s)) > 0; } else if (unlikely (rhs.type == var::NULL_TYPE)) { return STRING(lhs.s)->size() != 0; } } else if (unlikely (rhs.type == var::STRING_TYPE)) { if (unlikely (lhs.type == var::NULL_TYPE)) { return false; } } if (lhs.type == var::BOOLEAN_TYPE || rhs.type == var::BOOLEAN_TYPE || lhs.type == var::NULL_TYPE || rhs.type == var::NULL_TYPE) { return lhs.to_bool() > rhs.to_bool(); } if (unlikely (lhs.type == var::ARRAY_TYPE || rhs.type == var::ARRAY_TYPE)) { if (likely (lhs.type == var::ARRAY_TYPE && rhs.type == var::ARRAY_TYPE)) { return ARRAY(lhs.a)->count() > ARRAY(rhs.a)->count(); } php_warning ("Unsupported operand types for operator > (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return rhs.type != var::ARRAY_TYPE; } if (unlikely (lhs.type == var::OBJECT_TYPE || rhs.type == var::OBJECT_TYPE)) { php_warning ("Unsupported operand types for operator > (%s and %s)", lhs.get_type_c_str(), rhs.get_type_c_str()); return rhs.type != var::OBJECT_TYPE; } return lhs.to_float() > rhs.to_float(); } bool equals (const var &lhs, const var &rhs) { if (lhs.type != rhs.type) { return false; } switch (lhs.type) { case var::NULL_TYPE: return true; case var::BOOLEAN_TYPE: return lhs.b == rhs.b; case var::INTEGER_TYPE: return lhs.i == rhs.i; case var::FLOAT_TYPE: return lhs.f == rhs.f; case var::STRING_TYPE: return *STRING(lhs.s) == *STRING(rhs.s); case var::ARRAY_TYPE: return equals (*ARRAY(lhs.a), *ARRAY(rhs.a)); case var::OBJECT_TYPE: return equals (*OBJECT(lhs.o), *OBJECT(rhs.o)); default: php_assert (0); exit (1); } } bool not_equals (const var &lhs, const var &rhs) { return !equals (lhs, rhs); } void swap (var &lhs, var &rhs) { lhs.swap (rhs); } template <class T, class T1> array <T>& safe_set_add (array <T> &lhs, const array <T1> &rhs) { return lhs += rhs; } template <class T> array <T> safe_add (const array <T> &lhs, const array <T> &rhs) { return lhs + rhs; } var& safe_set_add (var &lhs, const var &rhs) { return lhs.safe_set_add (rhs); } var& safe_set_sub (var &lhs, const var &rhs) { return lhs.safe_set_sub (rhs); } var& safe_set_mul (var &lhs, const var &rhs) { return lhs.safe_set_mul (rhs); } var& safe_set_shl (var &lhs, const var &rhs) { return lhs.safe_set_shl (rhs); } int& safe_set_add (int &lhs, int rhs) { return lhs = safe_add (lhs, rhs); } int& safe_set_sub (int &lhs, int rhs) { return lhs = safe_sub (lhs, rhs); } int& safe_set_mul (int &lhs, int rhs) { return lhs = safe_mul (lhs, rhs); } int& safe_set_shl (int &lhs, int rhs) { return lhs = safe_shl (lhs, rhs); } int safe_add (int lhs, int rhs) { long long res = (long long)lhs + rhs; int resi = (int)res; if (resi != res) { php_warning ("Integer overflow in %d + %d", lhs, rhs); } return resi; } int safe_sub (int lhs, int rhs) { long long res = (long long)lhs - rhs; int resi = (int)res; if (resi != res) { php_warning ("Integer overflow in %d - %d", lhs, rhs); } return resi; } int safe_mul (int lhs, int rhs) { long long res = (long long)lhs * rhs; int resi = (int)res; if (resi != res) { php_warning ("Integer overflow in %d * %d", lhs, rhs); } return resi; } int safe_shl (int lhs, int rhs) { if ((unsigned int)rhs >= 32u) { php_warning ("Wrong right parameter %d in << operator", rhs); rhs = 0; } int res = lhs << rhs; if ((res >> rhs) != lhs) { php_warning ("Integer overflow in %d << %d", lhs, rhs); } return res; } double& safe_set_add (double &lhs, double rhs) { return lhs += rhs; } double& safe_set_sub (double &lhs, double rhs) { return lhs -= rhs; } double& safe_set_mul (double &lhs, double rhs) { return lhs *= rhs; } int safe_add (bool lhs, bool rhs) { return lhs + rhs; } int safe_add (bool lhs, int rhs) { return lhs + rhs; } double safe_add (bool lhs, double rhs) { return lhs + rhs; } int safe_add (int lhs, bool rhs) { return lhs + rhs; } double safe_add (int lhs, double rhs) { return lhs + rhs; } double safe_add (double lhs, bool rhs) { return lhs + rhs; } double safe_add (double lhs, int rhs) { return lhs + rhs; } double safe_add (double lhs, double rhs) { return lhs + rhs; } int safe_sub (bool lhs, bool rhs) { return lhs - rhs; } int safe_sub (bool lhs, int rhs) { return lhs - rhs; } double safe_sub (bool lhs, double rhs) { return lhs - rhs; } int safe_sub (int lhs, bool rhs) { return lhs - rhs; } double safe_sub (int lhs, double rhs) { return lhs - rhs; } double safe_sub (double lhs, bool rhs) { return lhs - rhs; } double safe_sub (double lhs, int rhs) { return lhs - rhs; } double safe_sub (double lhs, double rhs) { return lhs - rhs; } int safe_mul (bool lhs, bool rhs) { return lhs * rhs; } int safe_mul (bool lhs, int rhs) { return lhs * rhs; } double safe_mul (bool lhs, double rhs) { return lhs * rhs; } int safe_mul (int lhs, bool rhs) { return lhs * rhs; } double safe_mul (int lhs, double rhs) { return lhs * rhs; } double safe_mul (double lhs, bool rhs) { return lhs * rhs; } double safe_mul (double lhs, int rhs) { return lhs * rhs; } double safe_mul (double lhs, double rhs) { return lhs * rhs; } int& safe_incr_pre (int &lhs) { if (lhs == INT_MAX) { php_warning ("Integer overflow in ++%d", lhs); } return ++lhs; } int& safe_decr_pre (int &lhs) { if (lhs == INT_MIN) { php_warning ("Integer overflow in --%d", lhs); } return --lhs; } int safe_incr_post (int &lhs) { if (lhs == INT_MAX) { php_warning ("Integer overflow in %d++", lhs); } return lhs++; } int safe_decr_post (int &lhs) { if (lhs == INT_MIN) { php_warning ("Integer overflow in %d--", lhs); } return lhs--; } double& safe_incr_pre (double &lhs) { return ++lhs; } double& safe_decr_pre (double &lhs) { return --lhs; } double safe_incr_post (double &lhs) { return lhs++; } double safe_decr_post (double &lhs) { return lhs--; } var& safe_incr_pre (var &lhs) { return lhs.safe_incr_pre(); } var& safe_decr_pre (var &lhs) { return lhs.safe_decr_pre(); } var safe_incr_post (var &lhs) { return lhs.safe_incr_post(); } var safe_decr_post (var &lhs) { return lhs.safe_decr_post(); } bool eq2 (bool lhs, bool rhs) { return lhs == rhs; } bool eq2 (int lhs, int rhs) { return lhs == rhs; } bool eq2 (double lhs, double rhs) { return lhs == rhs; } bool eq2 (bool lhs, int rhs) { return lhs != !rhs; } bool eq2 (bool lhs, double rhs) { return lhs != (rhs == 0.0); } bool eq2 (int lhs, bool rhs) { return rhs != !lhs; } bool eq2 (double lhs, bool rhs) { return rhs != (lhs == 0.0); } bool eq2 (int lhs, double rhs) { return lhs == rhs; } bool eq2 (double lhs, int rhs) { return lhs == rhs; } bool eq2 (bool lhs, const string &rhs) { return lhs == rhs.to_bool(); } bool eq2 (int lhs, const string &rhs) { return lhs == rhs.to_float(); } bool eq2 (double lhs, const string &rhs) { return lhs == rhs.to_float(); } bool eq2 (const string &lhs, bool rhs) { return rhs == lhs.to_bool(); } bool eq2 (const string &lhs, int rhs) { return rhs == lhs.to_float(); } bool eq2 (const string &lhs, double rhs) { return rhs == lhs.to_float(); } template <class T> bool eq2 (bool lhs, const array <T> &rhs) { return lhs == !rhs.empty(); } template <class T> bool eq2 (int lhs, const array <T> &rhs) { php_warning ("Unsupported operand types for operator == (int and array)"); return false; } template <class T> bool eq2 (double lhs, const array <T> &rhs) { php_warning ("Unsupported operand types for operator == (float and array)"); return false; } template <class T> bool eq2 (const string &lhs, const array <T> &rhs) { php_warning ("Unsupported operand types for operator == (string and array)"); return false; } template <class T> bool eq2 (const array <T> &lhs, bool rhs) { return rhs == !lhs.empty(); } template <class T> bool eq2 (const array <T> &lhs, int rhs) { php_warning ("Unsupported operand types for operator == (array and int)"); return false; } template <class T> bool eq2 (const array <T> &lhs, double rhs) { php_warning ("Unsupported operand types for operator == (array and float)"); return false; } template <class T> bool eq2 (const array <T> &lhs, const string &rhs) { php_warning ("Unsupported operand types for operator == (array and string)"); return false; } template <class T> bool eq2 (bool lhs, const object_ptr <T> &rhs) { return lhs; } template <class T> bool eq2 (int lhs, const object_ptr <T> &rhs) { php_warning ("Unsupported operand types for operator == (int and object)"); return false; } template <class T> bool eq2 (double lhs, const object_ptr <T> &rhs) { php_warning ("Unsupported operand types for operator == (float and object)"); return false; } template <class T> bool eq2 (const string &lhs, const object_ptr <T> &rhs) { php_warning ("Unsupported operand types for operator == (string and object)"); return false; } template <class T, class T1> bool eq2 (const array <T1> &lhs, const object_ptr <T> &rhs) { php_warning ("Unsupported operand types for operator == (array and object)"); return false; } template <class T> bool eq2 (const object_ptr <T> &lhs, bool rhs) { return rhs; } template <class T> bool eq2 (const object_ptr <T> &lhs, int rhs) { php_warning ("Unsupported operand types for operator == (object and int)"); return false; } template <class T> bool eq2 (const object_ptr <T> &lhs, double rhs) { php_warning ("Unsupported operand types for operator == (object and float)"); return false; } template <class T> bool eq2 (const object_ptr <T> &lhs, const string &rhs) { php_warning ("Unsupported operand types for operator == (object and string)"); return false; } template <class T, class T1> bool eq2 (const object_ptr <T> &lhs, const array <T1> &rhs) { php_warning ("Unsupported operand types for operator == (object and array)"); return false; } bool eq2 (bool lhs, const var &rhs) { return lhs == rhs.to_bool(); } bool eq2 (int lhs, const var &rhs) { switch (rhs.type) { case var::NULL_TYPE: return lhs == 0; case var::BOOLEAN_TYPE: return !!lhs == rhs.b; case var::INTEGER_TYPE: return lhs == rhs.i; case var::FLOAT_TYPE: return lhs == rhs.f; case var::STRING_TYPE: return lhs == STRING(rhs.s)->to_float(); case var::ARRAY_TYPE: php_warning ("Unsupported operand types for operator == (int and array)"); return false; case var::OBJECT_TYPE: php_warning ("Unsupported operand types for operator == (int and object)"); return false; default: php_assert (0); exit (1); } } bool eq2 (double lhs, const var &rhs) { switch (rhs.type) { case var::NULL_TYPE: return lhs == 0.0; case var::BOOLEAN_TYPE: return (lhs != 0.0) == rhs.b; case var::INTEGER_TYPE: return lhs == rhs.i; case var::FLOAT_TYPE: return lhs == rhs.f; case var::STRING_TYPE: return lhs == STRING(rhs.s)->to_float(); case var::ARRAY_TYPE: php_warning ("Unsupported operand types for operator == (float and array)"); return false; case var::OBJECT_TYPE: php_warning ("Unsupported operand types for operator == (float and object)"); return false; default: php_assert (0); exit (1); } } bool eq2 (const string &lhs, const var &rhs) { return eq2 (var (lhs), rhs); } template <class T> bool eq2 (const array <T> &lhs, const var &rhs) { if (likely (rhs.is_array())) { return eq2 (lhs, *ARRAY(rhs.a)); } if (rhs.is_bool()) { return lhs.empty() != rhs.b; } if (rhs.is_null()) { return lhs.empty(); } php_warning ("Unsupported operand types for operator == (array and %s)", rhs.get_type_c_str()); return false; } template <class T> bool eq2 (const object_ptr <T> &lhs, const var &rhs) { if (likely (rhs.is_object())) { return eq2 (lhs, *OBJECT(rhs.o)); } if (rhs.is_bool()) { return rhs.b; } if (rhs.is_null()) { return false; } php_warning ("Unsupported operand types for operator == (object and %s)", rhs.get_type_c_str()); return false; } bool eq2 (const var &lhs, bool rhs) { return rhs == lhs.to_bool(); } bool eq2 (const var &lhs, int rhs) { switch (lhs.type) { case var::NULL_TYPE: return rhs == 0; case var::BOOLEAN_TYPE: return !!rhs == lhs.b; case var::INTEGER_TYPE: return rhs == lhs.i; case var::FLOAT_TYPE: return rhs == lhs.f; case var::STRING_TYPE: return rhs == STRING(lhs.s)->to_float(); case var::ARRAY_TYPE: php_warning ("Unsupported operand types for operator == (array and int)"); return false; case var::OBJECT_TYPE: php_warning ("Unsupported operand types for operator == (object and int)"); return false; default: php_assert (0); exit (1); } } bool eq2 (const var &lhs, double rhs) { switch (lhs.type) { case var::NULL_TYPE: return rhs == 0.0; case var::BOOLEAN_TYPE: return (rhs != 0.0) == lhs.b; case var::INTEGER_TYPE: return rhs == lhs.i; case var::FLOAT_TYPE: return rhs == lhs.f; case var::STRING_TYPE: return rhs == STRING(lhs.s)->to_float(); case var::ARRAY_TYPE: php_warning ("Unsupported operand types for operator == (array and float)"); return false; case var::OBJECT_TYPE: php_warning ("Unsupported operand types for operator == (object and float)"); return false; default: php_assert (0); exit (1); } } bool eq2 (const var &lhs, const string &rhs) { return eq2 (var (rhs), lhs); } template <class T> bool eq2 (const var &lhs, const array <T> &rhs) { if (likely (lhs.is_array())) { return eq2 (*ARRAY(lhs.a), rhs); } if (lhs.is_bool()) { return rhs.empty() != lhs.b; } if (lhs.is_null()) { return rhs.empty(); } php_warning ("Unsupported operand types for operator == (%s and array)", lhs.get_type_c_str()); return false; } template <class T> bool eq2 (const var &lhs, const object_ptr <T> &rhs) { if (likely (lhs.is_object())) { return eq2 (*OBJECT(lhs.o), rhs); } if (lhs.is_bool()) { return lhs.b; } if (lhs.is_null()) { return false; } php_warning ("Unsupported operand types for operator == (%s and object)", lhs.get_type_c_str()); return false; } template <class T1, class T2> bool neq2 (const T1 &lhs, const T2 &rhs) { return !eq2 (lhs, rhs); } bool equals (bool lhs, const var &rhs) { return rhs.is_bool() && equals (lhs, rhs.b); } bool equals (int lhs, const var &rhs) { return rhs.is_int() && equals (lhs, rhs.i); } bool equals (double lhs, const var &rhs) { return rhs.is_float() && equals (lhs, rhs.f); } bool equals (const string &lhs, const var &rhs) { return rhs.is_string() && equals (lhs, *STRING(rhs.s)); } template <class T> bool equals (const array <T> &lhs, const var &rhs) { return rhs.is_array() && equals (lhs, *ARRAY(rhs.a)); } template <class T> bool equals (const object_ptr <T> &lhs, const var &rhs) { return rhs.is_object() && equals (lhs, *OBJECT(rhs.o)); } bool equals (const var &lhs, bool rhs) { return lhs.is_bool() && equals (rhs, lhs.b); } bool equals (const var &lhs, int rhs) { return lhs.is_int() && equals (rhs, lhs.i); } bool equals (const var &lhs, double rhs) { return lhs.is_float() && equals (rhs, lhs.f); } bool equals (const var &lhs, const string &rhs) { return lhs.is_string() && equals (rhs, *STRING(lhs.s)); } template <class T> bool equals (const var &lhs, const array <T> &rhs) { return lhs.is_array() && equals (rhs, *ARRAY(lhs.a)); } template <class T> bool equals (const var &lhs, const object_ptr <T> &rhs) { return lhs.is_object() && equals (rhs, *OBJECT(lhs.o)); } template <class T> bool equals (const T &lhs, const T &rhs) { return lhs == rhs; } template <class T1, class T2> bool equals (const T1 &lhs, const T2 &rhs) { return false; } template <class T1, class T2> bool not_equals (const T1 &lhs, const T2 &rhs) { return !equals (lhs, rhs); } template <class T> bool eq2 (const var &v, const OrFalse <T> &value) { return likely (value.bool_value) ? eq2 (value.value, v) : eq2 (false, v); } template <class T> bool eq2 (const OrFalse <T> &value, const var &v) { return likely (value.bool_value) ? eq2 (value.value, v) : eq2 (false, v); } template <class T> bool equals (const OrFalse <T> &value, const var &v) { return likely (value.bool_value) ? equals (value.value, v) : equals (false, v); } template <class T> bool equals (const var &v, const OrFalse <T> &value) { return likely (value.bool_value) ? equals (value.value, v) : equals (false, v); } template <class T> bool not_equals (const OrFalse <T> &value, const var &v) { return likely (value.bool_value) ? not_equals (value.value, v) : not_equals (false, v); } template <class T> bool not_equals (const var &v, const OrFalse <T> &value) { return likely (value.bool_value) ? not_equals (value.value, v) : not_equals (false, v); }
83,256
31,681
/* ** Copyright(C) 2017, StepToSky ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** ** 1.Redistributions of source code must retain the above copyright notice, this ** list of conditions and the following disclaimer. ** 2.Redistributions in binary form must reproduce the above copyright notice, ** this list of conditions and the following disclaimer in the documentation ** and / or other materials provided with the distribution. ** 3.Neither the name of StepToSky nor the names of its contributors ** may be used to endorse or promote products derived from this software ** without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ** Contacts: www.steptosky.com */ #include "stsu_data_istream.h" namespace sts_bwc { // backward compatibility /********************************************************************************************************/ ///////////////////////////////////////* Constructors/Destructor *//////////////////////////////////////// /********************************************************************************************************/ DataStreamI::DataStreamI(std::istream & inStream) : mStream(&inStream), mError(DataStreamI::eErrors::ok) {} DataStreamI::DataStreamI() : mStream(nullptr), mError(DataStreamI::eErrors::ok) { } DataStreamI::~DataStreamI() { } /********************************************************************************************************/ //////////////////////////////////////////////* Operators */////////////////////////////////////////////// /********************************************************************************************************/ DataStreamI & DataStreamI::operator>>(char & outVal) { outVal = 0; if (!mStream->read(&outVal, sizeof(char))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(int8_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(int8_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(uint8_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(uint8_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(int16_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(int16_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(uint16_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(uint16_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(int32_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(int32_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(uint32_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(uint32_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(int64_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(int64_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(uint64_t & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(uint64_t))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(bool & outVal) { outVal = 0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(bool))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(float & outVal) { outVal = 0.0f; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(float))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(double & outVal) { outVal = 0.0; if (!mStream->read(reinterpret_cast<char *>(&outVal), sizeof(double))) { outVal = 0; mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(char *& outVal) { uint64_t len = 0; return readBytes(outVal, len); } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(wchar_t *& outVal) { uint64_t len = 0; return readBytes(outVal, len); } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(std::string & outVal) { uint64_t len; char * str; readBytes(str, len); outVal = std::string(str, len); return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::operator>>(std::wstring & outVal) { uint64_t len; char * str; readBytes(str, len); outVal = std::wstring(reinterpret_cast<wchar_t*>(str), len / sizeof(wchar_t)); return *this; } /********************************************************************************************************/ //////////////////////////////////////////////* Functions */////////////////////////////////////////////// /********************************************************************************************************/ DataStreamI & DataStreamI::readBytes(wchar_t *& outVal, uint64_t & outLen) { outVal = nullptr; outLen = 0; uint64_t byteCount; *this >> byteCount; if (byteCount == 0) { mError = eErrors::readZerroBytes; return *this; } uint64_t len = byteCount / sizeof(wchar_t); outVal = new wchar_t[len + 1]; if (!mStream->read(reinterpret_cast<char *>(outVal), byteCount)) { mError = eErrors::readError; delete[] outVal; return *this; } outVal[len] = L'\0'; outLen = byteCount; return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::readBytes(char *& outVal, uint64_t & outLen) { outVal = nullptr; outLen = 0; uint64_t len; *this >> len; if (len == 0) { mError = eErrors::readZerroBytes; return *this; } outVal = new char[len + 1]; if (!mStream->read(outVal, len)) { mError = eErrors::readError; delete[] outVal; return *this; } outVal[len] = '\0'; outLen = len; return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::readRawData(char * outVal, uint64_t inLen) { if (!mStream->read(outVal, inLen)) { mError = eErrors::readError; } return *this; } //------------------------------------------------------------------------- DataStreamI & DataStreamI::skipRawBytes(uint64_t inLen) { if (!mStream->seekg(inLen, mStream->cur)) { mError = eErrors::seekError; } return *this; } /********************************************************************************************************/ ////////////////////////////////////////////////////////////////////////////////////////////////////////// /********************************************************************************************************/ } // namespace sts
9,424
2,821
// Copyright (c) 2018-2019 The Blocknet developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/blocknetquicksend.h> #include <qt/blocknetaddressbook.h> #include <qt/blocknethdiv.h> #include <qt/blockneticonbtn.h> #include <qt/blocknetsendfundsrequest.h> #include <qt/blocknetsendfundsutil.h> #include <qt/addresstablemodel.h> #include <qt/optionsmodel.h> #include <qt/sendcoinsdialog.h> #include <amount.h> #include <base58.h> #include <wallet/coincontrol.h> #include <validation.h> #include <QMessageBox> #include <QKeyEvent> BlocknetQuickSend::BlocknetQuickSend(WalletModel *w, QWidget *parent) : QFrame(parent), walletModel(w), layout(new QVBoxLayout) { // this->setStyleSheet("border: 1px solid red"); this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); this->setLayout(layout); layout->setContentsMargins(BGU::spi(45), BGU::spi(10), BGU::spi(45), BGU::spi(30)); displayUnit = walletModel->getOptionsModel()->getDisplayUnit(); auto displayUnitName = BitcoinUnits::longName(displayUnit); titleLbl = new QLabel(tr("Quick Send")); titleLbl->setObjectName("h4"); auto *subtitleLbl = new QLabel(tr("Who would you like to send funds to?")); subtitleLbl->setObjectName("h2"); auto *addrBox = new QFrame; addrBox->setContentsMargins(QMargins()); auto *addrBoxLayout = new QHBoxLayout; addrBoxLayout->setContentsMargins(QMargins()); addrBox->setLayout(addrBoxLayout); addressTi = new BlocknetLineEdit(BGU::spi(400)); addressTi->setObjectName("address"); addressTi->setPlaceholderText(tr("Enter Scalaris Address...")); addressTi->setFocusPolicy(Qt::FocusPolicy::StrongFocus); addressTi->setValidator(new QRegExpValidator(QRegExp("[a-zA-Z0-9]{33,35}"), this)); auto *addAddressBtn = new BlocknetIconBtn(QString(), ":/redesign/QuickActions/AddressBookIcon.png"); addrBoxLayout->addWidget(addressTi, 0, Qt::AlignTop); addrBoxLayout->addSpacing(BGU::spi(20)); addrBoxLayout->addWidget(addAddressBtn, 0, Qt::AlignTop); auto *amountLbl = new QLabel(tr("How much would you like to send?")); amountLbl->setObjectName("h2"); auto *amountBox = new QFrame; auto *amountBoxLayout = new QHBoxLayout; amountBoxLayout->setContentsMargins(QMargins()); amountBox->setLayout(amountBoxLayout); amountTi = new BlocknetLineEdit; amountTi->setPlaceholderText(tr("Enter Amount...")); amountTi->setValidator(new BlocknetNumberValidator(0, BLOCKNETGUI_FUNDS_MAX, BitcoinUnits::decimals(displayUnit))); amountTi->setMaxLength(BLOCKNETGUI_MAXCHARS); auto *coinLbl = new QLabel(displayUnitName); coinLbl->setObjectName("coin"); coinLbl->setFixedHeight(amountTi->minimumHeight()); amountBoxLayout->addWidget(amountTi, 0, Qt::AlignLeft); amountBoxLayout->addWidget(coinLbl, 0, Qt::AlignLeft); amountBoxLayout->addStretch(1); // address div auto *div1 = new BlocknetHDiv; // grid divs auto *gdiv1 = new BlocknetHDiv; auto *gdiv2 = new BlocknetHDiv; auto *gdiv3 = new BlocknetHDiv; // Display total auto *totalGrid = new QFrame; // totalGrid->setStyleSheet("border: 1px solid red"); totalGrid->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); auto *totalsLayout = new QGridLayout; totalsLayout->setContentsMargins(QMargins()); totalsLayout->setSpacing(BGU::spi(50)); totalsLayout->setVerticalSpacing(0); totalGrid->setLayout(totalsLayout); auto *feeLbl = new QLabel(tr("Transaction Fee")); feeLbl->setObjectName("header"); feeValueLbl = new QLabel; feeValueLbl->setObjectName("standard"); auto *feeCol3 = new QLabel; auto *totalLbl = new QLabel(tr("Total")); totalLbl->setObjectName("header"); totalValueLbl = new QLabel(BitcoinUnits::formatWithUnit(displayUnit, 0)); totalValueLbl->setObjectName("header"); auto *totalCol3 = new QLabel; warningLbl = new QLabel; warningLbl->setObjectName("warning"); // Grid rows and columns (in order of rows and columns) totalsLayout->addWidget(gdiv1, 0, 0, 1, 3, Qt::AlignVCenter); totalsLayout->addWidget(feeLbl, 1, 0, Qt::AlignLeft | Qt::AlignVCenter); totalsLayout->addWidget(feeValueLbl, 1, 1, Qt::AlignLeft | Qt::AlignVCenter); totalsLayout->addWidget(feeCol3, 1, 2 ); totalsLayout->addWidget(gdiv2, 2, 0, 1, 3, Qt::AlignVCenter); totalsLayout->addWidget(totalLbl, 3, 0, Qt::AlignLeft | Qt::AlignVCenter); totalsLayout->addWidget(totalValueLbl, 3, 1, Qt::AlignLeft | Qt::AlignVCenter); totalsLayout->addWidget(totalCol3, 3, 2 ); totalsLayout->addWidget(gdiv3, 4, 0, 1, 3, Qt::AlignVCenter); totalsLayout->addWidget(warningLbl, 5, 0, 1, 3, Qt::AlignLeft); totalsLayout->setColumnStretch(2, 1); // 3rd column totalsLayout->setRowMinimumHeight(0, BGU::spi(15)); // div 1 totalsLayout->setRowMinimumHeight(1, BGU::spi(40)); // fee totalsLayout->setRowMinimumHeight(2, BGU::spi(15)); // div 2 totalsLayout->setRowMinimumHeight(3, BGU::spi(40)); // total totalsLayout->setRowMinimumHeight(4, BGU::spi(15)); // div 3 totalsLayout->setRowMinimumHeight(5, BGU::spi(30)); // warning confirmBtn = new BlocknetFormBtn; confirmBtn->setText(tr("Confirm Payment")); confirmBtn->setFocusPolicy(Qt::TabFocus); cancelBtn = new BlocknetFormBtn; cancelBtn->setObjectName("cancel"); cancelBtn->setText(tr("Cancel")); auto *btnBox = new QFrame; auto *btnBoxLayout = new QHBoxLayout; btnBoxLayout->setContentsMargins(QMargins()); btnBoxLayout->setSpacing(BGU::spi(15)); btnBox->setLayout(btnBoxLayout); btnBoxLayout->addWidget(cancelBtn, 0, Qt::AlignLeft); btnBoxLayout->addWidget(confirmBtn, 0, Qt::AlignLeft); btnBoxLayout->addStretch(1); layout->addWidget(titleLbl, 0, Qt::AlignTop | Qt::AlignLeft); layout->addSpacing(BGU::spi(40)); layout->addWidget(subtitleLbl, 0, Qt::AlignTop); layout->addSpacing(BGU::spi(20)); layout->addWidget(addrBox, 0, Qt::AlignLeft); layout->addSpacing(BGU::spi(10)); layout->addWidget(div1, 0); layout->addSpacing(BGU::spi(20)); layout->addWidget(amountLbl, 0); layout->addSpacing(BGU::spi(20)); layout->addWidget(amountBox, 0); layout->addSpacing(BGU::spi(20)); layout->addWidget(totalGrid, 0); layout->addSpacing(BGU::spi(20)); layout->addWidget(btnBox); layout->addStretch(1); connect(amountTi, &BlocknetLineEdit::textEdited, this, [this](const QString & text) { onAmountChanged(); }); connect(cancelBtn, &BlocknetFormBtn::clicked, this, &BlocknetQuickSend::onCancel); connect(confirmBtn, &BlocknetFormBtn::clicked, this, &BlocknetQuickSend::onSubmit); connect(addAddressBtn, &BlocknetIconBtn::clicked, this, &BlocknetQuickSend::openAddressBook); } bool BlocknetQuickSend::validated() { return walletModel->validateAddress(addressTi->text()) && !amountTi->text().isEmpty() && BlocknetSendFundsModel::stringToInt(amountTi->text(), displayUnit) > 0; } void BlocknetQuickSend::keyPressEvent(QKeyEvent *event) { QWidget::keyPressEvent(event); if (this->isHidden()) return; if (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return) onSubmit(); } bool BlocknetQuickSend::focusNextPrevChild(bool next) { if (next && amountTi->hasFocus()) { amountTi->clearFocus(); this->setFocus(Qt::FocusReason::ActiveWindowFocusReason); return true; } return QFrame::focusNextPrevChild(next); } void BlocknetQuickSend::mouseReleaseEvent(QMouseEvent *event) { QWidget::mouseReleaseEvent(event); if (this->amountTi->hasFocus() && !this->amountTi->rect().contains(event->pos())) { this->amountTi->clearFocus(); this->setFocus(Qt::FocusReason::ActiveWindowFocusReason); } } void BlocknetQuickSend::showEvent(QShowEvent *event) { QWidget::showEvent(event); if (!addressTi->hasFocus() && !amountTi->hasFocus()) addressTi->setFocus(Qt::FocusReason::ActiveWindowFocusReason); connect(walletModel, &WalletModel::encryptionStatusChanged, this, &BlocknetQuickSend::onEncryptionStatus); connect(walletModel->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &BlocknetQuickSend::onDisplayUnit); } void BlocknetQuickSend::hideEvent(QHideEvent *event) { QWidget::hideEvent(event); disconnect(walletModel, &WalletModel::encryptionStatusChanged, this, &BlocknetQuickSend::onEncryptionStatus); disconnect(walletModel->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &BlocknetQuickSend::onDisplayUnit); } void BlocknetQuickSend::addAddress(const QString &address) { addressTi->setText(address); } void BlocknetQuickSend::openAddressBook() { BlocknetAddressBookDialog dlg(walletModel, Qt::WindowSystemMenuHint | Qt::WindowTitleHint); dlg.singleShotMode(); connect(&dlg, &BlocknetAddressBookDialog::send, [this](const QString &address) { addAddress(address); }); dlg.exec(); } void BlocknetQuickSend::onAmountChanged() { BlocknetSendFundsModel model; const auto addrLabel = walletModel->getAddressTableModel()->labelForAddress(addressTi->text()); model.addRecipient(addressTi->text(), BlocknetSendFundsModel::stringToInt(amountTi->text(), displayUnit), addrLabel); CCoinControl cc = model.getCoinControl(walletModel); if (!walletModel->wallet().isLocked()) { // if the wallet is unlocked, calculate exact fees auto status = model.prepareFunds(walletModel, cc); QString feeAmount = BitcoinUnits::formatWithUnit(displayUnit, model.txFees()); feeValueLbl->setText(feeAmount); // Display or clear the warning message according to the wallet status if (status.status != WalletModel::OK) warningLbl->setText(BlocknetSendFundsPage::processSendCoinsReturn(walletModel, status).first); else warningLbl->clear(); } else if (cc.HasSelected()) { // estimate b/c wallet is locked here const auto feeInfo = BlocknetEstimateFee(walletModel, cc, model.subtractFee(), model.txRecipients()); QString feeAmount = BitcoinUnits::formatWithUnit(displayUnit, std::get<0>(feeInfo)); feeValueLbl->setText(QString("%1 %2").arg(feeAmount, tr("(estimated)"))); model.setEstimatedFees(std::get<0>(feeInfo)); } else { // estimate b/c wallet is locked here cc.m_feerate.reset(); // explicitly use only fee estimation rate for smart fee labels int estimatedConfirmations; FeeReason reason; CFeeRate feeRate = CFeeRate(walletModel->wallet().getMinimumFee(1000, cc, &estimatedConfirmations, &reason)); QString feeAmount = BitcoinUnits::formatWithUnit(displayUnit, feeRate.GetFeePerK()) + "/kB"; feeValueLbl->setText(QString("%1 %2").arg(feeAmount, tr("(estimated)"))); model.setEstimatedFees(feeRate.GetFeePerK()); } CAmount fees = walletModel->wallet().isLocked() ? model.estimatedFees() : model.txFees(); if (model.subtractFee()) fees *= -1; totalValueLbl->setText(BitcoinUnits::formatWithUnit(displayUnit, (walletModel->wallet().isLocked() ? fees : 0) + model.txTotalAmount())); } void BlocknetQuickSend::onSubmit() { if (!this->validated()) { QMessageBox::warning(this->parentWidget(), tr("Issue"), tr("Please specify a send address and an amount larger than %1") .arg(BitcoinUnits::formatWithUnit(displayUnit, ::minRelayTxFee.GetFeePerK()))); return; } // Unlock wallet context (for relock) WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus(); if (encStatus == WalletModel::EncryptionStatus::Locked || util::unlockedForStakingOnly) { const bool stateUnlockForStaking = util::unlockedForStakingOnly; WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if (!ctx.isValid() || util::unlockedForStakingOnly) { QMessageBox::warning(this->parentWidget(), tr("Issue"), tr("Failed to unlock the wallet")); } else { submitFunds(); util::unlockedForStakingOnly = stateUnlockForStaking; // restore unlocked for staking state } return; } submitFunds(); } WalletModel::SendCoinsReturn BlocknetQuickSend::submitFunds() { QList<SendCoinsRecipient> recipients; const auto addrLabel = walletModel->getAddressTableModel()->labelForAddress(addressTi->text()); recipients.push_back(SendCoinsRecipient{ addressTi->text(), addrLabel, BlocknetSendFundsModel::stringToInt(amountTi->text(), displayUnit), QString() }); WalletModelTransaction currentTransaction(recipients); CCoinControl ctrl; WalletModel::SendCoinsReturn prepareStatus = walletModel->prepareTransaction(currentTransaction, ctrl); const auto feeMsg = BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()); if (prepareStatus.status != WalletModel::OK) { // process prepareStatus and on error generate message shown to user auto res = BlocknetSendFundsPage::processSendCoinsReturn(walletModel, prepareStatus, feeMsg); updateLabels(prepareStatus); if (res.second) QMessageBox::critical(this->parentWidget(), tr("Issue"), res.first); else QMessageBox::warning(this->parentWidget(), tr("Issue"), res.first); return prepareStatus; } const auto txFee = currentTransaction.getTransactionFee(); const auto totalAmt = currentTransaction.getTotalTransactionAmount() + txFee; // Update labels feeValueLbl->setText(BitcoinUnits::formatWithUnit(displayUnit, txFee)); totalValueLbl->setText(BitcoinUnits::formatWithUnit(displayUnit, totalAmt)); // Format confirmation message QStringList formatted; QString questionString = tr("Are you sure you want to send?"); questionString.append("<br /><span style='font-size:10pt;'>"); questionString.append(tr("Please, review your transaction.")); questionString.append("</span><br />%1"); if (txFee > 0) { // append fee string if a fee is required questionString.append("<hr /><b>"); questionString.append(tr("Transaction fee")); questionString.append("</b>"); // append transaction size questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB): "); // append transaction fee value questionString.append("<span style='color:#aa0000; font-weight:bold;'>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(displayUnit, txFee)); questionString.append("</span><br />"); } // add total amount in all subdivision units questionString.append("<hr />"); questionString.append(QString("<b>%1</b>: <b>%2</b>").arg(tr("Total Amount")) .arg(BitcoinUnits::formatHtmlWithUnit(displayUnit, totalAmt))); SendConfirmationDialog confirmationDialog(tr("Confirm send coins"), questionString.arg(formatted.join("<br />")), SEND_CONFIRM_DELAY, this); confirmationDialog.exec(); WalletModel::SendCoinsReturn sendStatus(WalletModel::StatusCode::TransactionCommitFailed); bool canceledSend{false}; auto retval = static_cast<QMessageBox::StandardButton>(confirmationDialog.result()); if (retval == QMessageBox::Yes) { // now send the prepared transaction sendStatus = walletModel->sendCoins(currentTransaction); // process sendStatus and on error generate message shown to user auto res = BlocknetSendFundsPage::processSendCoinsReturn(walletModel, sendStatus, feeMsg); if (sendStatus.status == WalletModel::OK) Q_EMIT submit(); else { updateLabels(sendStatus); if (res.second) QMessageBox::critical(this->parentWidget(), tr("Issue"), res.first); else QMessageBox::warning(this->parentWidget(), tr("Issue"), res.first); } } else canceledSend = true; // Display warning message if necessary if (!canceledSend && sendStatus.status != WalletModel::OK && warningLbl) warningLbl->setText(BlocknetSendFundsRequest::sendStatusMsg(sendStatus, "", displayUnit)); return sendStatus; } void BlocknetQuickSend::onEncryptionStatus() { if (walletModel->getEncryptionStatus() == WalletModel::Unlocked && !addressTi->text().isEmpty()) onAmountChanged(); } void BlocknetQuickSend::onDisplayUnit(int unit) { displayUnit = unit; amountTi->setValidator(new BlocknetNumberValidator(0, BLOCKNETGUI_FUNDS_MAX, BitcoinUnits::decimals(displayUnit))); onAmountChanged(); } void BlocknetQuickSend::updateLabels(const WalletModel::SendCoinsReturn & result) { // Handle errors if (result.status != WalletModel::OK) warningLbl->setText(BlocknetSendFundsRequest::sendStatusMsg(result, "", displayUnit)); else warningLbl->clear(); feeValueLbl->setText(QString("%1 %2").arg(BitcoinUnits::formatWithUnit(displayUnit, txFees), tr("(estimated)"))); totalValueLbl->setText(BitcoinUnits::formatWithUnit(displayUnit, totalAmount)); }
17,638
5,674
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../config.h" #include "fzxx/match.h" #include "fzxx/tty_interface.h" static int isprint_unicode(char c) { return isprint(c) || c & (1 << 7); } static int is_boundary(char c) { return ~c & (1 << 7) || c & (1 << 6); } static void clear(tty_interface_t *state) { TTYWrapper *tty = state->tty; tty->setcol(0); size_t line = 0; while (line++ < state->options->num_lines) { tty->newline(); } tty->clearline(); if (state->options->num_lines > 0) { tty->moveup(line - 1); } tty->flush(); } static void draw_match(tty_interface_t *state, const char *choice, int selected) { TTYWrapper *tty = state->tty; options_t *options = state->options; char *search = state->last_search; int n = strlen(search); size_t positions[n + 1]; for (int i = 0; i < n + 1; i++) positions[i] = -1; score_t score = match_positions(search, choice, &positions[0]); if (options->show_scores) { if (score == SCORE_MIN) { tty->printf("( ) "); } else { tty->printf("(%5.2f) ", score); } } if (selected) #ifdef TTY_SELECTION_UNDERLINE tty->setunderline(); #else tty->setinvert(); #endif tty->setnowrap(); for (size_t i = 0, p = 0; choice[i] != '\0'; i++) { if (positions[p] == i) { tty->setfg(TTY_COLOR_HIGHLIGHT); p++; } else { tty->setfg(TTY_COLOR_NORMAL); } tty->printf("%c", choice[i]); } tty->setwrap(); tty->setnormal(); } static void draw(tty_interface_t *state) { TTYWrapper *tty = state->tty; choices_t *choices = state->choices; options_t *options = state->options; unsigned int num_lines = options->num_lines; size_t start = 0; size_t current_selection = choices->selection; if (current_selection + options->scrolloff >= num_lines) { start = current_selection + options->scrolloff - num_lines + 1; size_t available = choices_available(choices); if (start + num_lines >= available && available > 0) { start = available - num_lines; } } tty->setcol(0); tty->printf("%s%s", options->prompt, state->search); tty->clearline(); for (size_t i = start; i < start + num_lines; i++) { tty->printf("\n"); tty->clearline(); const char *choice = choices_get(choices, i); if (choice) { draw_match(state, choice, i == choices->selection); } } if (num_lines > 0) { tty->moveup(num_lines); } tty->setcol(0); fputs(options->prompt, tty->fout); for (size_t i = 0; i < state->cursor; i++) fputc(state->search[i], tty->fout); tty->flush(); } static void update_search(tty_interface_t *state) { choices_search(state->choices, state->search); strcpy(state->last_search, state->search); } static void update_state(tty_interface_t *state) { if (strcmp(state->last_search, state->search)) { update_search(state); draw(state); } } static void action_emit(tty_interface_t *state) { update_state(state); /* Reset the tty as close as possible to the previous state */ clear(state); /* ttyout should be flushed before outputting on stdout */ state->tty->close(); const char *selection = choices_get(state->choices, state->choices->selection); if (selection) { /* output the selected result */ printf("%s\n", selection); } else { /* No match, output the query instead */ printf("%s\n", state->search); } state->exit = EXIT_SUCCESS; } static void action_del_char(tty_interface_t *state) { if (*state->search) { size_t length = strlen(state->search); if (state->cursor == 0) { return; } size_t original_cursor = state->cursor; state->cursor--; while (!is_boundary(state->search[state->cursor]) && state->cursor) state->cursor--; memmove(&state->search[state->cursor], &state->search[original_cursor], length - original_cursor + 1); } } static void action_del_word(tty_interface_t *state) { size_t original_cursor = state->cursor; size_t cursor = state->cursor; while (cursor && isspace(state->search[cursor - 1])) cursor--; while (cursor && !isspace(state->search[cursor - 1])) cursor--; memmove(&state->search[cursor], &state->search[original_cursor], strlen(state->search) - original_cursor + 1); state->cursor = cursor; } static void action_del_all(tty_interface_t *state) { memmove(state->search, &state->search[state->cursor], strlen(state->search) - state->cursor + 1); state->cursor = 0; } static void action_prev(tty_interface_t *state) { update_state(state); choices_prev(state->choices); } static void action_ignore(tty_interface_t *state) { (void)state; } static void action_next(tty_interface_t *state) { update_state(state); choices_next(state->choices); } static void action_left(tty_interface_t *state) { if (state->cursor > 0) { state->cursor--; while (!is_boundary(state->search[state->cursor]) && state->cursor) state->cursor--; } } static void action_right(tty_interface_t *state) { if (state->cursor < strlen(state->search)) { state->cursor++; while (!is_boundary(state->search[state->cursor])) state->cursor++; } } static void action_beginning(tty_interface_t *state) { state->cursor = 0; } static void action_end(tty_interface_t *state) { state->cursor = strlen(state->search); } static void action_pageup(tty_interface_t *state) { update_state(state); for (size_t i = 0; i < state->options->num_lines && state->choices->selection > 0; i++) choices_prev(state->choices); } static void action_pagedown(tty_interface_t *state) { update_state(state); for (size_t i = 0; i < state->options->num_lines && state->choices->selection < state->choices->available - 1; i++) choices_next(state->choices); } static void action_autocomplete(tty_interface_t *state) { update_state(state); const char *current_selection = choices_get(state->choices, state->choices->selection); if (current_selection) { strncpy(state->search, choices_get(state->choices, state->choices->selection), SEARCH_SIZE_MAX); state->cursor = strlen(state->search); } } static void action_exit(tty_interface_t *state) { clear(state); state->tty->close(); state->exit = EXIT_FAILURE; } static void append_search(tty_interface_t *state, char ch) { char *search = state->search; size_t search_size = strlen(search); if (search_size < SEARCH_SIZE_MAX) { memmove(&search[state->cursor + 1], &search[state->cursor], search_size - state->cursor + 1); search[state->cursor] = ch; state->cursor++; } } void tty_interface_init(tty_interface_t *state, TTYWrapper *tty, choices_t *choices, options_t *options) { state->tty = tty; state->choices = choices; state->options = options; state->ambiguous_key_pending = 0; strcpy(state->input, ""); strcpy(state->search, ""); strcpy(state->last_search, ""); state->exit = -1; if (options->init_search) strncpy(state->search, options->init_search, SEARCH_SIZE_MAX); state->cursor = strlen(state->search); update_search(state); } typedef struct { const char *key; void (*action)(tty_interface_t *); } keybinding_t; #define KEY_CTRL(key) ((const char[]){((key) - ('@')), '\0'}) static const keybinding_t keybindings[] = { {"\x1b", action_exit}, /* ESC */ {"\x7f", action_del_char}, /* DEL */ {KEY_CTRL('H'), action_del_char}, /* Backspace (C-H) */ {KEY_CTRL('W'), action_del_word}, /* C-W */ {KEY_CTRL('U'), action_del_all}, /* C-U */ {KEY_CTRL('I'), action_autocomplete}, /* TAB (C-I ) */ {KEY_CTRL('C'), action_exit}, /* C-C */ {KEY_CTRL('D'), action_exit}, /* C-D */ {KEY_CTRL('M'), action_emit}, /* CR */ {KEY_CTRL('P'), action_prev}, /* C-P */ {KEY_CTRL('N'), action_next}, /* C-N */ {KEY_CTRL('K'), action_prev}, /* C-K */ {KEY_CTRL('J'), action_next}, /* C-J */ {KEY_CTRL('A'), action_beginning}, /* C-A */ {KEY_CTRL('E'), action_end}, /* C-E */ {"\x1bOD", action_left}, /* LEFT */ {"\x1b[D", action_left}, /* LEFT */ {"\x1bOC", action_right}, /* RIGHT */ {"\x1b[C", action_right}, /* RIGHT */ {"\x1b[1~", action_beginning}, /* HOME */ {"\x1b[H", action_beginning}, /* HOME */ {"\x1b[4~", action_end}, /* END */ {"\x1b[F", action_end}, /* END */ {"\x1b[A", action_prev}, /* UP */ {"\x1bOA", action_prev}, /* UP */ {"\x1b[B", action_next}, /* DOWN */ {"\x1bOB", action_next}, /* DOWN */ {"\x1b[5~", action_pageup}, {"\x1b[6~", action_pagedown}, {"\x1b[200~", action_ignore}, {"\x1b[201~", action_ignore}, {NULL, NULL}}; #undef KEY_CTRL static void handle_input(tty_interface_t *state, const char *s, int handle_ambiguous_key) { state->ambiguous_key_pending = 0; char *input = state->input; strcat(state->input, s); /* Figure out if we have completed a keybinding and whether we're in the * middle of one (both can happen, because of Esc). */ int found_keybinding = -1; int in_middle = 0; for (int i = 0; keybindings[i].key; i++) { if (!strcmp(input, keybindings[i].key)) found_keybinding = i; else if (!strncmp(input, keybindings[i].key, strlen(state->input))) in_middle = 1; } /* If we have an unambiguous keybinding, run it. */ if (found_keybinding != -1 && (!in_middle || handle_ambiguous_key)) { keybindings[found_keybinding].action(state); strcpy(input, ""); return; } /* We could have a complete keybinding, or could be in the middle of one. * We'll need to wait a few milliseconds to find out. */ if (found_keybinding != -1 && in_middle) { state->ambiguous_key_pending = 1; return; } /* Wait for more if we are in the middle of a keybinding */ if (in_middle) return; /* No matching keybinding, add to search */ for (int i = 0; input[i]; i++) if (isprint_unicode(input[i])) append_search(state, input[i]); /* We have processed the input, so clear it */ strcpy(input, ""); } int tty_interface_run(tty_interface_t *state) { draw(state); for (;;) { do { char s[2] = {state->tty->getchar(), '\0'}; handle_input(state, s, 0); if (state->exit >= 0) return state->exit; draw(state); } while (state->tty->input_ready(state->ambiguous_key_pending)); if (state->ambiguous_key_pending) { char s[1] = ""; handle_input(state, s, 1); if (state->exit >= 0) return state->exit; } update_state(state); } return state->exit; }
10,851
3,969
#include "storage/data_table.h" #include <pthread.h> #include <cstring> #include <list> #include <unordered_map> #include "common/allocator.h" #include "storage/block_access_controller.h" #include "storage/storage_util.h" #include "transaction/transaction_context.h" #include "transaction/transaction_util.h" namespace terrier::storage { DataTable::DataTable(BlockStore *const store, const BlockLayout &layout, const layout_version_t layout_version) : block_store_(store), layout_version_(layout_version), accessor_(layout) { TERRIER_ASSERT(layout.AttrSize(VERSION_POINTER_COLUMN_ID) == 8, "First column must have size 8 for the version chain."); TERRIER_ASSERT(layout.NumColumns() > NUM_RESERVED_COLUMNS, "First column is reserved for version info, second column is reserved for logical delete."); if (block_store_ != nullptr) { RawBlock *new_block = NewBlock(); // insert block blocks_.push_back(new_block); } insertion_head_ = blocks_.begin(); } DataTable::~DataTable() { common::SpinLatch::ScopedSpinLatch guard(&blocks_latch_); for (RawBlock *block : blocks_) { StorageUtil::DeallocateVarlens(block, accessor_); for (col_id_t i : accessor_.GetBlockLayout().Varlens()) accessor_.GetArrowBlockMetadata(block).GetColumnInfo(accessor_.GetBlockLayout(), i).Deallocate(); block_store_->Release(block); } } bool DataTable::Select(terrier::transaction::TransactionContext *txn, terrier::storage::TupleSlot slot, terrier::storage::ProjectedRow *out_buffer) const { data_table_counter_.IncrementNumSelect(1); return SelectIntoBuffer(txn, slot, out_buffer); } void DataTable::Scan(transaction::TransactionContext *const txn, SlotIterator *const start_pos, ProjectedColumns *const out_buffer) const { // TODO(Tianyu): So far this is not that much better than tuple-at-a-time access, // but can be improved if block is read-only, or if we implement version synopsis, to just use std::memcpy when it's // safe uint32_t filled = 0; while (filled < out_buffer->MaxTuples() && *start_pos != end()) { ProjectedColumns::RowView row = out_buffer->InterpretAsRow(filled); const TupleSlot slot = **start_pos; // Only fill the buffer with valid, visible tuples if (SelectIntoBuffer(txn, slot, &row)) { out_buffer->TupleSlots()[filled] = slot; filled++; } ++(*start_pos); } out_buffer->SetNumTuples(filled); } DataTable::SlotIterator &DataTable::SlotIterator::operator++() { common::SpinLatch::ScopedSpinLatch guard(&table_->blocks_latch_); // Jump to the next block if already the last slot in the block. if (current_slot_.GetOffset() == table_->accessor_.GetBlockLayout().NumSlots() - 1) { ++block_; // Cannot dereference if the next block is end(), so just use nullptr to denote current_slot_ = {block_ == table_->blocks_.end() ? nullptr : *block_, 0}; } else { current_slot_ = {*block_, current_slot_.GetOffset() + 1}; } return *this; } DataTable::SlotIterator DataTable::end() const { // NOLINT for STL name compability common::SpinLatch::ScopedSpinLatch guard(&blocks_latch_); // TODO(Tianyu): Need to look in detail at how this interacts with compaction when that gets in. // The end iterator could either point to an unfilled slot in a block, or point to nothing if every block in the // table is full. In the case that it points to nothing, we will use the end-iterator of the blocks list and // 0 to denote that this is the case. This solution makes increment logic simple and natural. if (blocks_.empty()) return {this, blocks_.end(), 0}; auto last_block = --blocks_.end(); uint32_t insert_head = (*last_block)->GetInsertHead(); // Last block is full, return the default end iterator that doesn't point to anything if (insert_head == accessor_.GetBlockLayout().NumSlots()) return {this, blocks_.end(), 0}; // Otherwise, insert head points to the slot that will be inserted next, which would be exactly what we want. return {this, last_block, insert_head}; } bool DataTable::Update(transaction::TransactionContext *const txn, const TupleSlot slot, const ProjectedRow &redo) { TERRIER_ASSERT(redo.NumColumns() <= accessor_.GetBlockLayout().NumColumns() - NUM_RESERVED_COLUMNS, "The input buffer cannot change the reserved columns, so it should have fewer attributes."); TERRIER_ASSERT(redo.NumColumns() > 0, "The input buffer should modify at least one attribute."); UndoRecord *const undo = txn->UndoRecordForUpdate(this, slot, redo); slot.GetBlock()->controller_.WaitUntilHot(); UndoRecord *version_ptr; do { version_ptr = AtomicallyReadVersionPtr(slot, accessor_); // Since we disallow write-write conflicts, the version vector pointer is essentially an implicit // write lock on the tuple. if (HasConflict(*txn, version_ptr) || !Visible(slot, accessor_)) { // Mark this UndoRecord as never installed by setting the table pointer to nullptr. This is inspected in the // TransactionManager's Rollback() and GC's Unlink logic undo->Table() = nullptr; return false; } // Store before-image before making any changes or grabbing lock for (uint16_t i = 0; i < undo->Delta()->NumColumns(); i++) StorageUtil::CopyAttrIntoProjection(accessor_, slot, undo->Delta(), i); // Update the next pointer of the new head of the version chain undo->Next() = version_ptr; } while (!CompareAndSwapVersionPtr(slot, accessor_, version_ptr, undo)); // Update in place with the new value. for (uint16_t i = 0; i < redo.NumColumns(); i++) { TERRIER_ASSERT(redo.ColumnIds()[i] != VERSION_POINTER_COLUMN_ID, "Input buffer should not change the version pointer column."); // TODO(Matt): It would be nice to check that a ProjectedRow that modifies the logical delete column only originated // from the DataTable calling Update() within Delete(), rather than an outside soure modifying this column, but // that's difficult with this implementation StorageUtil::CopyAttrFromProjection(accessor_, slot, redo, i); } data_table_counter_.IncrementNumUpdate(1); return true; } void DataTable::CheckMoveHead(std::list<RawBlock *>::iterator block) { // Assume block is full common::SpinLatch::ScopedSpinLatch guard_head(&header_latch_); if (block == insertion_head_) { // If the header block is full, move the header to point to the next block insertion_head_++; } // If there are no more free blocks, create a new empty block and point the insertion_head to it if (insertion_head_ == blocks_.end()) { RawBlock *new_block = NewBlock(); // take latch common::SpinLatch::ScopedSpinLatch guard_block(&blocks_latch_); // insert block blocks_.push_back(new_block); // set insertion header to --end() insertion_head_ = --blocks_.end(); } } TupleSlot DataTable::Insert(transaction::TransactionContext *const txn, const ProjectedRow &redo) { TERRIER_ASSERT(redo.NumColumns() == accessor_.GetBlockLayout().NumColumns() - NUM_RESERVED_COLUMNS, "The input buffer never changes the version pointer column, so it should have exactly 1 fewer " "attribute than the DataTable's layout."); // Insertion header points to the first block that has free tuple slots // Once a txn arrives, it will start from the insertion header to find the first // idle (no other txn is trying to get tuple slots in that block) and non-full block. // If no such block is found, the txn will create a new block. // Before the txn writes to the block, it will set block status to busy. // The first bit of block insert_head_ is used to indicate if the block is busy // If the first bit is 1, it indicates one txn is writing to the block. TupleSlot result; auto block = insertion_head_; while (true) { // No free block left if (block == blocks_.end()) { RawBlock *new_block = NewBlock(); TERRIER_ASSERT(accessor_.SetBlockBusyStatus(new_block), "Status of new block should not be busy"); // No need to flip the busy status bit accessor_.Allocate(new_block, &result); // take latch common::SpinLatch::ScopedSpinLatch guard(&blocks_latch_); // insert block blocks_.push_back(new_block); block = --blocks_.end(); break; } if (accessor_.SetBlockBusyStatus(*block)) { // No one is inserting into this block if (accessor_.Allocate(*block, &result)) { // The block is not full, succeed break; } // Fail to insert into the block, flip back the status bit accessor_.ClearBlockBusyStatus(*block); // if the full block is the insertion_header, move the insertion_header // Next insert txn will search from the new insertion_header CheckMoveHead(block); } // The block is full or the block is being inserted by other txn, try next block ++block; } // Do not need to wait unit finish inserting, // can flip back the status bit once the thread gets the allocated tuple slot accessor_.ClearBlockBusyStatus(*block); InsertInto(txn, redo, result); data_table_counter_.IncrementNumInsert(1); return result; } void DataTable::InsertInto(transaction::TransactionContext *txn, const ProjectedRow &redo, TupleSlot dest) { TERRIER_ASSERT(accessor_.Allocated(dest), "destination slot must already be allocated"); TERRIER_ASSERT(accessor_.IsNull(dest, VERSION_POINTER_COLUMN_ID), "The slot needs to be logically deleted to every running transaction"); // At this point, sequential scan down the block can still see this, except it thinks it is logically deleted if we 0 // the primary key column UndoRecord *undo = txn->UndoRecordForInsert(this, dest); TERRIER_ASSERT(dest.GetBlock()->controller_.GetBlockState()->load() == BlockState::HOT, "Should only be able to insert into hot blocks"); AtomicallyWriteVersionPtr(dest, accessor_, undo); // Set the logically deleted bit to present as the undo record is ready accessor_.AccessForceNotNull(dest, VERSION_POINTER_COLUMN_ID); // Update in place with the new value. for (uint16_t i = 0; i < redo.NumColumns(); i++) { TERRIER_ASSERT(redo.ColumnIds()[i] != VERSION_POINTER_COLUMN_ID, "Insert buffer should not change the version pointer column."); StorageUtil::CopyAttrFromProjection(accessor_, dest, redo, i); } } bool DataTable::Delete(transaction::TransactionContext *const txn, const TupleSlot slot) { data_table_counter_.IncrementNumDelete(1); UndoRecord *const undo = txn->UndoRecordForDelete(this, slot); slot.GetBlock()->controller_.WaitUntilHot(); UndoRecord *version_ptr; do { version_ptr = AtomicallyReadVersionPtr(slot, accessor_); // Since we disallow write-write conflicts, the version vector pointer is essentially an implicit // write lock on the tuple. if (HasConflict(*txn, version_ptr) || !Visible(slot, accessor_)) { // Mark this UndoRecord as never installed by setting the table pointer to nullptr. This is inspected in the // TransactionManager's Rollback() and GC's Unlink logic undo->Table() = nullptr; return false; } // Update the next pointer of the new head of the version chain undo->Next() = version_ptr; } while (!CompareAndSwapVersionPtr(slot, accessor_, version_ptr, undo)); // We have the write lock. Go ahead and flip the logically deleted bit to true accessor_.SetNull(slot, VERSION_POINTER_COLUMN_ID); return true; } template <class RowType> bool DataTable::SelectIntoBuffer(transaction::TransactionContext *const txn, const TupleSlot slot, RowType *const out_buffer) const { TERRIER_ASSERT(out_buffer->NumColumns() <= accessor_.GetBlockLayout().NumColumns() - NUM_RESERVED_COLUMNS, "The output buffer never returns the version pointer columns, so it should have " "fewer attributes."); TERRIER_ASSERT(out_buffer->NumColumns() > 0, "The output buffer should return at least one attribute."); // This cannot be visible if it's already deallocated. if (!accessor_.Allocated(slot)) return false; UndoRecord *version_ptr; bool visible; do { version_ptr = AtomicallyReadVersionPtr(slot, accessor_); // Copy the current (most recent) tuple into the output buffer. These operations don't need to be atomic, // because so long as we set the version ptr before updating in place, the reader will know if a conflict // can potentially happen, and chase the version chain before returning anyway, for (uint16_t i = 0; i < out_buffer->NumColumns(); i++) { TERRIER_ASSERT(out_buffer->ColumnIds()[i] != VERSION_POINTER_COLUMN_ID, "Output buffer should not read the version pointer column."); StorageUtil::CopyAttrIntoProjection(accessor_, slot, out_buffer, i); } // We still need to check the allocated bit because GC could have flipped it since last check visible = Visible(slot, accessor_); // Here we will need to check that the version pointer did not change during our read. If it did, the content // we have read might have been rolled back and an abort has already unlinked the associated undo-record, // we will have to loop around to avoid a dirty read. // // There is still an a-b-a problem if aborting transactions unlink themselves. Thus, in the system aborting // transactions still check out a timestamp and "commit" after rolling back their changes to guard against this, // The exact interleaving is this: // // transaction 1 transaction 2 // begin // read version_ptr // begin // write a -> a1 // read a1 // rollback a1 -> a // check version_ptr // return a1 // // For this to manifest, there has to be high contention on a given tuple slot, and insufficient CPU resources // (way more threads than there are cores, around 8x seems to work) such that threads are frequently swapped // out. compare-and-swap along with the pointer reduces the probability of this happening to be essentially // infinitesimal, but it's still a probabilistic fix. To 100% prevent this race, we have to wait until no // concurrent transaction with the abort that could have had a dirty read is alive to unlink this. The easiest // way to achieve that is to take a timestamp as well when all changes have been rolled back for an aborted // transaction, and let GC handle the unlinking. } while (version_ptr != AtomicallyReadVersionPtr(slot, accessor_)); // Nullptr in version chain means no other versions visible to any transaction alive at this point. // Alternatively, if the current transaction holds the write lock, it should be able to read its own updates. if (version_ptr == nullptr || version_ptr->Timestamp().load() == txn->FinishTime()) { return visible; } // Apply deltas until we reconstruct a version safe for us to read while (version_ptr != nullptr && transaction::TransactionUtil::NewerThan(version_ptr->Timestamp().load(), txn->StartTime())) { switch (version_ptr->Type()) { case DeltaRecordType::UPDATE: // Normal delta to be applied. Does not modify the logical delete column. StorageUtil::ApplyDelta(accessor_.GetBlockLayout(), *(version_ptr->Delta()), out_buffer); break; case DeltaRecordType::INSERT: visible = false; break; case DeltaRecordType::DELETE: visible = true; break; default: throw std::runtime_error("unexpected delta record type"); } version_ptr = version_ptr->Next(); } return visible; } template bool DataTable::SelectIntoBuffer<ProjectedRow>(transaction::TransactionContext *txn, const TupleSlot slot, ProjectedRow *const out_buffer) const; template bool DataTable::SelectIntoBuffer<ProjectedColumns::RowView>(transaction::TransactionContext *txn, const TupleSlot slot, ProjectedColumns::RowView *const out_buffer) const; UndoRecord *DataTable::AtomicallyReadVersionPtr(const TupleSlot slot, const TupleAccessStrategy &accessor) const { // Okay to ignore presence bit, because we use that for logical delete, not for validity of the version pointer value byte *ptr_location = accessor.AccessWithoutNullCheck(slot, VERSION_POINTER_COLUMN_ID); return reinterpret_cast<std::atomic<UndoRecord *> *>(ptr_location)->load(); } void DataTable::AtomicallyWriteVersionPtr(const TupleSlot slot, const TupleAccessStrategy &accessor, UndoRecord *const desired) { // Okay to ignore presence bit, because we use that for logical delete, not for validity of the version pointer value byte *ptr_location = accessor.AccessWithoutNullCheck(slot, VERSION_POINTER_COLUMN_ID); reinterpret_cast<std::atomic<UndoRecord *> *>(ptr_location)->store(desired); } bool DataTable::Visible(const TupleSlot slot, const TupleAccessStrategy &accessor) const { const bool present = accessor.Allocated(slot); const bool not_deleted = !accessor.IsNull(slot, VERSION_POINTER_COLUMN_ID); return present && not_deleted; } bool DataTable::HasConflict(const transaction::TransactionContext &txn, UndoRecord *const version_ptr) const { if (version_ptr == nullptr) return false; // Nobody owns this tuple's write lock, no older version visible const transaction::timestamp_t version_timestamp = version_ptr->Timestamp().load(); const transaction::timestamp_t txn_id = txn.FinishTime(); const transaction::timestamp_t start_time = txn.StartTime(); const bool owned_by_other_txn = (!transaction::TransactionUtil::Committed(version_timestamp) && version_timestamp != txn_id); const bool newer_committed_version = transaction::TransactionUtil::Committed(version_timestamp) && transaction::TransactionUtil::NewerThan(version_timestamp, start_time); return owned_by_other_txn || newer_committed_version; } bool DataTable::CompareAndSwapVersionPtr(const TupleSlot slot, const TupleAccessStrategy &accessor, UndoRecord *expected, UndoRecord *const desired) { // Okay to ignore presence bit, because we use that for logical delete, not for validity of the version pointer value byte *ptr_location = accessor.AccessWithoutNullCheck(slot, VERSION_POINTER_COLUMN_ID); return reinterpret_cast<std::atomic<UndoRecord *> *>(ptr_location)->compare_exchange_strong(expected, desired); } RawBlock *DataTable::NewBlock() { RawBlock *new_block = block_store_->Get(); accessor_.InitializeRawBlock(this, new_block, layout_version_); data_table_counter_.IncrementNumNewBlock(1); return new_block; } bool DataTable::HasConflict(const transaction::TransactionContext &txn, const TupleSlot slot) const { UndoRecord *const version_ptr = AtomicallyReadVersionPtr(slot, accessor_); return HasConflict(txn, version_ptr); } bool DataTable::IsVisible(const transaction::TransactionContext &txn, const TupleSlot slot) const { UndoRecord *version_ptr; bool visible; do { version_ptr = AtomicallyReadVersionPtr(slot, accessor_); // Here we will need to check that the version pointer did not change during our read. If it did, the visibility of // this tuple might have changed and we should check again. visible = Visible(slot, accessor_); } while (version_ptr != AtomicallyReadVersionPtr(slot, accessor_)); // Nullptr in version chain means no other versions visible to any transaction alive at this point. // Alternatively, if the current transaction holds the write lock, it should be able to read its own updates. if (version_ptr == nullptr || version_ptr->Timestamp().load() == txn.FinishTime()) { return visible; } // Apply deltas until we determine a version safe for us to read while (version_ptr != nullptr && transaction::TransactionUtil::NewerThan(version_ptr->Timestamp().load(), txn.StartTime())) { switch (version_ptr->Type()) { case DeltaRecordType::UPDATE: // Normal delta to be applied. Does not modify the logical delete column. break; case DeltaRecordType::INSERT: visible = false; break; case DeltaRecordType::DELETE: visible = true; } version_ptr = version_ptr->Next(); } return visible; } } // namespace terrier::storage
20,819
6,004
/* * tilefetcher.cpp -- part of Steps, a simple maps app * * Copyright 2009-2016 Andy Teijelo <www.ateijelo.com> * * 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 <QApplication> #include <QtAlgorithms> #include <QByteArray> #include <QSettings> #include <QtEndian> #include <QtDebug> #include <QFile> #include <QDir> #include <QSqlError> #include <QSqlQuery> #include "disktask.h" #include "networktask.h" #include "tilefetcher.h" #include "constants.h" #include "debug.h" TileFetcher::TileFetcher(QObject *parent) : QObject(parent) { for (int i=0; i<2; i++) { QThread *t = new QThread(this); idleDiskThreads.insert(t); t->start(); } for (int i=0; i<1; i++) { QThread *t = new QThread(this); idleNetworkThreads.insert(t); t->start(); } wakeUpEvent = QEvent::Type(QEvent::registerEventType()); pendingWakeUp = false; } TileFetcher::~TileFetcher() { foreach (QThread *t, idleDiskThreads+activeDiskThreads+idleNetworkThreads+activeNetworkThreads) { t->quit(); t->wait(); } } void TileFetcher::customEvent(QEvent *event) { fDebug(DEBUG_FETCHREQUESTS) << "TileFetcher::customEvent()"; if (event->type() == wakeUpEvent) { fDebug(DEBUG_FETCHREQUESTS) << " wakeUpEvent"; pendingWakeUp = false; work(); } } void TileFetcher::wakeUp() { fDebug(DEBUG_FETCHREQUESTS) << "TileFetcher::wakeUp()"; if (!pendingWakeUp) { pendingWakeUp = true; qApp->postEvent(this, new QEvent(wakeUpEvent)); } } void TileFetcher::fetchTile(const QString &maptype, int x, int y, int zoom) { fDebug(DEBUG_FETCHREQUESTS) << "TileFetcher::fetchTile" << maptype << x << y << zoom; // QMutexLocker l(&mutex); TileId r(maptype,x,y,zoom); if (requests.contains(r)) { fDebug(DEBUG_FETCHREQUESTS) << " request already queued."; return; } if (diskRequests.contains(r)) { fDebug(DEBUG_FETCHREQUESTS) << " request already in disk queue."; return; } if (networkRequests.contains(r)) { fDebug(DEBUG_FETCHREQUESTS) << " request already in network queue."; return; } requests.insert(r); wakeUp(); } void TileFetcher::forgetRequest(const QString &type, int x, int y, int zoom) { fDebug(DEBUG_FETCHREQUESTS) << "TileFetcher::forgetRequest" << type << x << y << zoom; // QMutexLocker l(&mutex); TileId r(type,x,y,zoom); QSet<TileId>::iterator i; i = requests.find(r); if (i != requests.end()) { requests.erase(i); } i = diskRequests.find(r); if (i != diskRequests.end()) { diskRequests.erase(i); } i = networkRequests.find(r); if (i != networkRequests.end()) { networkRequests.erase(i); } } void TileFetcher::networkTileData(const QString &type, int x, int y, int z, const QByteArray &data) { TileId tile(type,x,y,z); if (!data.isEmpty()) { emit tileData(type,x,y,z,data); memCache.insert(tile,data); diskWriteRequests.insert(tile,data); } activeNetworkRequests.remove(tile); wakeUp(); } void TileFetcher::diskTaskFinished(Task *task) { QThread* thread = task->thread(); QSet<QThread*>::iterator i = activeDiskThreads.find(thread); if (i == activeDiskThreads.end()) { fDebug(DEBUG_DISK) << "The thread of the disk task that just finished is not in the active list!"; exit(EXIT_FAILURE); } activeDiskThreads.erase(i); idleDiskThreads.insert(thread); task->deleteLater(); wakeUp(); } void TileFetcher::networkTaskFinished(Task *task) { QThread* thread = task->thread(); QSet<QThread*>::iterator i = activeNetworkThreads.find(thread); if (i == activeNetworkThreads.end()) { fDebug(DEBUG_NETWORK) << "The thread of the network task just finished is not in the active list!"; exit(EXIT_FAILURE); } activeNetworkThreads.erase(i); idleNetworkThreads.insert(thread); NetworkTask *n = static_cast<NetworkTask*>(task); activeNetworkRequests.remove(n->tileId()); task->deleteLater(); wakeUp(); } void TileFetcher::reload() { memCache.clear(); db.close(); } void TileFetcher::readMgm(const TileId& tile) { int mgm_x = tile.x >> 3; int mgm_y = tile.y >> 3; QSettings settings; QString filename = QString("%1/%2_%3/%4_%5.mgm") .arg(settings.value(SettingsKeys::CachePath,"").toString()) .arg(tile.type) .arg(tile.zoom) .arg(mgm_x) .arg(mgm_y); fDebug(DEBUG_DISK) << this << "started. Fetching" << tile.x << tile.y << "from" << filename; QFile mgm(filename); QHash<TileId,QPair<quint32,quint32> > mgmTiles; if (mgm.open(QIODevice::ReadOnly)) { quint64 r = 0; quint32 tile_start = 64*6 + 2; quint32 tile_end; quint16 no_tiles; r += mgm.read((char*)(&no_tiles),2); if (r != 2) { fDebug(DEBUG_DISK) << "error reading no_tiles"; no_tiles = 0; } no_tiles = qFromBigEndian(no_tiles); for (int i=0; i<no_tiles; i++) { quint8 tx,ty; r = mgm.read((char*)(&tx),1); r += mgm.read((char*)(&ty),1); r += mgm.read((char*)(&tile_end),4); if (r != 6) { fDebug(DEBUG_DISK) << "error reading tile entry " << i; break; } tile_end = qFromBigEndian(tile_end); TileId t(tile.type,tx + (mgm_x << 3),ty + (mgm_y << 3),tile.zoom); if (diskRequests.contains(t)) { mgmTiles.insert(t,qMakePair(tile_start,tile_end - tile_start)); diskRequests.remove(t); } tile_start = tile_end; } } if (!mgmTiles.contains(tile)) { diskRequests.remove(tile); networkRequests.insert(tile); } /* QSet<TileId>::iterator i = diskRequests.begin(); while (i != diskRequests.end()) { TileId t = *i; bool tBelongsHere = ((t.type == tile.type) && ((t.x >> 3) == mgm_x) && ((t.y >> 3) == mgm_y) && (t.zoom == tile.zoom)); if (tBelongsHere) { fDebug(DEBUG_DISK) << "tile" << t << "in queue, in the range of the mgm, but absent."; i = diskRequests.erase(i); networkRequests.insert(t); } else { i++; } } */ for (QHash<TileId,QPair<quint32,quint32> >::iterator i = mgmTiles.begin(); i != mgmTiles.end(); i++) { TileId t = i.key(); QPair<quint32,quint32> p = i.value(); quint32 tile_start = p.first; quint32 tile_size = p.second; mgm.seek(tile_start); QByteArray data = mgm.read(tile_size); if (static_cast<quint32>(data.size()) != tile_size) { fDebug(DEBUG_DISK) << "error reading tile " << tile.x << "," << tile.y << "data"; networkRequests.insert(t); continue; } else { fDebug(DEBUG_DISK) << "found tile" << t << "in mgm"; emit tileData(t.type,t.x,t.y,t.zoom,data); memCache.insert(t,data); } } } QByteArray TileFetcher::readMBTile(const TileId &tile) { QByteArray nothing; QSettings settings; QString path = settings.value(SettingsKeys::MBTilesPath,"").toString(); fDebug(DEBUG_DATABASE) << "readMBTile: " << tile; if (path.isEmpty()) { return nothing; } fDebug(DEBUG_DATABASE) << "db path:" << path; if (!db.isOpen()) { db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(path); if (!db.open()) return nothing; emit loadedMBTiles(path); fDebug(DEBUG_DATABASE) << "opened database:" << path; } //fDebug(DEBUG_DATABASE) << "db.hostName:" << db.hostName(); QSqlQuery q; q.prepare("SELECT tile_data FROM tiles WHERE " "zoom_level = :zoom AND " "tile_column = :x AND " "tile_row = :y LIMIT 1"); // .arg(tile.zoom) // .arg(tile.x) // .arg(tile.y) // ); q.bindValue(":zoom", tile.zoom); q.bindValue(":x", tile.x); q.bindValue(":y", tile.y); bool b = q.exec(); fDebug(DEBUG_DATABASE) << "exec returned" << b; //fDebug(DEBUG_DATABASE) << "x:" << tile.x << "y:" << tile.y << "zoom:" << tile.zoom; while (q.next()) { QByteArray r = q.value(0).toByteArray(); fDebug(DEBUG_DATABASE) << " query returned" << r.size() << "bytes"; return r; } fDebug(DEBUG_DATABASE) << " returned nothing"; return nothing; } bool TileFetcher::readSingleFile(const TileId& tile) { QSettings settings; QDir d(settings.value(SettingsKeys::CachePath,"").toString()); QFile f(d.absoluteFilePath(QString("cache/%1/%2/%3_%4").arg(tile.type).arg(tile.zoom).arg(tile.x).arg(tile.y))); fDebug(DEBUG_DISK) << "opening" << f.fileName(); if (f.open(QIODevice::ReadOnly)) { QByteArray data = f.readAll(); emit tileData(tile.type,tile.x,tile.y,tile.zoom,data); memCache.insert(tile,data); diskRequests.remove(tile); return true; } fDebug(DEBUG_DISK) << " failed"; return false; } void TileFetcher::work() { debug("TileFetcher::work"); while (requests.count() > 0) { QSet<TileId>::iterator i = requests.begin(); TileId r = *i; QByteArray a = memCache.getTileData(r); if (!a.isEmpty()) { emit tileData(r.type,r.x,r.y,r.zoom,a); requests.erase(i); continue; } requests.erase(i); diskRequests.insert(r); } while (diskRequests.count() > 0) { debug("while (diskRequests.count() > 0):"); QSet<TileId>::iterator i = diskRequests.begin(); TileId tile = *i; if (readSingleFile(tile)) continue; QByteArray data = readMBTile(tile); diskRequests.remove(tile); if (data.isNull()) { //fDebug(DEBUG_DISK) << "error reading tile " << tile.x << "," << tile.y << "data"; networkRequests.insert(tile); } else { //fDebug(DEBUG_DISK) << "found tile" << t << "in mgm"; emit tileData(tile.type,tile.x,tile.y,tile.zoom,data); memCache.insert(tile,data); } //readMgm(tile); } while (qMin(idleDiskThreads.count(),diskWriteRequests.count()) > 0) { QHash<TileId,QByteArray>::iterator i = diskWriteRequests.begin(); TileId r = i.key(); QByteArray a = i.value(); DiskTask *task = new DiskTask(); task->storeTile(r,a); connect(task,SIGNAL(finished(Task*)),this,SLOT(diskTaskFinished(Task*))); QSet<QThread*>::iterator j = idleDiskThreads.begin(); QThread *thread = *j; activeDiskThreads.insert(thread); idleDiskThreads.erase(j); task->moveToThread(thread); task->start(); diskWriteRequests.erase(i); } while (qMin(idleNetworkThreads.count(),networkRequests.count()) > 0) { QList<TileId> l = networkRequests.values(); qSort(l.begin(),l.end(),fetchOrder); QSet<TileId>::iterator i = networkRequests.find(l.at(0)); TileId r = *i; NetworkTask *task = new NetworkTask(r); connect(task,SIGNAL(tileData(QString,int,int,int,QByteArray)), this,SLOT(networkTileData(QString,int,int,int,QByteArray))); connect(task,SIGNAL(finished(Task*)), this,SLOT(networkTaskFinished(Task*))); QSet<QThread*>::iterator j = idleNetworkThreads.begin(); QThread *thread = *j; activeNetworkThreads.insert(thread); idleNetworkThreads.erase(j); task->moveToThread(thread); task->start(); networkRequests.erase(i); activeNetworkRequests.insert(r); } } bool fetchOrder(const TileId& t1, const TileId& t2) { if (t1.zoom < t2.zoom) return true; if (t1.zoom > t2.zoom) return false; if (t1.y < t2.y) return true; if (t1.y > t2.y) return false; if (t1.x < t2.x) return true; if (t1.x > t2.x) return false; return false; } void TileFetcher::debug(const QString& header) { if fEnabled(DEBUG_FETCHQUEUES) { qDebug() << header; // qDebug() << " idleDiskThreads:" << idleDiskThreads; qDebug() << " requests:"; foreach (const TileId& r, requests) qDebug() << " " << r.type << r.x << r.y << r.zoom; qDebug() << " diskRequests:"; foreach (const TileId& r, diskRequests) qDebug() << " " << r.type << r.x << r.y << r.zoom; qDebug() << " networkRequests:"; foreach (const TileId& r, networkRequests) qDebug() << " " << r.type << r.x << r.y << r.zoom; qDebug() << " activeNetworkRequests:"; foreach (const TileId& r, activeNetworkRequests) qDebug() << " " << r.type << r.x << r.y << r.zoom; } }
14,016
5,007
//-------------------------------------------------------------------------------------- // File: ShadowMap.cpp // // Starting point for new Direct3D applications // // Copyright (c) Microsoft Corporation. // Licensed under the MIT License (MIT). //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTcamera.h" #include "DXUTsettingsdlg.h" #include "SDKmisc.h" #include "SDKmesh.h" #include "resource.h" //#define DEBUG_VS // Uncomment this line to debug vertex shaders //#define DEBUG_PS // Uncomment this line to debug pixel shaders #define SHADOWMAP_SIZE 512 #define HELPTEXTCOLOR D3DXCOLOR( 0.0f, 1.0f, 0.3f, 1.0f ) LPCWSTR g_aszMeshFile[] = { L"room.x", L"airplane\\airplane 2.x", L"misc\\car.x", L"misc\\sphere.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"UI\\arrow.x", L"ring.x", L"ring.x", }; #define NUM_OBJ (sizeof(g_aszMeshFile)/sizeof(g_aszMeshFile[0])) D3DXMATRIXA16 g_amInitObjWorld[NUM_OBJ] = { D3DXMATRIXA16( 3.5f, 0.0f, 0.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f ), D3DXMATRIXA16( 0.43301f, 0.25f, 0.0f, 0.0f, -0.25f, 0.43301f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 5.0f, 1.33975f, 0.0f, 1.0f ), D3DXMATRIXA16( 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, -14.5f, -7.1f, 0.0f, 1.0f ), D3DXMATRIXA16( 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f, -7.0f, 0.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, 5.0f, 0.2f, 5.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, 5.0f, 0.2f, -5.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, -5.0f, 0.2f, 5.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, -5.0f, 0.2f, -5.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, 14.0f, 0.2f, 14.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, 14.0f, 0.2f, -14.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, -14.0f, 0.2f, 14.0f, 1.0f ), D3DXMATRIXA16( 5.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 5.5f, 0.0f, 0.0f, -9.0f, 0.0f, 0.0f, -14.0f, 0.2f, -14.0f, 1.0f ), D3DXMATRIXA16( 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, -14.5f, -9.0f, 0.0f, 1.0f ), D3DXMATRIXA16( 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 14.5f, -9.0f, 0.0f, 1.0f ), }; D3DVERTEXELEMENT9 g_aVertDecl[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, D3DDECL_END() }; //----------------------------------------------------------------------------- // Name: class CObj // Desc: Encapsulates a mesh object in the scene by grouping its world matrix // with the mesh. //----------------------------------------------------------------------------- #pragma warning( disable : 4324 ) struct CObj { CDXUTXFileMesh m_Mesh; D3DXMATRIXA16 m_mWorld; }; //----------------------------------------------------------------------------- // Name: class CViewCamera // Desc: A camera class derived from CFirstPersonCamera. The arrow keys and // numpad keys are disabled for this type of camera. //----------------------------------------------------------------------------- class CViewCamera : public CFirstPersonCamera { protected: virtual D3DUtil_CameraKeys MapKey( UINT nKey ) { // Provide custom mapping here. // Same as default mapping but disable arrow keys. switch( nKey ) { case 'A': return CAM_STRAFE_LEFT; case 'D': return CAM_STRAFE_RIGHT; case 'W': return CAM_MOVE_FORWARD; case 'S': return CAM_MOVE_BACKWARD; case 'Q': return CAM_MOVE_DOWN; case 'E': return CAM_MOVE_UP; case VK_HOME: return CAM_RESET; } return CAM_UNKNOWN; } }; //----------------------------------------------------------------------------- // Name: class CLightCamera // Desc: A camera class derived from CFirstPersonCamera. The letter keys // are disabled for this type of camera. This class is intended for use // by the spot light. //----------------------------------------------------------------------------- class CLightCamera : public CFirstPersonCamera { protected: virtual D3DUtil_CameraKeys MapKey( UINT nKey ) { // Provide custom mapping here. // Same as default mapping but disable arrow keys. switch( nKey ) { case VK_LEFT: return CAM_STRAFE_LEFT; case VK_RIGHT: return CAM_STRAFE_RIGHT; case VK_UP: return CAM_MOVE_FORWARD; case VK_DOWN: return CAM_MOVE_BACKWARD; case VK_PRIOR: return CAM_MOVE_UP; // pgup case VK_NEXT: return CAM_MOVE_DOWN; // pgdn case VK_NUMPAD4: return CAM_STRAFE_LEFT; case VK_NUMPAD6: return CAM_STRAFE_RIGHT; case VK_NUMPAD8: return CAM_MOVE_FORWARD; case VK_NUMPAD2: return CAM_MOVE_BACKWARD; case VK_NUMPAD9: return CAM_MOVE_UP; case VK_NUMPAD3: return CAM_MOVE_DOWN; case VK_HOME: return CAM_RESET; } return CAM_UNKNOWN; } }; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- ID3DXFont* g_pFont = NULL; // Font for drawing text ID3DXFont* g_pFontSmall = NULL; // Font for drawing text ID3DXSprite* g_pTextSprite = NULL; // Sprite for batching draw text calls ID3DXEffect* g_pEffect = NULL; // D3DX effect interface bool g_bShowHelp = true; // If true, it renders the UI control text CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CD3DSettingsDlg g_SettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // dialog for standard controls CFirstPersonCamera g_VCamera; // View camera CFirstPersonCamera g_LCamera; // Camera obj to help adjust light CObj g_Obj[NUM_OBJ]; // Scene object meshes LPDIRECT3DVERTEXDECLARATION9 g_pVertDecl = NULL;// Vertex decl for the sample LPDIRECT3DTEXTURE9 g_pTexDef = NULL; // Default texture for objects D3DLIGHT9 g_Light; // The spot light in the scene CDXUTXFileMesh g_LightMesh; LPDIRECT3DTEXTURE9 g_pShadowMap = NULL; // Texture to which the shadow map is rendered LPDIRECT3DSURFACE9 g_pDSShadow = NULL; // Depth-stencil buffer for rendering to shadow map float g_fLightFov; // FOV of the spot light (in radian) D3DXMATRIXA16 g_mShadowProj; // Projection matrix for shadow map bool g_bRightMouseDown = false;// Indicates whether right mouse button is held bool g_bCameraPerspective // Indicates whether we should render view from = true; // the camera's or the light's perspective bool g_bFreeLight = true; // Whether the light is freely moveable. //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 #define IDC_CHECKBOX 5 #define IDC_LIGHTPERSPECTIVE 6 #define IDC_ATTACHLIGHTTOCAR 7 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- void InitializeDialogs(); bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); void RenderText(); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK MouseProc( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); void CALLBACK OnLostDevice( void* pUserContext ); void CALLBACK OnDestroyDevice( void* pUserContext ); void RenderScene( IDirect3DDevice9* pd3dDevice, bool bRenderShadow, float fElapsedTime, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj ); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // Initialize the camera g_VCamera.SetScalers( 0.01f, 15.0f ); g_LCamera.SetScalers( 0.01f, 8.0f ); g_VCamera.SetRotateButtons( true, false, false ); g_LCamera.SetRotateButtons( false, false, true ); // Set up the view parameters for the camera D3DXVECTOR3 vFromPt = D3DXVECTOR3( 0.0f, 5.0f, -18.0f ); D3DXVECTOR3 vLookatPt = D3DXVECTOR3( 0.0f, -1.0f, 0.0f ); g_VCamera.SetViewParams( &vFromPt, &vLookatPt ); vFromPt = D3DXVECTOR3( 0.0f, 0.0f, -12.0f ); vLookatPt = D3DXVECTOR3( 0.0f, -2.0f, 1.0f ); g_LCamera.SetViewParams( &vFromPt, &vLookatPt ); // Initialize the spot light g_fLightFov = D3DX_PI / 2.0f; g_Light.Diffuse.r = 1.0f; g_Light.Diffuse.g = 1.0f; g_Light.Diffuse.b = 1.0f; g_Light.Diffuse.a = 1.0f; g_Light.Position = D3DXVECTOR3( -8.0f, -8.0f, 0.0f ); g_Light.Direction = D3DXVECTOR3( 1.0f, -1.0f, 0.0f ); D3DXVec3Normalize( ( D3DXVECTOR3* )&g_Light.Direction, ( D3DXVECTOR3* )&g_Light.Direction ); g_Light.Range = 10.0f; g_Light.Theta = g_fLightFov / 2.0f; g_Light.Phi = g_fLightFov / 2.0f; // Set the callback functions. These functions allow DXUT to notify // the application about device changes, user input, and windows messages. The // callbacks are optional so you need only set callbacks for events you're interested // in. However, if you don't handle the device reset/lost callbacks then the sample // framework won't be able to reset your device since the application must first // release all device resources before resetting. Likewise, if you don't handle the // device created/destroyed callbacks then DXUT won't be able to // recreate your device resources. DXUTSetCallbackD3D9DeviceAcceptable( IsDeviceAcceptable ); DXUTSetCallbackD3D9DeviceCreated( OnCreateDevice ); DXUTSetCallbackD3D9DeviceReset( OnResetDevice ); DXUTSetCallbackD3D9FrameRender( OnFrameRender ); DXUTSetCallbackD3D9DeviceLost( OnLostDevice ); DXUTSetCallbackD3D9DeviceDestroyed( OnDestroyDevice ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( KeyboardProc ); DXUTSetCallbackMouse( MouseProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); InitializeDialogs(); // Show the cursor and clip it when in full screen DXUTSetCursorSettings( true, true ); // Initialize DXUT and create the desired Win32 window and Direct3D // device for the application. Calling each of these functions is optional, but they // allow you to set several options which control the behavior of the framework. DXUTInit( true, true ); // Parse the command line and show msgboxes DXUTSetHotkeyHandling( true, true, true ); // handle the defaul hotkeys DXUTCreateWindow( L"ShadowMap" ); DXUTCreateDevice( true, 640, 480 ); // Pass control to DXUT for handling the message pump and // dispatching render calls. DXUT will call your FrameMove // and FrameRender callback when there is idle time between handling window messages. DXUTMainLoop(); // Perform any application-level cleanup here. Direct3D device resources are released within the // appropriate callback functions and therefore don't require any cleanup code here. return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Sets up the dialogs //-------------------------------------------------------------------------------------- void InitializeDialogs() { g_SettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 ); g_HUD.AddCheckBox( IDC_CHECKBOX, L"Display help text", 35, iY += 24, 125, 22, true, VK_F1 ); g_HUD.AddCheckBox( IDC_LIGHTPERSPECTIVE, L"View from light's perspective", 0, iY += 24, 160, 22, false, L'V' ); g_HUD.AddCheckBox( IDC_ATTACHLIGHTTOCAR, L"Attach light to car", 0, iY += 24, 160, 22, false, L'F' ); } //-------------------------------------------------------------------------------------- // Called during device initialization, this code checks the device for some // minimum set of capabilities, and rejects those that don't pass by returning false. //-------------------------------------------------------------------------------------- bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { // Skip backbuffer formats that don't support alpha blending IDirect3D9* pD3D = DXUTGetD3D9Object(); if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat ) ) ) return false; // Must support pixel shader 2.0 if( pCaps->PixelShaderVersion < D3DPS_VERSION( 2, 0 ) ) return false; // need to support D3DFMT_R32F render target if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_CUBETEXTURE, D3DFMT_R32F ) ) ) return false; // need to support D3DFMT_A8R8G8B8 render target if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_RENDERTARGET, D3DRTYPE_CUBETEXTURE, D3DFMT_A8R8G8B8 ) ) ) return false; return true; } //-------------------------------------------------------------------------------------- // This callback function is called immediately before a device is created to allow the // application to modify the device settings. The supplied pDeviceSettings parameter // contains the settings that the framework has selected for the new device, and the // application can make any desired changes directly to this structure. Note however that // DXUT will not correct invalid device settings so care must be taken // to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail. //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { assert( DXUT_D3D9_DEVICE == pDeviceSettings->ver ); HRESULT hr; IDirect3D9* pD3D = DXUTGetD3D9Object(); D3DCAPS9 caps; V( pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, &caps ) ); // Turn vsync off pDeviceSettings->d3d9.pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; g_SettingsDlg.GetDialogControl()->GetComboBox( DXUTSETTINGSDLG_PRESENT_INTERVAL )->SetEnabled( false ); // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if( ( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) == 0 || caps.VertexShaderVersion < D3DVS_VERSION( 1, 1 ) ) { pDeviceSettings->d3d9.BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING; } // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. #ifdef DEBUG_VS if( pDeviceSettings->d3d9.DeviceType != D3DDEVTYPE_REF ) { pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE; pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } #endif #ifdef DEBUG_PS pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF; #endif // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; if( pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } return true; } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // created, which will happen during application initialization and windowed/full screen // toggles. This is the best location to create D3DPOOL_MANAGED resources since these // resources need to be reloaded whenever the device is destroyed. Resources created // here should be released in the OnDestroyDevice callback. //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9CreateDevice( pd3dDevice ) ); V_RETURN( g_SettingsDlg.OnD3D9CreateDevice( pd3dDevice ) ); // Initialize the font V_RETURN( D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont ) ); V_RETURN( D3DXCreateFont( pd3dDevice, 12, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFontSmall ) ); // Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the // shader debugger. Debugging vertex shaders requires either REF or software vertex // processing, and debugging pixel shaders requires REF. The // D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the // shader debugger. It enables source level debugging, prevents instruction // reordering, prevents dead code elimination, and forces the compiler to compile // against the next higher available software target, which ensures that the // unoptimized shaders do not exceed the shader model limitations. Setting these // flags will cause slower rendering since the shaders will be unoptimized and // forced into software. See the DirectX documentation for more information about // using the shader debugger. DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE; #if defined( DEBUG ) || defined( _DEBUG ) // Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders. // Setting this flag improves the shader debugging experience, but still allows // the shaders to be optimized and to run exactly the way they will run in // the release configuration of this program. dwShaderFlags |= D3DXSHADER_DEBUG; #endif #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif // Read the D3DX effect file WCHAR str[MAX_PATH]; V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"ShadowMap.fx" ) ); // If this fails, there should be debug output as to // they the .fx file failed to compile V_RETURN( D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags, NULL, &g_pEffect, NULL ) ); // Create vertex declaration V_RETURN( pd3dDevice->CreateVertexDeclaration( g_aVertDecl, &g_pVertDecl ) ); // Initialize the meshes for( int i = 0; i < NUM_OBJ; ++i ) { V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, g_aszMeshFile[i] ) ); if( FAILED( g_Obj[i].m_Mesh.Create( pd3dDevice, str ) ) ) return DXUTERR_MEDIANOTFOUND; V_RETURN( g_Obj[i].m_Mesh.SetVertexDecl( pd3dDevice, g_aVertDecl ) ); g_Obj[i].m_mWorld = g_amInitObjWorld[i]; } // Initialize the light mesh V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"spotlight.x" ) ); if( FAILED( g_LightMesh.Create( pd3dDevice, str ) ) ) return DXUTERR_MEDIANOTFOUND; V_RETURN( g_LightMesh.SetVertexDecl( pd3dDevice, g_aVertDecl ) ); // World transform to identity D3DXMATRIXA16 mIdent; D3DXMatrixIdentity( &mIdent ); V_RETURN( pd3dDevice->SetTransform( D3DTS_WORLD, &mIdent ) ); return S_OK; } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has been // reset, which will happen after a lost device scenario. This is the best location to // create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever // the device is lost. Resources created here should be released in the OnLostDevice // callback. //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9ResetDevice() ); V_RETURN( g_SettingsDlg.OnD3D9ResetDevice() ); if( g_pFont ) V_RETURN( g_pFont->OnResetDevice() ); if( g_pFontSmall ) V_RETURN( g_pFontSmall->OnResetDevice() ); if( g_pEffect ) V_RETURN( g_pEffect->OnResetDevice() ); // Create a sprite to help batch calls when drawing many lines of text V_RETURN( D3DXCreateSprite( pd3dDevice, &g_pTextSprite ) ); // Setup the camera's projection parameters float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; g_VCamera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.1f, 100.0f ); g_LCamera.SetProjParams( D3DX_PI / 4, fAspectRatio, 0.1f, 100.0f ); // Create the default texture (used when a triangle does not use a texture) V_RETURN( pd3dDevice->CreateTexture( 1, 1, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_pTexDef, NULL ) ); D3DLOCKED_RECT lr; V_RETURN( g_pTexDef->LockRect( 0, &lr, NULL, 0 ) ); *( LPDWORD )lr.pBits = D3DCOLOR_RGBA( 255, 255, 255, 255 ); V_RETURN( g_pTexDef->UnlockRect( 0 ) ); // Restore the scene objects for( int i = 0; i < NUM_OBJ; ++i ) V_RETURN( g_Obj[i].m_Mesh.RestoreDeviceObjects( pd3dDevice ) ); V_RETURN( g_LightMesh.RestoreDeviceObjects( pd3dDevice ) ); // Restore the effect variables V_RETURN( g_pEffect->SetVector( "g_vLightDiffuse", ( D3DXVECTOR4* )&g_Light.Diffuse ) ); V_RETURN( g_pEffect->SetFloat( "g_fCosTheta", cosf( g_Light.Theta ) ) ); // Create the shadow map texture V_RETURN( pd3dDevice->CreateTexture( SHADOWMAP_SIZE, SHADOWMAP_SIZE, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R32F, D3DPOOL_DEFAULT, &g_pShadowMap, NULL ) ); // Create the depth-stencil buffer to be used with the shadow map // We do this to ensure that the depth-stencil buffer is large // enough and has correct multisample type/quality when rendering // the shadow map. The default depth-stencil buffer created during // device creation will not be large enough if the user resizes the // window to a very small size. Furthermore, if the device is created // with multisampling, the default depth-stencil buffer will not // work with the shadow map texture because texture render targets // do not support multisample. DXUTDeviceSettings d3dSettings = DXUTGetDeviceSettings(); V_RETURN( pd3dDevice->CreateDepthStencilSurface( SHADOWMAP_SIZE, SHADOWMAP_SIZE, d3dSettings.d3d9.pp.AutoDepthStencilFormat, D3DMULTISAMPLE_NONE, 0, TRUE, &g_pDSShadow, NULL ) ); // Initialize the shadow projection matrix D3DXMatrixPerspectiveFovLH( &g_mShadowProj, g_fLightFov, 1, 0.01f, 100.0f ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, pBackBufferSurfaceDesc->Height ); CDXUTControl* pControl = g_HUD.GetControl( IDC_LIGHTPERSPECTIVE ); if( pControl ) pControl->SetLocation( 0, pBackBufferSurfaceDesc->Height - 50 ); pControl = g_HUD.GetControl( IDC_ATTACHLIGHTTOCAR ); if( pControl ) pControl->SetLocation( 0, pBackBufferSurfaceDesc->Height - 25 ); return S_OK; } //-------------------------------------------------------------------------------------- // This callback function will be called once at the beginning of every frame. This is the // best location for your application to handle updates to the scene, but is not // intended to contain actual rendering calls, which should instead be placed in the // OnFrameRender callback. //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // Update the camera's position based on user input g_VCamera.FrameMove( fElapsedTime ); g_LCamera.FrameMove( fElapsedTime ); // Animate the plane, car and sphere meshes D3DXMATRIXA16 m; D3DXMatrixRotationY( &m, D3DX_PI * fElapsedTime / 4.0f ); D3DXMatrixMultiply( &g_Obj[1].m_mWorld, &g_Obj[1].m_mWorld, &m ); D3DXMatrixRotationY( &m, -D3DX_PI * fElapsedTime / 4.0f ); D3DXMatrixMultiply( &g_Obj[2].m_mWorld, &g_Obj[2].m_mWorld, &m ); D3DXVECTOR3 vR( 0.1f, 1.0f, -0.2f ); D3DXMatrixRotationAxis( &m, &vR, -D3DX_PI * fElapsedTime / 6.0f ); D3DXMatrixMultiply( &g_Obj[3].m_mWorld, &m, &g_Obj[3].m_mWorld ); } //-------------------------------------------------------------------------------------- // Renders the scene onto the current render target using the current // technique in the effect. //-------------------------------------------------------------------------------------- void RenderScene( IDirect3DDevice9* pd3dDevice, bool bRenderShadow, float fElapsedTime, const D3DXMATRIX* pmView, const D3DXMATRIX* pmProj ) { HRESULT hr; // Set the projection matrix V( g_pEffect->SetMatrix( "g_mProj", pmProj ) ); // Update the light parameters in the effect if( g_bFreeLight ) { // Freely moveable light. Get light parameter // from the light camera. D3DXVECTOR3 v = *g_LCamera.GetEyePt(); D3DXVECTOR4 v4; D3DXVec3Transform( &v4, &v, pmView ); V( g_pEffect->SetVector( "g_vLightPos", &v4 ) ); *( D3DXVECTOR3* )&v4 = *g_LCamera.GetWorldAhead(); v4.w = 0.0f; // Set w 0 so that the translation part doesn't come to play D3DXVec4Transform( &v4, &v4, pmView ); // Direction in view space D3DXVec3Normalize( ( D3DXVECTOR3* )&v4, ( D3DXVECTOR3* )&v4 ); V( g_pEffect->SetVector( "g_vLightDir", &v4 ) ); } else { // Light attached to car. Get the car's world position and direction. D3DXMATRIXA16 m = g_Obj[2].m_mWorld; D3DXVECTOR3 v( m._41, m._42, m._43 ); D3DXVECTOR4 vPos; D3DXVec3Transform( &vPos, &v, pmView ); D3DXVECTOR4 v4( 0.0f, 0.0f, -1.0f, 1.0f ); // In object space, car is facing -Z m._41 = m._42 = m._43 = 0.0f; // Remove the translation D3DXVec4Transform( &v4, &v4, &m ); // Obtain direction in world space v4.w = 0.0f; // Set w 0 so that the translation part doesn't come to play D3DXVec4Transform( &v4, &v4, pmView ); // Direction in view space D3DXVec3Normalize( ( D3DXVECTOR3* )&v4, ( D3DXVECTOR3* )&v4 ); V( g_pEffect->SetVector( "g_vLightDir", &v4 ) ); vPos += v4 * 4.0f; // Offset the center by 3 so that it's closer to the headlight. V( g_pEffect->SetVector( "g_vLightPos", &vPos ) ); } // Clear the render buffers V( pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0x000000ff, 1.0f, 0L ) ); if( bRenderShadow ) V( g_pEffect->SetTechnique( "RenderShadow" ) ); // Begin the scene if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { if( !bRenderShadow ) V( g_pEffect->SetTechnique( "RenderScene" ) ); // Render the objects for( int obj = 0; obj < NUM_OBJ; ++obj ) { D3DXMATRIXA16 mWorldView = g_Obj[obj].m_mWorld; D3DXMatrixMultiply( &mWorldView, &mWorldView, pmView ); V( g_pEffect->SetMatrix( "g_mWorldView", &mWorldView ) ); LPD3DXMESH pMesh = g_Obj[obj].m_Mesh.GetMesh(); UINT cPass; V( g_pEffect->Begin( &cPass, 0 ) ); for( UINT p = 0; p < cPass; ++p ) { V( g_pEffect->BeginPass( p ) ); for( DWORD i = 0; i < g_Obj[obj].m_Mesh.m_dwNumMaterials; ++i ) { D3DXVECTOR4 vDif( g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.r, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.g, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.b, g_Obj[obj].m_Mesh.m_pMaterials[i].Diffuse.a ); V( g_pEffect->SetVector( "g_vMaterial", &vDif ) ); if( g_Obj[obj].m_Mesh.m_pTextures[i] ) V( g_pEffect->SetTexture( "g_txScene", g_Obj[obj].m_Mesh.m_pTextures[i] ) ) else V( g_pEffect->SetTexture( "g_txScene", g_pTexDef ) ) V( g_pEffect->CommitChanges() ); V( pMesh->DrawSubset( i ) ); } V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); } // Render light if( !bRenderShadow ) V( g_pEffect->SetTechnique( "RenderLight" ) ); D3DXMATRIXA16 mWorldView = *g_LCamera.GetWorldMatrix(); D3DXMatrixMultiply( &mWorldView, &mWorldView, pmView ); V( g_pEffect->SetMatrix( "g_mWorldView", &mWorldView ) ); UINT cPass; LPD3DXMESH pMesh = g_LightMesh.GetMesh(); V( g_pEffect->Begin( &cPass, 0 ) ); for( UINT p = 0; p < cPass; ++p ) { V( g_pEffect->BeginPass( p ) ); for( DWORD i = 0; i < g_LightMesh.m_dwNumMaterials; ++i ) { D3DXVECTOR4 vDif( g_LightMesh.m_pMaterials[i].Diffuse.r, g_LightMesh.m_pMaterials[i].Diffuse.g, g_LightMesh.m_pMaterials[i].Diffuse.b, g_LightMesh.m_pMaterials[i].Diffuse.a ); V( g_pEffect->SetVector( "g_vMaterial", &vDif ) ); V( g_pEffect->SetTexture( "g_txScene", g_LightMesh.m_pTextures[i] ) ); V( g_pEffect->CommitChanges() ); V( pMesh->DrawSubset( i ) ); } V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); if( !bRenderShadow ) // Render stats and help text RenderText(); // Render the UI elements if( !bRenderShadow ) g_HUD.OnRender( fElapsedTime ); V( pd3dDevice->EndScene() ); } } //-------------------------------------------------------------------------------------- // This callback function will be called at the end of every frame to perform all the // rendering calls for the scene, and it will also be called if the window needs to be // repainted. After this function has returned, DXUT will call // IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain //-------------------------------------------------------------------------------------- void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // If the settings dialog is being shown, then // render it instead of rendering the app's scene if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.OnRender( fElapsedTime ); return; } HRESULT hr; // // Compute the view matrix for the light // This changes depending on the light mode // (free movement or attached) // D3DXMATRIXA16 mLightView; if( g_bFreeLight ) mLightView = *g_LCamera.GetViewMatrix(); else { // Light attached to car. mLightView = g_Obj[2].m_mWorld; D3DXVECTOR3 vPos( mLightView._41, mLightView._42, mLightView._43 ); // Offset z by -2 so that it's closer to headlight D3DXVECTOR4 vDir = D3DXVECTOR4( 0.0f, 0.0f, -1.0f, 1.0f ); // In object space, car is facing -Z mLightView._41 = mLightView._42 = mLightView._43 = 0.0f; // Remove the translation D3DXVec4Transform( &vDir, &vDir, &mLightView ); // Obtain direction in world space vDir.w = 0.0f; // Set w 0 so that the translation part below doesn't come to play D3DXVec4Normalize( &vDir, &vDir ); vPos.x += vDir.x * 4.0f; // Offset the center by 4 so that it's closer to the headlight vPos.y += vDir.y * 4.0f; vPos.z += vDir.z * 4.0f; vDir.x += vPos.x; // vDir denotes the look-at point vDir.y += vPos.y; vDir.z += vPos.z; D3DXVECTOR3 vUp( 0.0f, 1.0f, 0.0f ); D3DXMatrixLookAtLH( &mLightView, &vPos, ( D3DXVECTOR3* )&vDir, &vUp ); } // // Render the shadow map // LPDIRECT3DSURFACE9 pOldRT = NULL; V( pd3dDevice->GetRenderTarget( 0, &pOldRT ) ); LPDIRECT3DSURFACE9 pShadowSurf; if( SUCCEEDED( g_pShadowMap->GetSurfaceLevel( 0, &pShadowSurf ) ) ) { pd3dDevice->SetRenderTarget( 0, pShadowSurf ); SAFE_RELEASE( pShadowSurf ); } LPDIRECT3DSURFACE9 pOldDS = NULL; if( SUCCEEDED( pd3dDevice->GetDepthStencilSurface( &pOldDS ) ) ) pd3dDevice->SetDepthStencilSurface( g_pDSShadow ); { CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Shadow Map" ); RenderScene( pd3dDevice, true, fElapsedTime, &mLightView, &g_mShadowProj ); } if( pOldDS ) { pd3dDevice->SetDepthStencilSurface( pOldDS ); pOldDS->Release(); } pd3dDevice->SetRenderTarget( 0, pOldRT ); SAFE_RELEASE( pOldRT ); // // Now that we have the shadow map, render the scene. // const D3DXMATRIX* pmView = g_bCameraPerspective ? g_VCamera.GetViewMatrix() : &mLightView; // Initialize required parameter V( g_pEffect->SetTexture( "g_txShadow", g_pShadowMap ) ); // Compute the matrix to transform from view space to // light projection space. This consists of // the inverse of view matrix * view matrix of light * light projection matrix D3DXMATRIXA16 mViewToLightProj; mViewToLightProj = *pmView; D3DXMatrixInverse( &mViewToLightProj, NULL, &mViewToLightProj ); D3DXMatrixMultiply( &mViewToLightProj, &mViewToLightProj, &mLightView ); D3DXMatrixMultiply( &mViewToLightProj, &mViewToLightProj, &g_mShadowProj ); V( g_pEffect->SetMatrix( "g_mViewToLightProj", &mViewToLightProj ) ); { CDXUTPerfEventGenerator g( DXUT_PERFEVENTCOLOR, L"Scene" ); RenderScene( pd3dDevice, false, fElapsedTime, pmView, g_VCamera.GetProjMatrix() ); } g_pEffect->SetTexture( "g_txShadow", NULL ); } //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- void RenderText() { // The helper object simply helps keep track of text position, and color // and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr ); // If NULL is passed in as the sprite object, then it will work however the // pFont->DrawText() will not be batched together. Batching calls will improves performance. CDXUTTextHelper txtHelper( g_pFont, g_pTextSprite, 15 ); // Output statistics txtHelper.Begin(); txtHelper.SetInsertionPos( 5, 5 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) ); // Show FPS txtHelper.DrawTextLine( DXUTGetDeviceStats() ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); // Draw help if( g_bShowHelp ) { const D3DSURFACE_DESC* pd3dsdBackBuffer = DXUTGetD3D9BackBufferSurfaceDesc(); txtHelper.SetInsertionPos( 10, pd3dsdBackBuffer->Height - 15 * 10 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 0.75f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( L"Controls:" ); txtHelper.SetInsertionPos( 15, pd3dsdBackBuffer->Height - 15 * 9 ); WCHAR text[512]; swprintf_s(text,L"Rotate camera\nMove camera\n" L"Rotate light\nMove light\n" L"Change light mode (Current: %s)\nChange view reference (Current: %s)\n" L"Hidehelp\nQuit", g_bFreeLight ? L"Free" : L"Car-attached", g_bCameraPerspective ? L"Camera" : L"Light" ); txtHelper.DrawTextLine(text); txtHelper.SetInsertionPos( 265, pd3dsdBackBuffer->Height - 15 * 9 ); txtHelper.DrawTextLine( L"Left drag mouse\nW,S,A,D,Q,E\n" L"Right drag mouse\nW,S,A,D,Q,E while holding right mouse\n" L"F\nV\nF1\nESC" ); } else { txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); txtHelper.DrawTextLine( L"Press F1 for help" ); } txtHelper.End(); } //-------------------------------------------------------------------------------------- // Before handling window messages, DXUT passes incoming windows // messages to the application through this callback function. If the application sets // *pbNoFurtherProcessing to TRUE, then DXUT will not process this message. //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all windows messages to camera and dialogs so they can respond to user input if( WM_KEYDOWN != uMsg || g_bRightMouseDown ) g_LCamera.HandleMessages( hWnd, uMsg, wParam, lParam ); if( WM_KEYDOWN != uMsg || !g_bRightMouseDown ) { if( g_bCameraPerspective ) g_VCamera.HandleMessages( hWnd, uMsg, wParam, lParam ); else g_LCamera.HandleMessages( hWnd, uMsg, wParam, lParam ); } return 0; } //-------------------------------------------------------------------------------------- // As a convenience, DXUT inspects the incoming windows messages for // keystroke messages and decodes the message parameters to pass relevant keyboard // messages to the application. The framework does not remove the underlying keystroke // messages, which are still passed to the application's MsgProc callback. //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { } void CALLBACK MouseProc( bool bLeftButtonDown, bool bRightButtonDown, bool bMiddleButtonDown, bool bSideButton1Down, bool bSideButton2Down, int nMouseWheelDelta, int xPos, int yPos, void* pUserContext ) { g_bRightMouseDown = bRightButtonDown; } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() ); break; case IDC_CHECKBOX: { CDXUTCheckBox* pCheck = ( CDXUTCheckBox* )pControl; g_bShowHelp = pCheck->GetChecked(); break; } case IDC_LIGHTPERSPECTIVE: { CDXUTCheckBox* pCheck = ( CDXUTCheckBox* )pControl; g_bCameraPerspective = !pCheck->GetChecked(); if( g_bCameraPerspective ) { g_VCamera.SetRotateButtons( true, false, false ); g_LCamera.SetRotateButtons( false, false, true ); } else { g_VCamera.SetRotateButtons( false, false, false ); g_LCamera.SetRotateButtons( true, false, true ); } break; } case IDC_ATTACHLIGHTTOCAR: { CDXUTCheckBox* pCheck = ( CDXUTCheckBox* )pControl; g_bFreeLight = !pCheck->GetChecked(); break; } } } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // entered a lost state and before IDirect3DDevice9::Reset is called. Resources created // in the OnResetDevice callback should be released here, which generally includes all // D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for // information about lost devices. //-------------------------------------------------------------------------------------- void CALLBACK OnLostDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9LostDevice(); g_SettingsDlg.OnD3D9LostDevice(); if( g_pFont ) g_pFont->OnLostDevice(); if( g_pFontSmall ) g_pFontSmall->OnLostDevice(); if( g_pEffect ) g_pEffect->OnLostDevice(); SAFE_RELEASE( g_pTextSprite ); SAFE_RELEASE( g_pDSShadow ); SAFE_RELEASE( g_pShadowMap ); SAFE_RELEASE( g_pTexDef ); for( int i = 0; i < NUM_OBJ; ++i ) g_Obj[i].m_Mesh.InvalidateDeviceObjects(); g_LightMesh.InvalidateDeviceObjects(); } //-------------------------------------------------------------------------------------- // This callback function will be called immediately after the Direct3D device has // been destroyed, which generally happens as a result of application termination or // windowed/full screen toggles. Resources created in the OnCreateDevice callback // should be released here, which generally includes all D3DPOOL_MANAGED resources. //-------------------------------------------------------------------------------------- void CALLBACK OnDestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9DestroyDevice(); g_SettingsDlg.OnD3D9DestroyDevice(); SAFE_RELEASE( g_pEffect ); SAFE_RELEASE( g_pFont ); SAFE_RELEASE( g_pFontSmall ); SAFE_RELEASE( g_pVertDecl ); SAFE_RELEASE( g_pEffect ); for( int i = 0; i < NUM_OBJ; ++i ) g_Obj[i].m_Mesh.Destroy(); g_LightMesh.Destroy(); }
49,061
17,392
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (c) 2019 Panda Team */ #include <node_api.h> #include "jsfeature_top.hpp" #include "utils.hpp" template napi_value top_<int64_t,int64_t,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int64_t,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,int32_t,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,bool,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,double,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,std::string,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,int64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<int64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,int64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<int64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,int32_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<int32_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,int32_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<int32_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,bool,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<bool>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,bool,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<bool>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,double,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<double>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,double,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<double>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,std::string,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<std::string>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,std::string,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<std::string>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,uint64_t,true,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<uint64_t>,true,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,uint64_t,false,cross::non_iterable>(napi_env env, js_function & jsf, jsfeature * obj); template napi_value top_<int64_t,uint64_t,js_array<uint64_t>,false,cross::iterable>(napi_env env, js_function & jsf, jsfeature * obj);
18,998
7,405
#include "../../amalgamated/rfc_amalgamated.h" class MyWindow : public KFrame, public KMenuItemListener { protected: KMenuBar menuBar; KMenu mFile, mEdit, mHelp; KMenuItem miOpen, miExit, miCut, miCopy, miPaste, miAbout; public: MyWindow() { this->SetText(L"My Window"); this->Create(); miOpen.SetText(L"Open..."); miExit.SetText(L"Exit"); miCut.SetText(L"Cut"); miCopy.SetText(L"Copy"); miPaste.SetText(L"Paste"); miAbout.SetText(L"About..."); miOpen.SetListener(this); miExit.SetListener(this); miCut.SetListener(this); miCopy.SetListener(this); miPaste.SetListener(this); miAbout.SetListener(this); // add menu items into menu mFile.AddMenuItem(&miOpen); mFile.AddSeperator(); mFile.AddMenuItem(&miExit); mEdit.AddMenuItem(&miCut); mEdit.AddSeperator(); mEdit.AddMenuItem(&miCopy); mEdit.AddMenuItem(&miPaste); mHelp.AddMenuItem(&miAbout); // add menu into menubar menuBar.AddMenu(L"File", &mFile); menuBar.AddMenu(L"Edit", &mEdit); menuBar.AddMenu(L"Help", &mHelp); menuBar.AddToWindow(this); // add menubar into the window } void OnMenuItemPress(KMenuItem *menuItem) { if (menuItem == &miAbout) { ::MessageBoxW(this->GetHWND(), L"RFC Menu/Popup Example", L"About", MB_ICONINFORMATION); } else if (menuItem == &miExit) { this->OnClose(); // destroy window and quit from message loop! } } // macro to handle window messages... BEGIN_KMSG_HANDLER ON_KMSG(WM_RBUTTONUP, OnRClickWindow) // call OnRClickWindow method when WM_RBUTTONUP msg received END_KMSG_HANDLER(KFrame) // KFrame is our parent! LRESULT OnRClickWindow(WPARAM wParam, LPARAM lParam) { mEdit.PopUpMenu(this); // show mEdit menu as popup return 0; } }; class MyApplication : public KApplication { public: int Main(KString **argv, int argc) { MyWindow window; window.CenterScreen(); window.SetVisible(true); ::DoMessagePump(); return 0; } }; START_RFC_APPLICATION(MyApplication);
1,970
821
#include <iostream> #include <math.h> using namespace std; int main(void) { int numPrecision = 2; cout.precision(numPrecision); double a = 0; int b = 1; cout << "Value for \"double a\" is: " << fixed << a << endl; cout << "Value for \"int b\" is: " /* << fixed */ << b << endl; return 0; }
303
125