repo_name
stringlengths
5
85
path
stringlengths
3
252
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
922
999k
license
stringclasses
15 values
kristapsdz/letskencrypt-portable
http.c
1
18646
/* $Id$ */ /* * Copyright (c) 2016 Kristaps Dzonsons <kristaps@bsd.lv> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <sys/socket.h> #include <sys/param.h> #include <arpa/inet.h> #if TLS_API < 20160801 # include <sys/stat.h> # include <sys/mman.h> #endif #include <assert.h> #include <ctype.h> #include <err.h> #if TLS_API < 20160801 # include <fcntl.h> #endif #include <limits.h> #include <netdb.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <tls.h> #include <unistd.h> #include "http.h" #include "extern.h" #ifndef DEFAULT_CA_FILE # define DEFAULT_CA_FILE "/etc/ssl/cert.pem" #endif /* * A buffer for transferring HTTP/S data. */ struct httpxfer { char *hbuf; /* header transfer buffer */ size_t hbufsz; /* header buffer size */ int headok; /* header has been parsed */ char *bbuf; /* body transfer buffer */ size_t bbufsz; /* body buffer size */ int bodyok; /* body has been parsed */ char *headbuf; /* lookaside buffer for headers */ struct httphead *head; /* parsed headers */ size_t headsz; /* number of headers */ }; /* * An HTTP/S connection object. */ struct http { int fd; /* connected socket */ short port; /* port number */ struct source src; /* endpoint (raw) host */ char *path; /* path to request */ char *host; /* name of endpoint host */ struct tls *ctx; /* if TLS */ writefp writer; /* write function */ readfp reader; /* read function */ }; struct httpcfg { struct tls_config *tlscfg; }; static ssize_t dosysread(char *buf, size_t sz, const struct http *http) { ssize_t rc; rc = read(http->fd, buf, sz); if (rc < 0) warn("%s: read", http->src.ip); return (rc); } static ssize_t dosyswrite(const void *buf, size_t sz, const struct http *http) { ssize_t rc; rc = write(http->fd, buf, sz); if (rc < 0) warn("%s: write", http->src.ip); return(rc); } static ssize_t dotlsread(char *buf, size_t sz, const struct http *http) { ssize_t rc; do { rc = tls_read(http->ctx, buf, sz); } while (TLS_WANT_POLLIN == rc || TLS_WANT_POLLOUT == rc); if (rc < 0) warnx("%s: tls_read: %s", http->src.ip, tls_error(http->ctx)); return (rc); } static ssize_t dotlswrite(const void *buf, size_t sz, const struct http *http) { ssize_t rc; do { rc = tls_write(http->ctx, buf, sz); } while (TLS_WANT_POLLIN == rc || TLS_WANT_POLLOUT == rc); if (rc < 0) warnx("%s: tls_write: %s", http->src.ip, tls_error(http->ctx)); return (rc); } /* * Free the resources of an http_init() object. */ void http_uninit(struct httpcfg *p) { if (NULL == p) return; if (NULL != p->tlscfg) tls_config_free(p->tlscfg); free(p); } /* * Work around the "lazy-loading" problem in earlier versions of libtls. * In these systems, using tls_config_set_ca_file() would only cause the * file location to be copied. * It would then be used after the pledge and/or chroot. * We work around this by loading the file directly. */ #if TLS_API < 20160801 static int http_config_set_ca_file(struct httpcfg *p) { int fd, rc = 0; struct stat st; void *buf; if (-1 == (fd = open(DEFAULT_CA_FILE, O_RDONLY, 0))) { warn("%s", DEFAULT_CA_FILE); return(0); } else if (-1 == fstat(fd, &st)) { warn("%s", DEFAULT_CA_FILE); close(fd); return(0); } buf = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0); if (MAP_FAILED == buf) { warn("%s", DEFAULT_CA_FILE); close(fd); return(0); } if (-1 == tls_config_set_ca_mem(p->tlscfg, buf, st.st_size)) warn("%s: tls_config_set_ca_file", DEFAULT_CA_FILE); else rc = 1; munmap(buf, st.st_size); close(fd); return(rc); } #endif /* * This function allocates a configuration shared among multiple * connections. * It will generally be called once, then used in a series of * connections. * Returns the configuration object or NULL on errors. * A returned object must be freed with http_deinit(). */ struct httpcfg * http_init(void) { struct httpcfg *p; /* Can be called more than once. */ if (-1 == tls_init()) { warn("tls_init"); return (NULL); } if (NULL == (p = malloc(sizeof(struct httpcfg)))) { warn("calloc"); return (NULL); } else if (NULL == (p->tlscfg = tls_config_new())) { warn("tls_config_new"); goto err; } tls_config_set_protocols(p->tlscfg, TLS_PROTOCOLS_ALL); #if TLS_API < 20160801 if ( ! http_config_set_ca_file(p)) goto err; #else if (-1 == tls_config_set_ca_file(p->tlscfg, DEFAULT_CA_FILE)) { warn("tls_config_set_ca_file: %s", tls_config_error(p->tlscfg)); goto err; } #endif if (-1 == tls_config_set_ciphers(p->tlscfg, "compat")) { #if TLS_API < 20160801 warn("tls_config_set_ciphers"); #else warn("tls_config_set_ciphers: %s", tls_config_error(p->tlscfg)); #endif goto err; } return (p); err: http_uninit(p); return (NULL); } static ssize_t http_read(char *buf, size_t sz, const struct http *http) { ssize_t ssz, xfer; xfer = 0; do { if ((ssz = http->reader(buf, sz, http)) < 0) return (-1); if (0 == ssz) break; xfer += ssz; sz -= ssz; buf += ssz; } while (ssz > 0 && sz > 0); return (xfer); } static int http_write(const char *buf, size_t sz, const struct http *http) { ssize_t ssz, xfer; xfer = sz; while (sz > 0) { if ((ssz = http->writer(buf, sz, http)) < 0) return (-1); sz -= ssz; buf += (size_t)ssz; } return (xfer); } void http_disconnect(struct http *http) { int rc; if (NULL != http->ctx) { do { rc = tls_close(http->ctx); } while (TLS_WANT_POLLIN == rc || TLS_WANT_POLLOUT == rc); if (rc < 0) warnx("%s: tls_close: %s", http->src.ip, tls_error(http->ctx)); if (-1 == close(http->fd)) warn("%s: close", http->src.ip); tls_free(http->ctx); } else if (-1 != http->fd) { /* Non-TLS connection. */ if (-1 == close(http->fd)) warn("%s: close", http->src.ip); } http->fd = -1; http->ctx = NULL; } void http_free(struct http *http) { if (NULL == http) return; http_disconnect(http); free(http->host); free(http->path); free(http->src.ip); free(http); } struct http * http_alloc(struct httpcfg *cfg, const struct source *addrs, size_t addrsz, const char *host, short port, const char *path) { struct sockaddr_storage ss; int family, fd, c; socklen_t len; size_t cur, i = 0; struct http *http; /* Do this while we still have addresses to connect. */ again: if (i == addrsz) return (NULL); cur = i++; /* Convert to PF_INET or PF_INET6 address from string. */ memset(&ss, 0, sizeof(struct sockaddr_storage)); if (4 == addrs[cur].family) { family = PF_INET; ((struct sockaddr_in *)&ss)->sin_family = AF_INET; ((struct sockaddr_in *)&ss)->sin_port = htons(port); c = inet_pton(AF_INET, addrs[cur].ip, &((struct sockaddr_in *)&ss)->sin_addr); len = sizeof(struct sockaddr_in); } else if (6 == addrs[cur].family) { family = PF_INET6; ((struct sockaddr_in6 *)&ss)->sin6_family = AF_INET6; ((struct sockaddr_in6 *)&ss)->sin6_port = htons(port); c = inet_pton(AF_INET6, addrs[cur].ip, &((struct sockaddr_in6 *)&ss)->sin6_addr); len = sizeof(struct sockaddr_in6); } else { warnx("%s: unknown family", addrs[cur].ip); goto again; } if (c < 0) { warn("%s: inet_ntop", addrs[cur].ip); goto again; } else if (0 == c) { warnx("%s: inet_ntop", addrs[cur].ip); goto again; } /* Create socket and connect. */ fd = socket(family, SOCK_STREAM, 0); if (-1 == fd) { warn("%s: socket", addrs[cur].ip); goto again; } else if (-1 == connect(fd, (struct sockaddr *)&ss, len)) { warn("%s: connect", addrs[cur].ip); close(fd); goto again; } /* Allocate the communicator. */ http = calloc(1, sizeof(struct http)); if (NULL == http) { warn("calloc"); close(fd); return (NULL); } http->fd = fd; http->port = port; http->src.family = addrs[cur].family; http->src.ip = strdup(addrs[cur].ip); http->host = strdup(host); http->path = strdup(path); if (NULL == http->src.ip || NULL == http->host || NULL == http->path) { warn("strdup"); goto err; } /* If necessary, do our TLS setup. */ if (443 != port) { http->writer = dosyswrite; http->reader = dosysread; return (http); } http->writer = dotlswrite; http->reader = dotlsread; if (NULL == (http->ctx = tls_client())) { warn("tls_client"); goto err; } else if (-1 == tls_configure(http->ctx, cfg->tlscfg)) { warnx("%s: tls_configure: %s", http->src.ip, tls_error(http->ctx)); goto err; } if (0 != tls_connect_socket (http->ctx, http->fd, http->host)) { warnx("%s: tls_connect_socket: %s, %s", http->src.ip, http->host, tls_error(http->ctx)); goto err; } return (http); err: http_free(http); return (NULL); } struct httpxfer * http_open(const struct http *http, const void *p, size_t psz) { char *req; int c; struct httpxfer *trans; if (NULL == p) { c = asprintf(&req, "GET %s HTTP/1.0\r\n" "Host: %s\r\n" "\r\n", http->path, http->host); } else { c = asprintf(&req, "POST %s HTTP/1.0\r\n" "Host: %s\r\n" "Content-Length: %zu\r\n" "\r\n", http->path, http->host, psz); } if (-1 == c) { warn("asprintf"); return (NULL); } else if ( ! http_write(req, c, http)) { free(req); return (NULL); } else if (NULL != p && ! http_write(p, psz, http)) { free(req); return (NULL); } free(req); trans = calloc(1, sizeof(struct httpxfer)); if (NULL == trans) warn("calloc"); return (trans); } void http_close(struct httpxfer *x) { if (NULL == x) return; free(x->hbuf); free(x->bbuf); free(x->headbuf); free(x->head); free(x); } /* * Read the HTTP body from the wire. * If invoked multiple times, this will return the same pointer with the * same data (or NULL, if the original invocation returned NULL). * Returns NULL if read or allocation errors occur. * You must not free the returned pointer. */ char * http_body_read(const struct http *http, struct httpxfer *trans, size_t *sz) { char buf[BUFSIZ]; ssize_t ssz; void *pp; size_t szp; if (NULL == sz) sz = &szp; /* Have we already parsed this? */ if (trans->bodyok > 0) { *sz = trans->bbufsz; return (trans->bbuf); } else if (trans->bodyok < 0) return (NULL); *sz = 0; trans->bodyok = -1; do { /* If less than sizeof(buf), at EOF. */ if ((ssz = http_read(buf, sizeof(buf), http)) < 0) return (NULL); else if (0 == ssz) break; pp = realloc(trans->bbuf, trans->bbufsz + ssz); if (NULL == pp) { warn("realloc"); return (NULL); } trans->bbuf = pp; memcpy(trans->bbuf + trans->bbufsz, buf, ssz); trans->bbufsz += ssz; } while (sizeof(buf) == ssz); trans->bodyok = 1; *sz = trans->bbufsz; return (trans->bbuf); } struct httphead * http_head_get(const char *v, struct httphead *h, size_t hsz) { size_t i; for (i = 0; i < hsz; i++) { if (strcmp(h[i].key, v)) continue; return (&h[i]); } return (NULL); } /* * Look through the headers and determine our HTTP code. * This will return -1 on failure, otherwise the code. */ int http_head_status(const struct http *http, struct httphead *h, size_t sz) { int rc; unsigned int code; struct httphead *st; if (NULL == (st = http_head_get("Status", h, sz))) { warnx("%s: no status header", http->src.ip); return (-1); } rc = sscanf(st->val, "%*s %u %*s", &code); if (rc < 0) { warn("sscanf"); return (-1); } else if (1 != rc) { warnx("%s: cannot convert status header", http->src.ip); return (-1); } return (code); } /* * Parse headers from the transfer. * Malformed headers are skipped. * A special "Status" header is added for the HTTP status line. * This can only happen once http_head_read has been called with * success. * This can be invoked multiple times: it will only parse the headers * once and after that it will just return the cache. * You must not free the returned pointer. * If the original header parse failed, or if memory allocation fails * internally, this returns NULL. */ struct httphead * http_head_parse(const struct http *http, struct httpxfer *trans, size_t *sz) { size_t hsz, szp; struct httphead *h; char *cp, *ep, *ccp, *buf; if (NULL == sz) sz = &szp; /* * If we've already parsed the headers, return the * previously-parsed buffer now. * If we have errors on the stream, return NULL now. */ if (NULL != trans->head) { *sz = trans->headsz; return (trans->head); } else if (trans->headok <= 0) return (NULL); if (NULL == (buf = strdup(trans->hbuf))) { warn("strdup"); return (NULL); } hsz = 0; cp = buf; do { if (NULL != (cp = strstr(cp, "\r\n"))) cp += 2; hsz++; } while (NULL != cp); /* * Allocate headers, then step through the data buffer, parsing * out headers as we have them. * We know at this point that the buffer is nil-terminated in * the usual way. */ h = calloc(hsz, sizeof(struct httphead)); if (NULL == h) { warn("calloc"); free(buf); return (NULL); } *sz = hsz; hsz = 0; cp = buf; do { if (NULL != (ep = strstr(cp, "\r\n"))) { *ep = '\0'; ep += 2; } if (0 == hsz) { h[hsz].key = "Status"; h[hsz++].val = cp; continue; } /* Skip bad headers. */ if (NULL == (ccp = strchr(cp, ':'))) { warnx("%s: header without separator", http->src.ip); continue; } *ccp++ = '\0'; while (isspace((int)*ccp)) ccp++; h[hsz].key = cp; h[hsz++].val = ccp; } while (NULL != (cp = ep)); trans->headbuf = buf; trans->head = h; trans->headsz = hsz; return (h); } /* * Read the HTTP headers from the wire. * If invoked multiple times, this will return the same pointer with the * same data (or NULL, if the original invocation returned NULL). * Returns NULL if read or allocation errors occur. * You must not free the returned pointer. */ char * http_head_read(const struct http *http, struct httpxfer *trans, size_t *sz) { char buf[BUFSIZ]; ssize_t ssz; char *ep; void *pp; size_t szp; if (NULL == sz) sz = &szp; /* Have we already parsed this? */ if (trans->headok > 0) { *sz = trans->hbufsz; return (trans->hbuf); } else if (trans->headok < 0) return (NULL); *sz = 0; ep = NULL; trans->headok = -1; /* * Begin by reading by BUFSIZ blocks until we reach the header * termination marker (two CRLFs). * We might read into our body, but that's ok: we'll copy out * the body parts into our body buffer afterward. */ do { /* If less than sizeof(buf), at EOF. */ if ((ssz = http_read(buf, sizeof(buf), http)) < 0) return (NULL); else if (0 == ssz) break; pp = realloc(trans->hbuf, trans->hbufsz + ssz); if (NULL == pp) { warn("realloc"); return (NULL); } trans->hbuf = pp; memcpy(trans->hbuf + trans->hbufsz, buf, ssz); trans->hbufsz += ssz; /* Search for end of headers marker. */ ep = memmem(trans->hbuf, trans->hbufsz, "\r\n\r\n", 4); } while (NULL == ep && sizeof(buf) == ssz); if (NULL == ep) { warnx("%s: partial transfer", http->src.ip); return (NULL); } *ep = '\0'; /* * The header data is invalid if it has any binary characters in * it: check that now. * This is important because we want to guarantee that all * header keys and pairs are properly nil-terminated. */ if (strlen(trans->hbuf) != (uintptr_t)(ep - trans->hbuf)) { warnx("%s: binary data in header", http->src.ip); return (NULL); } /* * Copy remaining buffer into body buffer. */ ep += 4; trans->bbufsz = (trans->hbuf + trans->hbufsz) - ep; trans->bbuf = malloc(trans->bbufsz); if (NULL == trans->bbuf) { warn("malloc"); return (NULL); } memcpy(trans->bbuf, ep, trans->bbufsz); trans->headok = 1; *sz = trans->hbufsz; return (trans->hbuf); } void http_get_free(struct httpget *g) { if (NULL == g) return; http_close(g->xfer); http_free(g->http); free(g); } struct httpget * http_get(struct httpcfg *cfg, const struct source *addrs, size_t addrsz, const char *domain, short port, const char *path, const void *post, size_t postsz) { struct http *h; struct httpxfer *x; struct httpget *g; struct httphead *head; size_t headsz, bodsz, headrsz; int code; char *bod, *headr; h = http_alloc(cfg, addrs, addrsz, domain, port, path); if (NULL == h) return (NULL); if (NULL == (x = http_open(h, post, postsz))) { http_free(h); return (NULL); } else if (NULL == (headr = http_head_read(h, x, &headrsz))) { http_close(x); http_free(h); return (NULL); } else if (NULL == (bod = http_body_read(h, x, &bodsz))) { http_close(x); http_free(h); return (NULL); } http_disconnect(h); if (NULL == (head = http_head_parse(h, x, &headsz))) { http_close(x); http_free(h); return (NULL); } else if ((code = http_head_status(h, head, headsz)) < 0) { http_close(x); http_free(h); return (NULL); } if (NULL == (g = calloc(1, sizeof(struct httpget)))) { warn("calloc"); http_close(x); http_free(h); return (NULL); } g->headpart = headr; g->headpartsz = headrsz; g->bodypart = bod; g->bodypartsz = bodsz; g->head = head; g->headsz = headsz; g->code = code; g->xfer = x; g->http = h; return (g); } #if 0 int main(void) { struct httpget *g; struct httphead *httph; size_t i, httphsz; struct source addrs[2]; size_t addrsz; #if 0 addrs[0].ip = "127.0.0.1"; addrs[0].family = 4; addrsz = 1; #else addrs[0].ip = "2a00:1450:400a:806::2004"; addrs[0].family = 6; addrs[1].ip = "193.135.3.123"; addrs[1].family = 4; addrsz = 2; #endif #if 0 g = http_get(addrs, addrsz, "localhost", 80, "/index.html"); #else g = http_get(addrs, addrsz, "www.google.ch", 80, "/index.html", NULL, 0); #endif if (NULL == g) errx(EXIT_FAILURE, "http_get"); httph = http_head_parse(g->http, g->xfer, &httphsz); warnx("code: %d", g->code); for (i = 0; i < httphsz; i++) warnx("head: [%s]=[%s]", httph[i].key, httph[i].val); http_get_free(g); return (EXIT_SUCCESS); } #endif
isc
cliffordwolf/picorv32
scripts/cxxdemo/syscalls.c
4
1805
// An extremely minimalist syscalls.c for newlib // Based on riscv newlib libgloss/riscv/sys_*.c // Written by Clifford Wolf. #include <sys/stat.h> #include <unistd.h> #include <errno.h> #define UNIMPL_FUNC(_f) ".globl " #_f "\n.type " #_f ", @function\n" #_f ":\n" asm ( ".text\n" ".align 2\n" UNIMPL_FUNC(_open) UNIMPL_FUNC(_openat) UNIMPL_FUNC(_lseek) UNIMPL_FUNC(_stat) UNIMPL_FUNC(_lstat) UNIMPL_FUNC(_fstatat) UNIMPL_FUNC(_isatty) UNIMPL_FUNC(_access) UNIMPL_FUNC(_faccessat) UNIMPL_FUNC(_link) UNIMPL_FUNC(_unlink) UNIMPL_FUNC(_execve) UNIMPL_FUNC(_getpid) UNIMPL_FUNC(_fork) UNIMPL_FUNC(_kill) UNIMPL_FUNC(_wait) UNIMPL_FUNC(_times) UNIMPL_FUNC(_gettimeofday) UNIMPL_FUNC(_ftime) UNIMPL_FUNC(_utime) UNIMPL_FUNC(_chown) UNIMPL_FUNC(_chmod) UNIMPL_FUNC(_chdir) UNIMPL_FUNC(_getcwd) UNIMPL_FUNC(_sysconf) "j unimplemented_syscall\n" ); void unimplemented_syscall() { const char *p = "Unimplemented system call called!\n"; while (*p) *(volatile int*)0x10000000 = *(p++); asm volatile ("ebreak"); __builtin_unreachable(); } ssize_t _read(int file, void *ptr, size_t len) { // always EOF return 0; } ssize_t _write(int file, const void *ptr, size_t len) { const void *eptr = ptr + len; while (ptr != eptr) *(volatile int*)0x10000000 = *(char*)(ptr++); return len; } int _close(int file) { // close is called before _exit() return 0; } int _fstat(int file, struct stat *st) { // fstat is called during libc startup errno = ENOENT; return -1; } void *_sbrk(ptrdiff_t incr) { extern unsigned char _end[]; // Defined by linker static unsigned long heap_end; if (heap_end == 0) heap_end = (long)_end; heap_end += incr; return (void *)(heap_end - incr); } void _exit(int exit_status) { asm volatile ("ebreak"); __builtin_unreachable(); }
isc
bnoordhuis/suv
deps/libuv/test/test-loop-handles.c
73
9821
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /* Tests commented out with XXX are ones that are failing on Linux */ /* * Purpose of this test is to check semantics of starting and stopping * prepare, check and idle watchers. * * - A watcher must be able to safely stop or close itself; * - Once a watcher is stopped or closed its callback should never be called. * - If a watcher is closed, it is implicitly stopped and its close_cb should * be called exactly once. * - A watcher can safely start and stop other watchers of the same type. * - Prepare and check watchers are called once per event loop iterations. * - All active idle watchers are queued when the event loop has no more work * to do. This is done repeatedly until all idle watchers are inactive. * - If a watcher starts another watcher of the same type its callback is not * immediately queued. For check and prepare watchers, that means that if * a watcher makes another of the same type active, it'll not be called until * the next event loop iteration. For idle. watchers this means that the * newly activated idle watcher might not be queued immediately. * - Prepare, check, idle watchers keep the event loop alive even when they're * not active. * * This is what the test globally does: * * - prepare_1 is always active and counts event loop iterations. It also * creates and starts prepare_2 every other iteration. Finally it verifies * that no idle watchers are active before polling. * - prepare_2 is started by prepare_1 every other iteration. It immediately * stops itself. It verifies that a watcher is not queued immediately * if created by another watcher of the same type. * - There's a check watcher that stops the event loop after a certain number * of iterations. It starts a varying number of idle_1 watchers. * - Idle_1 watchers stop themselves after being called a few times. All idle_1 * watchers try to start the idle_2 watcher if it is not already started or * awaiting its close callback. * - The idle_2 watcher always exists but immediately closes itself after * being started by a check_1 watcher. It verifies that a watcher is * implicitly stopped when closed, and that a watcher can close itself * safely. * - There is a repeating timer. It does not keep the event loop alive * (ev_unref) but makes sure that the loop keeps polling the system for * events. */ #include "uv.h" #include "task.h" #include <math.h> #define IDLE_COUNT 7 #define ITERATIONS 21 #define TIMEOUT 100 static uv_prepare_t prepare_1_handle; static uv_prepare_t prepare_2_handle; static uv_check_t check_handle; static uv_idle_t idle_1_handles[IDLE_COUNT]; static uv_idle_t idle_2_handle; static uv_timer_t timer_handle; static int loop_iteration = 0; static int prepare_1_cb_called = 0; static int prepare_1_close_cb_called = 0; static int prepare_2_cb_called = 0; static int prepare_2_close_cb_called = 0; static int check_cb_called = 0; static int check_close_cb_called = 0; static int idle_1_cb_called = 0; static int idle_1_close_cb_called = 0; static int idles_1_active = 0; static int idle_2_cb_called = 0; static int idle_2_close_cb_called = 0; static int idle_2_cb_started = 0; static int idle_2_is_active = 0; static void timer_cb(uv_timer_t* handle, int status) { ASSERT(handle == &timer_handle); ASSERT(status == 0); } static void idle_2_close_cb(uv_handle_t* handle) { LOG("IDLE_2_CLOSE_CB\n"); ASSERT(handle == (uv_handle_t*)&idle_2_handle); ASSERT(idle_2_is_active); idle_2_close_cb_called++; idle_2_is_active = 0; } static void idle_2_cb(uv_idle_t* handle, int status) { LOG("IDLE_2_CB\n"); ASSERT(handle == &idle_2_handle); ASSERT(status == 0); idle_2_cb_called++; uv_close((uv_handle_t*)handle, idle_2_close_cb); } static void idle_1_cb(uv_idle_t* handle, int status) { int r; LOG("IDLE_1_CB\n"); ASSERT(handle != NULL); ASSERT(status == 0); ASSERT(idles_1_active > 0); /* Init idle_2 and make it active */ if (!idle_2_is_active && !uv_is_closing((uv_handle_t*)&idle_2_handle)) { r = uv_idle_init(uv_default_loop(), &idle_2_handle); ASSERT(r == 0); r = uv_idle_start(&idle_2_handle, idle_2_cb); ASSERT(r == 0); idle_2_is_active = 1; idle_2_cb_started++; } idle_1_cb_called++; if (idle_1_cb_called % 5 == 0) { r = uv_idle_stop((uv_idle_t*)handle); ASSERT(r == 0); idles_1_active--; } } static void idle_1_close_cb(uv_handle_t* handle) { LOG("IDLE_1_CLOSE_CB\n"); ASSERT(handle != NULL); idle_1_close_cb_called++; } static void prepare_1_close_cb(uv_handle_t* handle) { LOG("PREPARE_1_CLOSE_CB"); ASSERT(handle == (uv_handle_t*)&prepare_1_handle); prepare_1_close_cb_called++; } static void check_close_cb(uv_handle_t* handle) { LOG("CHECK_CLOSE_CB\n"); ASSERT(handle == (uv_handle_t*)&check_handle); check_close_cb_called++; } static void prepare_2_close_cb(uv_handle_t* handle) { LOG("PREPARE_2_CLOSE_CB\n"); ASSERT(handle == (uv_handle_t*)&prepare_2_handle); prepare_2_close_cb_called++; } static void check_cb(uv_check_t* handle, int status) { int i, r; LOG("CHECK_CB\n"); ASSERT(handle == &check_handle); ASSERT(status == 0); if (loop_iteration < ITERATIONS) { /* Make some idle watchers active */ for (i = 0; i < 1 + (loop_iteration % IDLE_COUNT); i++) { r = uv_idle_start(&idle_1_handles[i], idle_1_cb); ASSERT(r == 0); idles_1_active++; } } else { /* End of the test - close all handles */ uv_close((uv_handle_t*)&prepare_1_handle, prepare_1_close_cb); uv_close((uv_handle_t*)&check_handle, check_close_cb); uv_close((uv_handle_t*)&prepare_2_handle, prepare_2_close_cb); for (i = 0; i < IDLE_COUNT; i++) { uv_close((uv_handle_t*)&idle_1_handles[i], idle_1_close_cb); } /* This handle is closed/recreated every time, close it only if it is */ /* active.*/ if (idle_2_is_active) { uv_close((uv_handle_t*)&idle_2_handle, idle_2_close_cb); } } check_cb_called++; } static void prepare_2_cb(uv_prepare_t* handle, int status) { int r; LOG("PREPARE_2_CB\n"); ASSERT(handle == &prepare_2_handle); ASSERT(status == 0); /* prepare_2 gets started by prepare_1 when (loop_iteration % 2 == 0), */ /* and it stops itself immediately. A started watcher is not queued */ /* until the next round, so when this callback is made */ /* (loop_iteration % 2 == 0) cannot be true. */ ASSERT(loop_iteration % 2 != 0); r = uv_prepare_stop((uv_prepare_t*)handle); ASSERT(r == 0); prepare_2_cb_called++; } static void prepare_1_cb(uv_prepare_t* handle, int status) { int r; LOG("PREPARE_1_CB\n"); ASSERT(handle == &prepare_1_handle); ASSERT(status == 0); if (loop_iteration % 2 == 0) { r = uv_prepare_start(&prepare_2_handle, prepare_2_cb); ASSERT(r == 0); } prepare_1_cb_called++; loop_iteration++; printf("Loop iteration %d of %d.\n", loop_iteration, ITERATIONS); } TEST_IMPL(loop_handles) { int i; int r; r = uv_prepare_init(uv_default_loop(), &prepare_1_handle); ASSERT(r == 0); r = uv_prepare_start(&prepare_1_handle, prepare_1_cb); ASSERT(r == 0); r = uv_check_init(uv_default_loop(), &check_handle); ASSERT(r == 0); r = uv_check_start(&check_handle, check_cb); ASSERT(r == 0); /* initialize only, prepare_2 is started by prepare_1_cb */ r = uv_prepare_init(uv_default_loop(), &prepare_2_handle); ASSERT(r == 0); for (i = 0; i < IDLE_COUNT; i++) { /* initialize only, idle_1 handles are started by check_cb */ r = uv_idle_init(uv_default_loop(), &idle_1_handles[i]); ASSERT(r == 0); } /* don't init or start idle_2, both is done by idle_1_cb */ /* the timer callback is there to keep the event loop polling */ /* unref it as it is not supposed to keep the loop alive */ r = uv_timer_init(uv_default_loop(), &timer_handle); ASSERT(r == 0); r = uv_timer_start(&timer_handle, timer_cb, TIMEOUT, TIMEOUT); ASSERT(r == 0); uv_unref((uv_handle_t*)&timer_handle); r = uv_run(uv_default_loop(), UV_RUN_DEFAULT); ASSERT(r == 0); ASSERT(loop_iteration == ITERATIONS); ASSERT(prepare_1_cb_called == ITERATIONS); ASSERT(prepare_1_close_cb_called == 1); ASSERT(prepare_2_cb_called == floor(ITERATIONS / 2.0)); ASSERT(prepare_2_close_cb_called == 1); ASSERT(check_cb_called == ITERATIONS); ASSERT(check_close_cb_called == 1); /* idle_1_cb should be called a lot */ ASSERT(idle_1_close_cb_called == IDLE_COUNT); ASSERT(idle_2_close_cb_called == idle_2_cb_started); ASSERT(idle_2_is_active == 0); MAKE_VALGRIND_HAPPY(); return 0; }
isc
ennis/autograph-pipelines
src/Engine/DebugOverlay.cpp
1
22413
#include <autograph/Engine/CVar.h> #include <autograph/Engine/DebugOverlay.h> #include <autograph/Engine/ImGuiUtils.h> #include <autograph/Engine/ImageUtils.h> #include <autograph/Engine/RenderUtils.h> #include <autograph/Engine/Shader.h> #include <autograph/Engine/imgui.h> #include <autograph/Gfx/GfxContext.h> #include <autograph/Gfx/Draw.h> #include <autograph/Gfx/GLHandle.h> #include <autograph/Gfx/Sampler.h> #include <autograph/Core/Support/Debug.h> #include <autograph/Core/Support/FileDialog.h> #include <autograph/Core/Support/ProjectRoot.h> #include <cinttypes> namespace ag { static const char *imageFileFilters = "png,jpg,jpeg,bmp,tga,psd,gif"; static constexpr Sampler::Desc nearestClampToEdge = Sampler::Desc{gl::NEAREST, gl::NEAREST, gl::CLAMP_TO_EDGE, gl::CLAMP_TO_EDGE, gl::CLAMP_TO_EDGE }; struct DebugOverlayGlobals { GPUPipeline textureViewShader = GPUPipeline{GPUPipelineType::Graphics, "shaders/default.lua:textureView"}; Sampler textureViewSampler; }; static DebugOverlayGlobals &getDebugGlobals() { static DebugOverlayGlobals g; static bool initialized = false; if (!initialized) { g.textureViewSampler = Sampler{ nearestClampToEdge }; initialized = true; } return g; } static const char *getInternalFormatName(gl::GLenum internalFormat) { switch (internalFormat) { case gl::R8: return "R8"; case gl::R8_SNORM: return "R8_SNORM"; case gl::R16: return "R16"; case gl::R16_SNORM: return "R16_SNORM"; case gl::RG8: return "RG8"; case gl::RG8_SNORM: return "RG8_SNORM"; case gl::RG16: return "RG16"; case gl::RG16_SNORM: return "RG16_SNORM"; case gl::R3_G3_B2: return "R3_G3_B2"; case gl::RGB4: return "RGB4"; case gl::RGB5: return "RGB5"; case gl::RGB8: return "RGB8"; case gl::RGB8_SNORM: return "RGB8_SNORM"; case gl::RGB10: return "RGB10"; case gl::RGB12: return "RGB12"; case gl::RGB16_SNORM: return "RGB16_SNORM"; case gl::RGBA2: return "RGBA2"; case gl::RGBA4: return "RGBA4"; case gl::RGB5_A1: return "RGB5_A1"; case gl::RGBA8: return "RGBA8"; case gl::RGBA8_SNORM: return "RGBA8_SNORM"; case gl::RGB10_A2: return "RGB10_A2"; case gl::RGB10_A2UI: return "RGB10_A2UI"; case gl::RGBA12: return "RGBA12"; case gl::RGBA16: return "RGBA16"; case gl::SRGB8: return "SRGB8"; case gl::SRGB8_ALPHA8: return "SRGB8_ALPHA8"; case gl::R16F: return "R16F"; case gl::RG16F: return "RG16F"; case gl::RGB16F: return "RGB16F"; case gl::RGBA16F: return "RGBA16F"; case gl::R32F: return "R32F"; case gl::RG32F: return "RG32F"; case gl::RGB32F: return "RGB32F"; case gl::RGBA32F: return "RGBA32F"; case gl::R11F_G11F_B10F: return "R11F_G11F_B10F"; case gl::RGB9_E5: return "RGB9_E5"; case gl::R8I: return "R8I"; case gl::R8UI: return "R8UI"; case gl::R16I: return "R16I"; case gl::R16UI: return "R16UI"; case gl::R32I: return "R32I"; case gl::R32UI: return "R32UI"; case gl::RG8I: return "RG8I"; case gl::RG8UI: return "RG8UI"; case gl::RG16I: return "RG16I"; case gl::RG16UI: return "RG16UI"; case gl::RG32I: return "RG32I"; case gl::RG32UI: return "RG32UI"; case gl::RGB8I: return "RGB8I"; case gl::RGB8UI: return "RGB8UI"; case gl::RGB16I: return "RGB16I"; case gl::RGB16UI: return "RGB16UI"; case gl::RGB32I: return "RGB32I"; case gl::RGB32UI: return "RGB32UI"; case gl::RGBA8I: return "RGBA8I"; case gl::RGBA8UI: return "RGBA8UI"; case gl::RGBA16I: return "RGBA16I"; case gl::RGBA16UI: return "RGBA16UI"; case gl::RGBA32I: return "RGBA32I"; case gl::RGBA32UI: return "RGBA32UI"; case gl::DEPTH_COMPONENT16: return "DEPTH_COMPONENT16"; case gl::DEPTH_COMPONENT24: return "DEPTH_COMPONENT24"; case gl::DEPTH_COMPONENT32: return "DEPTH_COMPONENT32"; case gl::DEPTH_COMPONENT32F: return "DEPTH_COMPONENT32F"; case gl::DEPTH24_STENCIL8: return "DEPTH24_STENCIL8"; case gl::DEPTH32F_STENCIL8: return "DEPTH32F_STENCIL8"; case gl::STENCIL_INDEX8: return "STENCIL_INDEX8"; case gl::COMPRESSED_RED: return "COMPRESSED_RED"; case gl::COMPRESSED_RG: return "COMPRESSED_RG"; case gl::COMPRESSED_RGB: return "COMPRESSED_RGB"; case gl::COMPRESSED_RGBA: return "COMPRESSED_RGBA"; case gl::COMPRESSED_SRGB: return "COMPRESSED_SRGB"; case gl::COMPRESSED_SRGB_ALPHA: return "COMPRESSED_SRGB_ALPHA"; case gl::COMPRESSED_RED_RGTC1: return "COMPRESSED_RED_RGTC1"; case gl::COMPRESSED_SIGNED_RED_RGTC1: return "COMPRESSED_SIGNED_RED_RGTC1"; case gl::COMPRESSED_RG_RGTC2: return "COMPRESSED_RG_RGTC2"; case gl::COMPRESSED_SIGNED_RG_RGTC2: return "COMPRESSED_SIGNED_RG_RGTC2"; case gl::COMPRESSED_RGBA_BPTC_UNORM: return "COMPRESSED_RGBA_BPTC_UNORM"; case gl::COMPRESSED_SRGB_ALPHA_BPTC_UNORM: return "COMPRESSED_SRGB_ALPHA_BPTC_UNORM"; case gl::COMPRESSED_RGB_BPTC_SIGNED_FLOAT: return "COMPRESSED_RGB_BPTC_SIGNED_FLOAT"; case gl::COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT: return "COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT"; case gl::COMPRESSED_RGB_S3TC_DXT1_EXT: return "COMPRESSED_RGB_S3TC_DXT1_EXT"; case gl::COMPRESSED_SRGB_S3TC_DXT1_EXT: return "COMPRESSED_SRGB_S3TC_DXT1_EXT"; case gl::COMPRESSED_RGBA_S3TC_DXT1_EXT: return "COMPRESSED_RGBA_S3TC_DXT1_EXT"; case gl::COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT: return "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; case gl::COMPRESSED_RGBA_S3TC_DXT3_EXT: return "COMPRESSED_RGBA_S3TC_DXT3_EXT"; case gl::COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT: return "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; case gl::COMPRESSED_RGBA_S3TC_DXT5_EXT: return "COMPRESSED_RGBA_S3TC_DXT5_EXT"; case gl::COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT: return "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; default: return "<unknown GL internal format>"; } } static ImageFormat GLInternalFormatToImageFormat(gl::GLenum glfmt) { switch (glfmt) { case gl::SRGB8: return ImageFormat::R8G8B8_SRGB; case gl::SRGB8_ALPHA8: return ImageFormat::R8G8B8A8_SRGB; case gl::RGBA16F: return ImageFormat::R16G16B16A16_SFLOAT; case gl::RG16F: return ImageFormat::R16G16_SFLOAT; default: return ImageFormat::R8G8B8A8_SRGB; } } static void beginFixedTooltip(const char *id) { ImGui::PushStyleColor(ImGuiCol_WindowBg, ImGui::GetStyle().Colors[ImGuiCol_PopupBg]); ImGui::Begin(id, nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_ShowBorders | ImGuiWindowFlags_NoResize); } static void endFixedTooltip() { ImGui::End(); ImGui::PopStyleColor(); } static void texturePreview(gl::GLuint textureObj, int w, int h, float lod, int xoffset, int yoffset, float zoomLevel, bool mirror = false, float range_min = 0.0f, float range_max = 1.0f) { ImGui::Dummy(ImVec2{(float)w, (float)h}); auto pos = ImGui::GetItemRectMin(); auto size = ImGui::GetItemRectSize(); gui::customRendering([=](const ImDrawList *parentList, const ImDrawCmd *cmd) { auto& fb = getGfxContext().getDefaultFramebuffer(); auto fb_width = fb.width(); auto fb_height = fb.height(); float uv_l = (float)xoffset / (float)w; float uv_t = 1.0f / zoomLevel; float uv_r = 1.0f / zoomLevel; float uv_b = (float)yoffset / (float)h; if (mirror) std::swap(uv_t, uv_b); ag::drawRect(fb, pos.x, pos.y, pos.x + size.x, pos.y + size.y, uv_l, uv_t, uv_r, uv_b, getDebugGlobals().textureViewShader, bind::scissor(0, (int)cmd->ClipRect.x, (int)(fb_height - cmd->ClipRect.w), (int)(cmd->ClipRect.z - cmd->ClipRect.x), (int)(cmd->ClipRect.w - cmd->ClipRect.y)), bind::texture(0, textureObj, getDebugGlobals().textureViewSampler.object()), bind::uniform_float("uLod", lod), bind::uniform_vec2("uRange", vec2(range_min, range_max)), bind::uniform_vec4("uBorder", vec4(0.1f, 0.1f, 0.1f, 1.0f))); }); } static void GLTextureViewWindow(gl::GLuint textureObj, int w, int h, gl::GLenum internalFormat, bool &opened) { auto internalFormatName = getInternalFormatName(internalFormat); auto windowName = fmt::format("Texture object {} ({}x{} {})", textureObj, w, h, internalFormatName); if (ImGui::Begin(windowName.c_str(), &opened, ImGuiWindowFlags_MenuBar)) { // ImGui::Image(reinterpret_cast<ImTextureID>(textureObj), ImVec2{ (float)w, // (float)h }); float range_min = ImGui::GetStateStorage()->GetFloat(ImGui::GetID("range_min"), 0.0f); float range_max = ImGui::GetStateStorage()->GetFloat(ImGui::GetID("range_max"), 1.0f); float zoomLevel = ImGui::GetStateStorage()->GetFloat(ImGui::GetID("zoom_level"), 1.0f); bool mirror = ImGui::GetStateStorage()->GetBool(ImGui::GetID("mirror"), false); int xoff = ImGui::GetStateStorage()->GetInt(ImGui::GetID("xoff"), 0); int yoff = ImGui::GetStateStorage()->GetInt(ImGui::GetID("yoff"), 0); texturePreview(textureObj, w, h, 1.0f, xoff, yoff, zoomLevel, mirror, range_min, range_max); vec4 pixel; int mx, my; bool hovered = false; if (ImGui::IsItemHovered()) { hovered = true; auto pos = ImGui::GetMousePos(); auto ref = ImGui::GetItemRectMin(); mx = glm::clamp((int)(pos.x - ref.x), 0, w - 1); my = glm::clamp((int)(pos.y - ref.y), 0, h - 1); // TODO handle integer textures gl::GetTextureSubImage(textureObj, 0, mx, my, 0, 1, 1, 1, gl::RGBA, gl::FLOAT, 4 * 4, &pixel); } if (ImGui::BeginMenuBar()) { if (ImGui::Button(ICON_FA_SEARCH_MINUS)) { zoomLevel /= 2; } ImGui::SameLine(); if (ImGui::Button(ICON_FA_SEARCH_PLUS)) { zoomLevel *= 2; } ImGui::SameLine(); if (ImGui::Button(ICON_FA_ARROWS_ALT)) { zoomLevel = 1.0f; } ImGui::SameLine(); ImGui::Checkbox("Mirror", &mirror); ImGui::SameLine(); ImGui::PushItemWidth(130.0f); float zoomLevelPercent = zoomLevel * 100.0f; ImGui::SliderFloat("Zoom", &zoomLevelPercent, 1.0f, 400.0f, "%g %%"); zoomLevel = zoomLevelPercent / 100.0f; ImGui::SameLine(); ImGui::SliderFloat("Min", &range_min, 0.0f, 1.0f); ImGui::SameLine(); ImGui::SliderFloat("Max", &range_max, 0.0f, 1.0f); ImGui::PopItemWidth(); ImGui::SameLine(); if (hovered) { ImGui::PushItemWidth(-1.0f); ImGui::Text("%05i,%05i => [%.03f, %.03f, %.03f, %.03f]", mx, my, pixel.r, pixel.g, pixel.b, pixel.a); ImGui::PopItemWidth(); } ImGui::EndMenuBar(); } ImGui::GetStateStorage()->SetBool(ImGui::GetID("mirror"), mirror); ImGui::GetStateStorage()->SetFloat(ImGui::GetID("range_min"), range_min); ImGui::GetStateStorage()->SetFloat(ImGui::GetID("range_max"), range_max); ImGui::GetStateStorage()->SetFloat(ImGui::GetID("zoom_level"), zoomLevel); ImGui::GetStateStorage()->SetInt(ImGui::GetID("xoff"), xoff); ImGui::GetStateStorage()->SetInt(ImGui::GetID("yoff"), yoff); } ImGui::End(); } static void saveGLTexture(const char *path, gl::GLuint textureObj, int w, int h, gl::GLenum internalFormat) { ImageFormat fmt; gl::GLenum extFormat; gl::GLenum components; int size; switch (internalFormat) { case gl::RGBA16F: fmt = ImageFormat::R16G16B16A16_SFLOAT; extFormat = gl::HALF_FLOAT; components = gl::RGBA; size = 8; break; case gl::RG16F: fmt = ImageFormat::R16G16_SFLOAT; extFormat = gl::HALF_FLOAT; components = gl::RG; size = 4; break; case gl::RGBA8_SNORM: fmt = ImageFormat::R8G8B8A8_SNORM; extFormat = gl::UNSIGNED_INT_8_8_8_8_REV; components = gl::RGBA; size = 4; break; case gl::RGBA8: fmt = ImageFormat::R8G8B8A8_UNORM; extFormat = gl::UNSIGNED_INT_8_8_8_8_REV; components = gl::RGBA; size = 4; break; case gl::SRGB8_ALPHA8: fmt = ImageFormat::R8G8B8A8_SRGB; extFormat = gl::UNSIGNED_INT_8_8_8_8_REV; components = gl::RGBA; size = 4; break; default: errorMessage("saveGLTexture: texture format not supported ({})", getInternalFormatName(internalFormat)); return; } // allocate space for image auto bufsize = w * h * size; std::vector<char> pixels(bufsize); gl::GetTextureSubImage(textureObj, 0, 0, 0, 0, w, h, 1, components, extFormat, bufsize, pixels.data()); saveImageByPath(path, pixels.data(), w, h, fmt, fmt); } static void GLTextureGUI(gl::GLuint textureObj) { int w, h; gl::GLint internalFormat; gl::GetTextureLevelParameteriv(textureObj, 0, gl::TEXTURE_WIDTH, &w); gl::GetTextureLevelParameteriv(textureObj, 0, gl::TEXTURE_HEIGHT, &h); gl::GetTextureLevelParameteriv(textureObj, 0, gl::TEXTURE_INTERNAL_FORMAT, &internalFormat); auto imguiState = ImGui::GetStateStorage(); auto id = ImGui::GetID("texview"); bool opened = imguiState->GetBool(id); if (ImGui::Button("Toggle view texture")) { opened = true; } if (opened) { GLTextureViewWindow(textureObj, w, h, internalFormat, opened); } imguiState->SetBool(id, opened); if (ImGui::Button("Load texture...")) { auto file = openFileDialog(imageFileFilters, getProjectRootDirectory().c_str()); if (file) { try { auto img = loadImage(file->c_str()); if (img.desc.width == w && img.desc.height == h) { // dimensions match, continue // as usual, let OpenGL do the pixel conversion gl::TextureSubImage2D(textureObj, 0, 0, 0, w, h, gl::RGBA, gl::UNSIGNED_INT_8_8_8_8, img.data.get()); } else { errorMessage("Error loading texture: mismatched dimensions ({}x{})", img.desc.width, img.desc.height); } } catch (std::exception &e) { errorMessage("Error loading image file: {}", e.what()); } } } ImGui::SameLine(); if (ImGui::Button("Save texture...")) { auto file = saveFileDialog(imageFileFilters, getProjectRootDirectory().c_str()); if (file) { try { // allocate space for image saveGLTexture(file->c_str(), textureObj, w, h, internalFormat); } catch (std::exception &e) { errorMessage("Error saving image file: {}", e.what()); } } } // auto& defaultFbo = gl::getDefaultFramebuffer(); // int screenW = defaultFbo.width(); // int screenH = defaultFbo.height(); // getRenderUtils().drawSprite(gl::getDefaultFramebuffer(), 0.0f, 0.0f, // (float)w, (float)h, textureObj); } static void GLObjectListGUI() { ImGui::Begin("GL objects"); static int selected = -1; auto objCount = getGLObjectCount(); if (selected >= objCount) selected = objCount - 1; ////////////////////////////////////////// ImGui::BeginChild("Object list", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, ImGui::GetContentRegionAvail().y), true, ImGuiWindowFlags_HorizontalScrollbar); ImGui::Columns(3); ImGui::Text("Object ID"); ImGui::NextColumn(); ImGui::Text("Type"); ImGui::NextColumn(); ImGui::Text("Frame created"); ImGui::NextColumn(); ImGui::Separator(); for (int i = 0; i < objCount; ++i) { ImGui::PushID(i); auto obj = getGLObjectData(i); auto objStr = fmt::format("({}):{}", obj->type, obj->obj); bool isSelected = selected == i; if (ImGui::Selectable(objStr.c_str(), &isSelected, ImGuiSelectableFlags_SpanAllColumns)) { selected = i; } ImGui::NextColumn(); ImGui::Text("%s", getGLObjectTypeName(obj->type)); ImGui::NextColumn(); ImGui::Text("%" PRIi64, obj->creationFrame); ImGui::NextColumn(); ImGui::PopID(); } ImGui::EndChild(); ////////////////////////////////////////// if (selected != -1) { ImGui::SameLine(); ImGui::BeginChild("Object GUI", ImVec2(0, 300), false); auto obj = getGLObjectData(selected); if (obj->type == gl::TEXTURE) GLTextureGUI(obj->obj); ImGui::EndChild(); } ImGui::End(); } using NameValuePair = std::pair<const char *, gl::GLenum>; static void ComboGLenum(const char *label, gl::GLenum *outValue, span<const NameValuePair> values) { auto enumToIndex = [&](gl::GLenum e) { int i = 0; for (auto &p : values) { if (p.second == e) return i; ++i; } return -1; }; int curIdx = enumToIndex(*outValue); ImGui::Combo(label, &curIdx, [](void *data, int idx, const char **out_text) { auto values = *static_cast<span<NameValuePair> *>(data); if (idx < (int)values.size()) { *out_text = values[idx].first; return true; } return false; }, &values, (int)values.size()); *outValue = values[curIdx].second; } /*static void pipelineStateGUI(PipelineState *ps) { ////////////////////////////////////////////////////// // Depth-stencil if (ImGui::CollapsingHeader("Depth-stencil state")) { ImGui::Checkbox("Depth test enabled", &ps->drawStates.depthStencilState.depthTestEnable); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("gl::Enable(gl::DEPTH_TEST)"); } ImGui::Checkbox("Depth write enabled", &ps->drawStates.depthStencilState.depthWriteEnable); if (ImGui::IsItemHovered()) { ImGui::SetTooltip("Write to the depth buffer"); } static const NameValuePair depthTestFuncNames[] = { {"gl::NEVER", gl::NEVER}, {"gl::LESS", gl::LESS}, {"gl::EQUAL", gl::EQUAL}, {"gl::LEQUAL", gl::LEQUAL}, {"gl::GREATER", gl::GREATER}, {"gl::NOTEQUAL", gl::NOTEQUAL}, {"gl::GEQUAL", gl::GEQUAL}, {"gl::ALWAYS", gl::ALWAYS}}; ComboGLenum("Depth test func", &ps->drawStates.depthStencilState.depthTestFunc, depthTestFuncNames); } ////////////////////////////////////////////////////// // Rasterizer if (ImGui::CollapsingHeader("Rasterizer state")) { static const NameValuePair fillModeNames[] = {{"gl::FILL", gl::FILL}, {"gl::LINE", gl::LINE}}; ComboGLenum("Fill mode", &ps->drawStates.rasterizerState.fillMode, fillModeNames); } ////////////////////////////////////////////////////// // Viewports if (ImGui::CollapsingHeader("Viewports")) { ImGui::Columns(5); ImGui::Text("Viewport index"); ImGui::NextColumn(); ImGui::Text("X"); ImGui::NextColumn(); ImGui::Text("Y"); ImGui::NextColumn(); ImGui::Text("W"); ImGui::NextColumn(); ImGui::Text("H"); ImGui::NextColumn(); ImGui::Separator(); for (int i = 0; i < 8; ++i) { ImGui::PushID(i); ImGui::Text("%i", i); ImGui::NextColumn(); ImGui::InputFloat("##X", &ps->drawStates.viewports[i].x); ImGui::NextColumn(); ImGui::InputFloat("##Y", &ps->drawStates.viewports[i].y); ImGui::NextColumn(); ImGui::InputFloat("##Z", &ps->drawStates.viewports[i].w); ImGui::NextColumn(); ImGui::InputFloat("##W", &ps->drawStates.viewports[i].h); ImGui::NextColumn(); ImGui::Separator(); ImGui::PopID(); } ImGui::Columns(1); } ////////////////////////////////////////////////////// // Shader sources if (ImGui::CollapsingHeader("Shader sources")) { if (ImGui::Button("Recompile")) { ps->shouldRecompile = true; } if (ImGui::Button("VS")) ImGui::OpenPopup("Vertex Shader"); ImGui::SameLine(); if (ImGui::Button("FS")) ImGui::OpenPopup("Fragment Shader"); ImGui::SameLine(); if (ImGui::Button("GS")) ImGui::OpenPopup("Geometry Shader"); ImGui::SameLine(); if (ImGui::Button("TCS")) ImGui::OpenPopup("Tess Control Shader"); ImGui::SameLine(); if (ImGui::Button("TES")) ImGui::OpenPopup("Tess Eval Shader"); if (ImGui::Button("CS")) ImGui::OpenPopup("Compute Shader"); ImVec2 shaderEditWinSize = ImVec2{200.0f, 400.0f}; size_t bufSize = 100000; auto shaderEditPopup = [&](const char *label, std::string &source) { if (ImGui::BeginResizablePopup(label, shaderEditWinSize)) { ImGui::PushItemWidth(-1); gui::inputTextMultilineString("", source, bufSize); ImGui::PopItemWidth(); ImGui::EndPopup(); } }; shaderEditPopup("Vertex Shader", ps->vertexShaderSource); shaderEditPopup("Fragment Shader", ps->fragmentShaderSource); shaderEditPopup("Geometry Shader", ps->geometryShaderSource); shaderEditPopup("Tess Control Shader", ps->tessControlShaderSource); shaderEditPopup("Tess Eval Shader", ps->tessEvalShaderSource); shaderEditPopup("Compute Shader", ps->computeShaderSource); } } static void pipelineStatesGUI() { ImGui::Begin("Shaders"); auto &pipelineStateCache = getPipelineStateCache(); if (ImGui::Button("Reload all (Ctrl+F5)")) { pipelineStateCache.reloadAll(); } int numPS = pipelineStateCache.getCachedPipelineStateCount(); for (int i = 0; i < numPS; ++i) { ImGui::PushID(i); auto ps = pipelineStateCache.getCachedPipelineState(i); if (ImGui::CollapsingHeader( fmt::format("#{} | {}", i, ps->origShaderID.c_str()).c_str())) { ImGui::Indent(20.0f); pipelineStateGUI(ps); ImGui::Unindent(20.0f); } ImGui::PopID(); } ImGui::End(); }*/ void drawDebugOverlay(double dt) { beginFixedTooltip("frame"); ImGui::TextDisabled("Frame time: %.06f ms (%.02f FPS)", dt * 1000.0f, 1.0f / dt); endFixedTooltip(); //pipelineStatesGUI(); GLObjectListGUI(); showCVarGui(); } } // namespace ag
mit
nevik-xx/psl1ght
tools/scetool/self.cpp
1
31118
/* * Copyright (c) 2011-2013 by naehrwert * This file is released under the GPLv2. */ #include <stdio.h> #include <stdlib.h> #include "types.h" #include "config.h" #include "util.h" #include "sce.h" #include "sce_inlines.h" #include "self.h" #include "elf.h" #include "elf_inlines.h" #include "tables.h" #include "sha1.h" #include "np.h" static void _get_shdr_flags(s8 *str, u64 flags) { memset(str, '-', 3); str[3] = 0; if(flags & SHF_WRITE) str[0] = 'W'; if(flags & SHF_ALLOC) str[1] = 'A'; if(flags & SHF_EXECINSTR) str[2] = 'E'; } static void _get_phdr_flags(s8 *str, u64 flags) { memset(str, '-', 3); str[3] = 0; if(flags & PF_X) str[0] = 'X'; if(flags & PF_W) str[1] = 'W'; if(flags & PF_R) str[2] = 'R'; } void _print_self_header(FILE *fp, self_header_t *h) { fprintf(fp, "[*] SELF Header:\n"); fprintf(fp, " Header Type 0x%016llX\n", h->header_type); fprintf(fp, " App Info Offset 0x%016llX\n", h->app_info_offset); fprintf(fp, " ELF Offset 0x%016llX\n", h->elf_offset); fprintf(fp, " PH Offset 0x%016llX\n", h->phdr_offset); fprintf(fp, " SH Offset 0x%016llX\n", h->shdr_offset); fprintf(fp, " Section Info Offset 0x%016llX\n", h->section_info_offset); fprintf(fp, " SCE Version Offset 0x%016llX\n", h->sce_version_offset); fprintf(fp, " Control Info Offset 0x%016llX\n", h->control_info_offset); fprintf(fp, " Control Info Size 0x%016llX\n", h->control_info_size); //fprintf(fp, " padding 0x%016llX\n", h->padding); } void _print_app_info(FILE *fp, app_info_t *ai) { const s8 *name; fprintf(fp, "[*] Application Info:\n"); name = _get_name(_auth_ids, ai->auth_id); if(name != NULL) { fprintf(fp, " Auth-ID "); _PRINT_RAW(fp, "0x%016llX ", ai->auth_id); fprintf(fp, "[%s]\n", name); } else fprintf(fp, " Auth-ID 0x%016llX\n", ai->auth_id); name = _get_name(_vendor_ids, ai->vendor_id); if(name != NULL) { fprintf(fp, " Vendor-ID "); _PRINT_RAW(fp, "0x%08X ", ai->vendor_id); fprintf(fp, "[%s]\n", name); } else fprintf(fp, " Vendor-ID 0x%08X\n", ai->vendor_id); name = _get_name(_self_types, ai->self_type); if(name != NULL) fprintf(fp, " SELF-Type [%s]\n", name); else fprintf(fp, " SELF-Type 0x%08X\n", ai->self_type); fprintf(fp, " Version %s\n", sce_version_to_str(ai->version)); //fprintf(fp, " padding 0x%016llX\n", ai->padding); } void _print_section_info_header(FILE *fp) { fprintf(fp, "[*] Section Infos:\n"); fprintf(fp, " Idx Offset Size Compressed unk0 unk1 Encrypted\n"); } void _print_section_info(FILE *fp, section_info_t *si, u32 idx) { fprintf(fp, " %03d %08X %08X %s %08X %08X %s\n", idx, (u32)si->offset, (u32)si->size, si->compressed == 2 ? "[YES]" : "[NO ]", si->unknown_0, si->unknown_1, si->encrypted == 1 ? "[YES]" : "[NO ]"); } void _print_sce_version(FILE *fp, sce_version_t *sv) { fprintf(fp, "[*] SCE Version:\n"); fprintf(fp, " Header Type 0x%08X\n", sv->header_type); fprintf(fp, " Present [%s]\n", sv->present == SCE_VERSION_PRESENT ? "TRUE" : "FALSE"); fprintf(fp, " Size 0x%08X\n", sv->size); fprintf(fp, " unknown_3 0x%08X\n", sv->unknown_3); } void _print_control_info(FILE *fp, control_info_t *ci) { const s8 *name; fprintf(fp, "[*] Control Info\n"); name = _get_name(_control_info_types, ci->type); if(name != NULL) fprintf(fp, " Type %s\n", name); else fprintf(fp, " Type 0x%08X\n", ci->type); fprintf(fp, " Size 0x%08X\n", ci->size); fprintf(fp, " Next [%s]\n", ci->next == 1 ? "TRUE" : "FALSE"); switch(ci->type) { case CONTROL_INFO_TYPE_FLAGS: _hexdump(fp, " Flags", 0, (u8 *)ci + sizeof(control_info_t), ci->size - sizeof(control_info_t), FALSE); break; case CONTROL_INFO_TYPE_DIGEST: if(ci->size == 0x30) { ci_data_digest_30_t *dig = (ci_data_digest_30_t *)((u8 *)ci + sizeof(control_info_t)); _hexdump(fp, " Digest", 0, dig->digest, 20, FALSE); } else if(ci->size == 0x40) { ci_data_digest_40_t *dig = (ci_data_digest_40_t *)((u8 *)ci + sizeof(control_info_t)); _es_ci_data_digest_40(dig); _hexdump(fp, " Digest 1 ", 0, dig->digest1, 20, FALSE); _hexdump(fp, " Digest 2 ", 0, dig->digest2, 20, FALSE); if(dig->fw_version != 0) fprintf(fp, " FW Version %d [%02d.%02d]\n", (u32)dig->fw_version, ((u32)dig->fw_version)/10000, (((u32)dig->fw_version)%10000)/100); } break; case CONTROL_INFO_TYPE_NPDRM: { ci_data_npdrm_t *np = (ci_data_npdrm_t *)((u8 *)ci + sizeof(control_info_t)); //Was already fixed in decrypt_header. //_es_ci_data_npdrm(np); fprintf(fp, " Magic 0x%08X [%s]\n", np->magic, (np->magic == NP_CI_MAGIC ? "OK" : "ERROR")); fprintf(fp, " unknown_0 0x%08X\n", np->unknown_0); fprintf(fp, " Licence Type 0x%08X\n", np->license_type); fprintf(fp, " App Type 0x%08X\n", np->app_type); fprintf(fp, " ContentID %s\n", np->content_id); _hexdump(fp, " Random Pad ", 0, np->rndpad, 0x10, FALSE); _hexdump(fp, " CID_FN Hash ", 0, np->hash_cid_fname, 0x10, FALSE); _hexdump(fp, " CI Hash ", 0, np->hash_ci, 0x10, FALSE); fprintf(fp, " unknown_1 0x%016llX\n", np->unknown_1); fprintf(fp, " unknown_2 0x%016llX\n", np->unknown_2); } break; } } static void _print_cap_flags_flags(FILE *fp, oh_data_cap_flags_t *cf) { if(cf->flags & 0x01) fprintf(fp, "0x01 "); if(cf->flags & 0x02) fprintf(fp, "0x02 "); if(cf->flags & 0x04) fprintf(fp, "0x04 "); if(cf->flags & CAP_FLAG_REFTOOL) fprintf(fp, "REFTOOL "); if(cf->flags & CAP_FLAG_DEBUG) fprintf(fp, "DEBUG "); if(cf->flags & CAP_FLAG_RETAIL) fprintf(fp, "RETAIL "); if(cf->flags & CAP_FLAG_SYSDBG) fprintf(fp, "SYSDBG "); } void _print_opt_header(FILE *fp, opt_header_t *oh) { const s8 *name; fprintf(fp, "[*] Optional Header\n"); name = _get_name(_optional_header_types, oh->type); if(name != NULL) fprintf(fp, " Type %s\n", name); else fprintf(fp, " Type 0x%08X\n", oh->type); fprintf(fp, " Size 0x%08X\n", oh->size); fprintf(fp, " Next [%s]\n", oh->next == 1 ? "TRUE" : "FALSE"); switch(oh->type) { case OPT_HEADER_TYPE_CAP_FLAGS: { oh_data_cap_flags_t *cf = (oh_data_cap_flags_t *)((u8 *)oh + sizeof(opt_header_t)); _IF_RAW(_hexdump(fp, " Flags", 0, (u8 *)cf, sizeof(oh_data_cap_flags_t), FALSE)); _es_oh_data_cap_flags(cf); fprintf(fp, " unknown_3 0x%016llX\n", cf->unk3); fprintf(fp, " unknown_4 0x%016llX\n", cf->unk4); fprintf(fp, " Flags 0x%016llX [ ", cf->flags); _print_cap_flags_flags(fp, cf); fprintf(fp, "]\n"); fprintf(fp, " unknown_6 0x%08X\n", cf->unk6); fprintf(fp, " unknown_7 0x%08X\n", cf->unk7); } break; #ifdef CONFIG_DUMP_INDIV_SEED case OPT_HEADER_TYPE_INDIV_SEED: { u8 *is = (u8 *)oh + sizeof(opt_header_t); _hexdump(fp, " Seed", 0, is, oh->size - sizeof(opt_header_t), TRUE); } break; #endif } } void _print_elf32_ehdr(FILE *fp, Elf32_Ehdr *h) { const s8 *name; fprintf(fp, "[*] ELF32 Header:\n"); name = _get_name(_e_types, h->e_type); if(name != NULL) fprintf(fp, " Type [%s]\n", name); else fprintf(fp, " Type 0x%04X\n", h->e_type); name = _get_name(_e_machines, h->e_machine); if(name != NULL) fprintf(fp, " Machine [%s]\n", name); else fprintf(fp, " Machine 0x%04X\n", h->e_machine); fprintf(fp, " Version 0x%08X\n", h->e_version); fprintf(fp, " Entry 0x%08X\n", h->e_entry); fprintf(fp, " Program Headers Offset 0x%08X\n", h->e_phoff); fprintf(fp, " Section Headers Offset 0x%08X\n", h->e_shoff); fprintf(fp, " Flags 0x%08X\n", h->e_flags); fprintf(fp, " Program Headers Count %04d\n", h->e_phnum); fprintf(fp, " Section Headers Count %04d\n", h->e_shnum); fprintf(fp, " SH String Index %04d\n", h->e_shstrndx); } void _print_elf64_ehdr(FILE *fp, Elf64_Ehdr *h) { const s8 *name; fprintf(fp, "[*] ELF64 Header:\n"); name = _get_name(_e_types, h->e_type); if(name != NULL) fprintf(fp, " Type [%s]\n", name); else fprintf(fp, " Type 0x%04X\n", h->e_type); name = _get_name(_e_machines, h->e_machine); if(name != NULL) fprintf(fp, " Machine [%s]\n", name); else fprintf(fp, " Machine 0x%04X\n", h->e_machine); fprintf(fp, " Version 0x%08X\n", h->e_version); fprintf(fp, " Entry 0x%016llX\n", h->e_entry); fprintf(fp, " Program Headers Offset 0x%016llX\n", h->e_phoff); fprintf(fp, " Section Headers Offset 0x%016llX\n", h->e_shoff); fprintf(fp, " Flags 0x%08X\n", h->e_flags); fprintf(fp, " Program Headers Count %04d\n", h->e_phnum); fprintf(fp, " Section Headers Count %04d\n", h->e_shnum); fprintf(fp, " SH String Index %04d\n", h->e_shstrndx); } void _print_elf32_shdr_header(FILE *fp) { fprintf(fp, "[*] ELF32 Section Headers:\n"); fprintf(fp, " Idx Name Type Flags Address Offset Size ES Align LK\n"); } void _print_elf32_shdr(FILE *fp, Elf32_Shdr *h, u32 idx) { const s8 *name; s8 flags[4]; _get_shdr_flags(flags, h->sh_flags); fprintf(fp, " %03d %04X ", idx, h->sh_name); name = _get_name(_sh_types, h->sh_type); if(name != NULL) fprintf(fp, "%-13s ", name); else fprintf(fp, "%08X ", h->sh_type); fprintf(fp, "%s %05X %05X %05X %02X %05X %03d\n", flags, h->sh_addr, h->sh_offset, h->sh_size, h->sh_entsize, h->sh_addralign, h->sh_link); } void _print_elf64_shdr_header(FILE *fp) { fprintf(fp, "[*] ELF64 Section Headers:\n"); fprintf(fp, " Idx Name Type Flags Address Offset Size ES Align LK\n"); } void _print_elf64_shdr(FILE *fp, Elf64_Shdr *h, u32 idx) { const s8 *name; s8 flags[4]; _get_shdr_flags(flags, h->sh_flags); fprintf(fp, " %03d %04X ", idx, h->sh_name); name = _get_name(_sh_types, h->sh_type); if(name != NULL) fprintf(fp, "%-13s ", name); else fprintf(fp, "%08X ", h->sh_type); fprintf(fp, "%s %08X %08X %08X %04X %08X %03d\n", flags, (u32)h->sh_addr, (u32)h->sh_offset, (u32)h->sh_size, (u32)h->sh_entsize, (u32)h->sh_addralign, h->sh_link); } void _print_elf32_phdr_header(FILE *fp) { fprintf(fp, "[*] ELF32 Program Headers:\n"); fprintf(fp, " Idx Type Offset VAddr PAddr FileSize MemSize Flags Align\n"); } void _print_elf32_phdr(FILE *fp, Elf32_Phdr *h, u32 idx) { const s8 *name; s8 flags[4]; _get_phdr_flags(flags, h->p_flags); fprintf(fp, " %03d ", idx); name = _get_name(_ph_types, h->p_type); if(name != NULL) fprintf(fp, "%-7s ", name); else fprintf(fp, "0x%08X ", h->p_type); fprintf(fp, "%05X %05X %05X %05X %05X %s %05X\n", h->p_offset, h->p_vaddr, h->p_paddr, h->p_filesz, h->p_memsz, flags, h->p_align); } void _print_elf64_phdr_header(FILE *fp) { fprintf(fp, "[*] ELF64 Program Headers:\n"); fprintf(fp, " Idx Type Offset VAddr PAddr FileSize MemSize PPU SPU RSX Align\n"); } void _print_elf64_phdr(FILE *fp, Elf64_Phdr *h, u32 idx) { const s8 *name; s8 ppu[4], spu[4], rsx[4]; _get_phdr_flags(ppu, h->p_flags); _get_phdr_flags(spu, h->p_flags >> 20); _get_phdr_flags(rsx, h->p_flags >> 24); fprintf(fp, " %03d ", idx); name = _get_name(_ph_types, h->p_type); if(name != NULL) fprintf(fp, "%-8s ", name); else fprintf(fp, "%08X ", h->p_type); fprintf(fp, "%08X %08X %08X %08X %08X %s %s %s %08X\n", (u32)h->p_offset, (u32)h->p_vaddr, (u32)h->p_paddr, (u32)h->p_filesz, (u32)h->p_memsz, ppu, spu, rsx, (u32)h->p_align); } BOOL self_print_info(FILE *fp, sce_buffer_ctxt_t *ctxt) { u32 i, self_type; const u8 *eident; //Check for SELF. if(ctxt->sceh->header_type != SCE_HEADER_TYPE_SELF) return FALSE; //Print SELF infos. _print_self_header(fp, ctxt->self.selfh); _print_app_info(fp, ctxt->self.ai); if(ctxt->self.sv != NULL) _print_sce_version(fp, ctxt->self.sv); //Print control infos. if(ctxt->self.cis != NULL) LIST_FOREACH(iter, ctxt->self.cis) _print_control_info(fp, (control_info_t *)iter->value); //Print optional headers. if(ctxt->mdec == TRUE) { LIST_FOREACH(iter, ctxt->self.ohs) { #ifndef CONFIG_DUMP_INDIV_SEED if(((opt_header_t *)iter->value)->type != OPT_HEADER_TYPE_INDIV_SEED) _print_opt_header(fp, (opt_header_t *)iter->value); #else _print_opt_header(fp, (opt_header_t *)iter->value); #endif } } self_type = ctxt->self.ai->self_type; eident = ctxt->scebuffer + ctxt->self.selfh->elf_offset; //SPU is 32 bit. if(self_type == SELF_TYPE_LDR || self_type == SELF_TYPE_ISO || eident[EI_CLASS] == ELFCLASS32) { //32 bit ELF. Elf32_Ehdr *eh = (Elf32_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); _es_elf32_ehdr(eh); //Print section infos. _print_section_info_header(fp); for(i = 0; i < eh->e_phnum; i++) { _es_section_info(&ctxt->self.si[i]); _print_section_info(fp, &ctxt->self.si[i], i); } //Print ELF header. _print_elf32_ehdr(fp, eh); Elf32_Phdr *ph = (Elf32_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); //Print program headers. _print_elf32_phdr_header(fp); for(i = 0; i < eh->e_phnum; i++) { _es_elf32_phdr(&ph[i]); _print_elf32_phdr(fp, &ph[i], i); } if(eh->e_shnum > 0) { Elf32_Shdr *sh = (Elf32_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); //Print section headers. _print_elf32_shdr_header(fp); for(i = 0; i < eh->e_shnum; i++) { _es_elf32_shdr(&sh[i]); _print_elf32_shdr(fp, &sh[i], i); } } } else { //64 bit ELF. Elf64_Ehdr *eh = (Elf64_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); _es_elf64_ehdr(eh); //Print section infos. _print_section_info_header(fp); for(i = 0; i < eh->e_phnum; i++) { _es_section_info(&ctxt->self.si[i]); _print_section_info(fp, &ctxt->self.si[i], i); } //Print ELF header. _print_elf64_ehdr(stdout, eh); Elf64_Phdr *ph = (Elf64_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); //Print program headers. _print_elf64_phdr_header(fp); for(i = 0; i < eh->e_phnum; i++) { _es_elf64_phdr(&ph[i]); _print_elf64_phdr(fp, &ph[i], i); } if(eh->e_shnum > 0) { Elf64_Shdr *sh = (Elf64_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); //Print section headers. _print_elf64_shdr_header(fp); for(i = 0; i < eh->e_shnum; i++) { _es_elf64_shdr(&sh[i]); _print_elf64_shdr(fp, &sh[i], i); } } } return TRUE; } //TODO: maybe implement better. BOOL self_write_to_elf(sce_buffer_ctxt_t *ctxt, const s8 *elf_out) { FILE *fp; u32 i, self_type; const u8 *eident; //Check for SELF. if(ctxt->sceh->header_type != SCE_HEADER_TYPE_SELF) return FALSE; if((fp = fopen(elf_out, "wb")) == NULL) return FALSE; self_type = ctxt->self.ai->self_type; eident = ctxt->scebuffer + ctxt->self.selfh->elf_offset; //SPU is 32 bit. if(self_type == SELF_TYPE_LDR || self_type == SELF_TYPE_ISO || eident[EI_CLASS] == ELFCLASS32) { #ifdef CONFIG_DUMP_INDIV_SEED /* //Print individuals seed. if(self_type == SELF_TYPE_ISO) { u8 *indiv_seed = (u8 *)ctxt->self.ish + sizeof(iseed_header_t); s8 ifile[256]; sprintf(ifile, "%s.indiv_seed.bin", elf_out); FILE *ifp = fopen(ifile, "wb"); fwrite(indiv_seed, sizeof(u8), ctxt->self.ish->size - sizeof(iseed_header_t), ifp); fclose(ifp); } */ #endif //32 bit ELF. Elf32_Ehdr ceh, *eh = (Elf32_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); _copy_es_elf32_ehdr(&ceh, eh); //Write ELF header. fwrite(eh, sizeof(Elf32_Ehdr), 1, fp); //Write program headers. Elf32_Phdr *ph = (Elf32_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); fwrite(ph, sizeof(Elf32_Phdr), ceh.e_phnum, fp); //Write program data. metadata_section_header_t *msh = ctxt->metash; for(i = 0; i < ctxt->metah->section_count; i++) { if(msh[i].type == METADATA_SECTION_TYPE_PHDR) { _es_elf32_phdr(&ph[msh[i].index]); fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); fwrite(ctxt->scebuffer + msh[i].data_offset, sizeof(u8), msh[i].data_size, fp); } } //Write section headers. if(ctxt->self.selfh->shdr_offset != 0) { Elf32_Shdr *sh = (Elf32_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); fseek(fp, ceh.e_shoff, SEEK_SET); fwrite(sh, sizeof(Elf32_Shdr), ceh.e_shnum, fp); } } else { //64 bit ELF. Elf64_Ehdr ceh, *eh = (Elf64_Ehdr *)(ctxt->scebuffer + ctxt->self.selfh->elf_offset); _copy_es_elf64_ehdr(&ceh, eh); //Write ELF header. fwrite(eh, sizeof(Elf64_Ehdr), 1, fp); //Write program headers. Elf64_Phdr *ph = (Elf64_Phdr *)(ctxt->scebuffer + ctxt->self.selfh->phdr_offset); fwrite(ph, sizeof(Elf64_Phdr), ceh.e_phnum, fp); //Write program data. metadata_section_header_t *msh = ctxt->metash; for(i = 0; i < ctxt->metah->section_count; i++) { if(msh[i].type == METADATA_SECTION_TYPE_PHDR) { if(msh[i].compressed == METADATA_SECTION_COMPRESSED) { _es_elf64_phdr(&ph[msh[i].index]); u8 *data = (u8 *)malloc(ph[msh[i].index].p_filesz); _zlib_inflate(ctxt->scebuffer + msh[i].data_offset, msh[i].data_size, data, ph[msh[i].index].p_filesz); fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); fwrite(data, sizeof(u8), ph[msh[i].index].p_filesz, fp); free(data); } else { _es_elf64_phdr(&ph[msh[i].index]); fseek(fp, ph[msh[i].index].p_offset, SEEK_SET); fwrite(ctxt->scebuffer + msh[i].data_offset, sizeof(u8), msh[i].data_size, fp); } } } //Write section headers. if(ctxt->self.selfh->shdr_offset != 0) { Elf64_Shdr *sh = (Elf64_Shdr *)(ctxt->scebuffer + ctxt->self.selfh->shdr_offset); fseek(fp, ceh.e_shoff, SEEK_SET); fwrite(sh, sizeof(Elf64_Shdr), ceh.e_shnum, fp); } } fclose(fp); return TRUE; } /*! Static zero control flags. */ static u8 _static_control_flags[0x20] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; /*! Static control digest1. */ static u8 _static_control_digest[0x14] = { 0x62, 0x7C, 0xB1, 0x80, 0x8A, 0xB9, 0x38, 0xE3, 0x2C, 0x8C, 0x09, 0x17, 0x08, 0x72, 0x6A, 0x57, 0x9E, 0x25, 0x86, 0xE4 }; static BOOL _create_control_infos(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { control_info_t *ci; u32 self_type = ctxt->self.ai->self_type; //Step 1. switch(self_type) { case SELF_TYPE_LV0: case SELF_TYPE_LV1: case SELF_TYPE_LV2: case SELF_TYPE_APP: case SELF_TYPE_ISO: case SELF_TYPE_LDR: case SELF_TYPE_NPDRM: //TODO: <-- figure more out. { //Add control flags. ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_flags_t)); ci->type = CONTROL_INFO_TYPE_FLAGS; ci->size = sizeof(control_info_t) + sizeof(ci_data_flags_t); ci->next = 1; ci_data_flags_t *cif = (ci_data_flags_t *)((u8 *)ci + sizeof(control_info_t)); //Add default flags. if(sconf->ctrl_flags == NULL) memcpy(cif->data, _static_control_flags, 0x20); else memcpy(cif->data, sconf->ctrl_flags, 0x20); list_add_back(ctxt->self.cis, ci); } break; } //Step 2. switch(self_type) { case SELF_TYPE_LV0: case SELF_TYPE_LV1: case SELF_TYPE_LV2: case SELF_TYPE_APP: case SELF_TYPE_ISO: case SELF_TYPE_LDR: case SELF_TYPE_NPDRM: { //Add digest 0x40. ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_digest_40_t)); ci->type = CONTROL_INFO_TYPE_DIGEST; ci->size = sizeof(control_info_t) + sizeof(ci_data_digest_40_t); if(self_type == SELF_TYPE_NPDRM) ci->next = 1; else ci->next = 0; ci_data_digest_40_t *cid = (ci_data_digest_40_t *)((u8 *)ci + sizeof(control_info_t)); memcpy(cid->digest1, _static_control_digest, 0x14); memset(cid->digest2, 0, 0x14); sha1(ctxt->makeself->elf, ctxt->makeself->elf_len, cid->digest2); //TODO: check that. if(self_type == SELF_TYPE_NPDRM) cid->fw_version = sce_hexver_to_decver(sconf->fw_version); else cid->fw_version = 0; //Fixup. _es_ci_data_digest_40(cid); list_add_back(ctxt->self.cis, ci); } break; } //Step 3. switch(self_type) { case SELF_TYPE_NPDRM: { //Add NPDRM control info. if(sconf->npdrm_config == NULL) return FALSE; ci = (control_info_t *)malloc(sizeof(control_info_t) + sizeof(ci_data_npdrm_t)); ci->type = CONTROL_INFO_TYPE_NPDRM; ci->size = sizeof(control_info_t) + sizeof(ci_data_npdrm_t); ci->next = 0; ci_data_npdrm_t *cinp = (ci_data_npdrm_t *)((u8 *)ci + sizeof(control_info_t)); //Create NPDRM control info. if(np_create_ci(sconf->npdrm_config, cinp) == FALSE) { free(ci); return FALSE; } list_add_back(ctxt->self.cis, ci); } break; } return TRUE; } static void _set_cap_flags(u32 self_type, oh_data_cap_flags_t *capf) { switch(self_type) { case SELF_TYPE_LV0: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B; capf->unk6 = 1; break; case SELF_TYPE_LV1: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B; capf->unk6 = 1; break; case SELF_TYPE_LV2: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B; capf->unk6 = 1; break; case SELF_TYPE_APP: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x7B; capf->unk6 = 1; capf->unk7 = 0x20000; break; case SELF_TYPE_ISO: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL; //0x78; break; case SELF_TYPE_LDR: capf->flags = CAP_FLAG_SYSDBG | CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL; //0x78; break; case SELF_TYPE_NPDRM: capf->flags = CAP_FLAG_RETAIL | CAP_FLAG_DEBUG | CAP_FLAG_REFTOOL | 0x3; //0x3B; capf->unk6 = 1; capf->unk7 = 0x2000; break; } _es_oh_data_cap_flags(capf); } static BOOL _create_optional_headers(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { opt_header_t *oh; u32 self_type = ctxt->self.ai->self_type; //Step 1. switch(self_type) { case SELF_TYPE_LV0: case SELF_TYPE_LV1: case SELF_TYPE_LV2: case SELF_TYPE_APP: case SELF_TYPE_ISO: case SELF_TYPE_LDR: case SELF_TYPE_NPDRM: { //Add capability flags. oh = (opt_header_t *)malloc(sizeof(opt_header_t) + sizeof(oh_data_cap_flags_t)); oh->type = OPT_HEADER_TYPE_CAP_FLAGS; oh->size = sizeof(opt_header_t) + sizeof(oh_data_cap_flags_t); if(self_type == SELF_TYPE_ISO) oh->next = 1; else oh->next = 0; oh_data_cap_flags_t *capf = (oh_data_cap_flags_t *)((u8 *)oh + sizeof(opt_header_t)); //Add default flags. if(sconf->cap_flags == NULL) _set_cap_flags(self_type, capf); else memcpy(capf, sconf->cap_flags, 0x20); list_add_back(ctxt->self.ohs, oh); } break; } //Step 2. switch(self_type) { case SELF_TYPE_ISO: { //Add individuals seed. oh = (opt_header_t *)malloc(sizeof(opt_header_t) + 0x100); oh->type = OPT_HEADER_TYPE_INDIV_SEED; oh->size = sizeof(opt_header_t) + 0x100; oh->next = 0; u8 *is = (u8 *)oh + sizeof(opt_header_t); memset(is, 0, 0x100); #ifdef CONFIG_CUSTOM_INDIV_SEED if(sconf->indiv_seed != NULL) memcpy(is, sconf->indiv_seed, sconf->indiv_seed_size); #endif list_add_back(ctxt->self.ohs, oh); } break; } return TRUE; } static void _fill_sce_version(sce_buffer_ctxt_t *ctxt) { ctxt->self.sv->header_type = SUB_HEADER_TYPE_SCEVERSION; ctxt->self.sv->present = SCE_VERSION_NOT_PRESENT; ctxt->self.sv->size = sizeof(sce_version_t); ctxt->self.sv->unknown_3 = 0x00000000; } static void _add_phdr_section(sce_buffer_ctxt_t *ctxt, u32 p_type, u32 size, u32 idx) { //Offset gets set later. ctxt->self.si[idx].offset = 0; ctxt->self.si[idx].size = size; if(p_type == PT_LOAD || p_type == PT_PS3_PRX_RELOC || p_type == 0x700000A8) ctxt->self.si[idx].encrypted = 1; //Encrypted LOAD (?). else ctxt->self.si[idx].encrypted = 0; //No LOAD (?). ctxt->self.si[idx].compressed = SECTION_INFO_NOT_COMPRESSED; ctxt->self.si[idx].unknown_0 = 0; //Unknown. ctxt->self.si[idx].unknown_1 = 0; //Unknown. } static BOOL _add_shdrs_section(sce_buffer_ctxt_t *ctxt, u32 idx) { //Add a section for the section headers. if(ctxt->makeself->shdrs != NULL) { u32 shsize = ctxt->makeself->shsize; void *sec = _memdup(ctxt->makeself->shdrs, shsize); sce_add_data_section(ctxt, sec, shsize, FALSE); //Fill metadata section header. sce_set_metash(ctxt, METADATA_SECTION_TYPE_SHDR, FALSE, idx); return TRUE; } return FALSE; } static BOOL _build_self_32(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { u32 i; Elf32_Ehdr *ehdr; Elf32_Phdr *phdrs; //Elf32_Shdr *shdrs; //Copy ELF header. ctxt->makeself->ehdr = (Elf32_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf32_Ehdr)); ctxt->makeself->ehsize = sizeof(Elf32_Ehdr); ehdr = (Elf32_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf32_Ehdr)); _es_elf32_ehdr(ehdr); //Copy program headers. ctxt->makeself->phdrs = (Elf32_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf32_Phdr) * ehdr->e_phnum); ctxt->makeself->phsize = sizeof(Elf32_Phdr) * ehdr->e_phnum; phdrs = (Elf32_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf32_Phdr) * ehdr->e_phnum); //Copy section headers. if(ehdr->e_shnum != 0) { ctxt->makeself->shdrs = (Elf32_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf32_Shdr) * ehdr->e_shnum); ctxt->makeself->shsize = sizeof(Elf32_Shdr) * ehdr->e_shnum; //shdrs = (Elf32_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf32_Shdr) * ehdr->e_shnum); } //Allocate metadata section headers (one for each program header and one for the section headers). ctxt->metash = (metadata_section_header_t *)malloc(sizeof(metadata_section_header_t) * (ehdr->e_phnum + 1)); //Copy sections, fill section infos and metadata section headers. ctxt->self.si = (section_info_t *)malloc(sizeof(section_info_t) * ehdr->e_phnum); for(i = 0; i < ehdr->e_phnum; i++) { _es_elf32_phdr(&phdrs[i]); void *sec = _memdup(ctxt->makeself->elf + phdrs[i].p_offset, phdrs[i].p_filesz); //Never compress sections on SPU SELFs. sce_add_data_section(ctxt, sec, phdrs[i].p_filesz, FALSE); //Add section info. _add_phdr_section(ctxt, phdrs[i].p_type, phdrs[i].p_filesz, i); //Fill metadata section header. sce_set_metash(ctxt, METADATA_SECTION_TYPE_PHDR, phdrs[i].p_type == PT_LOAD ? TRUE : FALSE, i); } //Section info count. ctxt->makeself->si_cnt = ehdr->e_phnum; //Number of section infos that are present as data sections. ctxt->makeself->si_sec_cnt = ehdr->e_phnum; //Add a section for the section headers. if(sconf->add_shdrs == TRUE) if(_add_shdrs_section(ctxt, i) == TRUE) i++; //Metadata. ctxt->metah->section_count = i; return TRUE; } static BOOL _build_self_64(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { u32 i; Elf64_Ehdr *ehdr; Elf64_Phdr *phdrs; //Elf64_Shdr *shdrs; //Copy ELF header. ctxt->makeself->ehdr = (Elf64_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf64_Ehdr)); ctxt->makeself->ehsize = sizeof(Elf64_Ehdr); ehdr = (Elf64_Ehdr *)_memdup(ctxt->makeself->elf, sizeof(Elf64_Ehdr)); _es_elf64_ehdr(ehdr); //Copy program headers. ctxt->makeself->phdrs = (Elf64_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf64_Phdr) * ehdr->e_phnum); ctxt->makeself->phsize = sizeof(Elf64_Phdr) * ehdr->e_phnum; phdrs = (Elf64_Phdr *)_memdup(ctxt->makeself->elf + ehdr->e_phoff, sizeof(Elf64_Phdr) * ehdr->e_phnum); //Copy section headers. if(ehdr->e_shnum != 0) { ctxt->makeself->shdrs = (Elf64_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf64_Shdr) * ehdr->e_shnum); ctxt->makeself->shsize = sizeof(Elf64_Shdr) * ehdr->e_shnum; //shdrs = (Elf64_Shdr *)_memdup(ctxt->makeself->elf + ehdr->e_shoff, sizeof(Elf64_Shdr) * ehdr->e_shnum); } //Allocate metadata section headers (one for each program header and one for the section headers). ctxt->metash = (metadata_section_header_t *)malloc(sizeof(metadata_section_header_t) * (ehdr->e_phnum + 1)); //Copy sections, fill section infos and metadata section headers. ctxt->self.si = (section_info_t *)malloc(sizeof(section_info_t) * ehdr->e_phnum); u32 loff = 0xFFFFFFFF, skip = 0; for(i = 0; i < ehdr->e_phnum; i++) { _es_elf64_phdr(&phdrs[i]); //Add section info. _add_phdr_section(ctxt, phdrs[i].p_type, phdrs[i].p_filesz, i); //TODO: what if the size differs, why skip other program headers? //Fill metadata section header but skip identical program header offsets. if(sconf->skip_sections == TRUE && (phdrs[i].p_offset == loff || !(phdrs[i].p_type == PT_LOAD || phdrs[i].p_type == PT_PS3_PRX_RELOC || phdrs[i].p_type == 0x700000A8))) { const s8 *name = _get_name(_ph_types, phdrs[i].p_type); if(name != NULL) _LOG_VERBOSE("Skipped program header %-8s @ 0x%08X (0x%08X)\n", name, phdrs[i].p_offset, phdrs[i].p_filesz); else _LOG_VERBOSE("Skipped program header 0x%08X @ 0x%08X (0x%08X)\n", phdrs[i].p_type, phdrs[i].p_offset, phdrs[i].p_filesz); skip++; } else { void *sec = _memdup(ctxt->makeself->elf + phdrs[i].p_offset, phdrs[i].p_filesz); //PPU sections may be compressed. sce_add_data_section(ctxt, sec, phdrs[i].p_filesz, TRUE); sce_set_metash(ctxt, METADATA_SECTION_TYPE_PHDR, TRUE /*(phdrs[i].p_type == PT_LOAD || phdrs[i].p_type == PT_PS3_PRX_RELOC || phdrs[i].p_type == 0x700000A8) ? TRUE : FALSE*/, i - skip); } loff = phdrs[i].p_offset; } //Section info count. ctxt->makeself->si_cnt = ehdr->e_phnum; //Number of section infos that are present as data sections. ctxt->makeself->si_sec_cnt = i - skip; //Add a section for the section headers. if(sconf->add_shdrs == TRUE) if(_add_shdrs_section(ctxt, i - skip) == TRUE) i++; //Metadata. i -= skip; ctxt->metah->section_count = i; return TRUE; } BOOL self_build_self(sce_buffer_ctxt_t *ctxt, self_config_t *sconf) { //const u8 *eident; //Fill config values. ctxt->sceh->key_revision = sconf->key_revision; ctxt->self.ai->auth_id = sconf->auth_id; ctxt->self.ai->vendor_id = sconf->vendor_id; ctxt->self.ai->self_type = sconf->self_type; ctxt->self.ai->version = sconf->app_version; //Create control infos. if(_create_control_infos(ctxt, sconf) == FALSE) { printf("[*] Error: Could not create SELF control infos.\n"); return FALSE; } #ifdef CONFIG_CUSTOM_INDIV_SEED if(sconf->indiv_seed != NULL && sconf->self_type != SELF_TYPE_ISO) printf("[*] Warning: Skipping individuals seed for non-ISO SELF.\n"); #endif //Create optional headers. if(_create_optional_headers(ctxt, sconf) == FALSE) { printf("[*] Error: Could not create SELF optional headers.\n"); return FALSE; } //Set SCE version. _fill_sce_version(ctxt); //Check for 32 bit or 64 bit ELF. //eident = (const u8*)ctxt->makeself->elf; if(sconf->self_type == SELF_TYPE_LDR || sconf->self_type == SELF_TYPE_ISO /*|| eident[EI_CLASS] == ELFCLASS32*/) return _build_self_32(ctxt, sconf); return _build_self_64(ctxt, sconf); }
mit
aliakseis/LIII
src/3rdparty/torrent-rasterbar/bindings/python/src/fingerprint.cpp
1
1056
// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <libtorrent/fingerprint.hpp> #include "boost_python.hpp" void bind_fingerprint() { using namespace boost::python; using namespace libtorrent; def("generate_fingerprint", &generate_fingerprint); #ifndef TORRENT_NO_DEPRECATE class_<fingerprint>("fingerprint", no_init) .def( init<char const*,int,int,int,int>( (arg("id"), "major", "minor", "revision", "tag") ) ) .def("__str__", &fingerprint::to_string) .def_readonly("name", &fingerprint::name) .def_readonly("major_version", &fingerprint::major_version) .def_readonly("minor_version", &fingerprint::minor_version) .def_readonly("revision_version", &fingerprint::revision_version) .def_readonly("tag_version", &fingerprint::tag_version) ; #endif }
mit
jediguy13/TFT_Touch_Shield_V1
TFT_T.cpp
1
11165
/* ST7781R TFT Library. 2011 Copyright (c) Seeed Technology Inc. Authors: Albert.Miao, Visweswara R (with initializtion code from TFT vendor) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Modified record: 2012.3.27 by Frankie.Chu Add funtion:setDisplayDirect. Add more conditional statements in funtions,fillRectangle,drawChar,drawString to deal with different directions displaying. 2015.12.1 by jediguy13 Add support for arduino due by changing bit mask things */ #include "TFT_T.h" void TFT::pushData(unsigned char data) { all_pin_output(); all_pin_low(); //for(int x=2; x<10; x++){digitalWrite(x,bitRead(data,x-2));} is slow REG_PIOB_ODSR |= (bitRead(data,0)<<25); //why is pin 2 here? REG_PIOC_ODSR |= (bitRead(data,1)<<28); //and why is pin 3 just 1 separate? REG_PIOC_ODSR |= (bitRead(data,2)<<26); REG_PIOC_ODSR |= (bitRead(data,3)<<25); REG_PIOC_ODSR |= (bitRead(data,4)<<24); REG_PIOC_ODSR |= (bitRead(data,5)<<23); REG_PIOC_ODSR |= (bitRead(data,6)<<22); REG_PIOC_ODSR |= (bitRead(data,7)<<21); } unsigned char TFT::getData(void) { unsigned char data=0; delay(1); for(int x=2; x<10; x++){bitWrite(data,x-2,digitalRead(x));} return data; } void TFT::sendCommand(unsigned int index) { CS_LOW; RS_LOW; RD_HIGH; WR_HIGH; WR_LOW; pushData(0); WR_HIGH; WR_LOW; pushData(index&0xff); WR_HIGH; CS_HIGH; } void TFT::sendData(unsigned int data) { CS_LOW; RS_HIGH; RD_HIGH; WR_LOW; pushData((data&0xff00)>>8); WR_HIGH; WR_LOW; pushData(data&0xff); WR_HIGH; CS_HIGH; } unsigned int TFT::readRegister(unsigned int index) { unsigned int data=0; CS_LOW; RS_LOW; RD_HIGH; all_pin_output(); WR_LOW; pushData(0); WR_HIGH; WR_LOW; pushData(index); WR_HIGH; all_pin_input(); all_pin_low(); RS_HIGH; RD_LOW; RD_HIGH; data |= getData()<<8; RD_LOW; RD_HIGH; data |= getData(); CS_HIGH; all_pin_output(); return data; } void TFT::init (void) { CS_OUTPUT; RD_OUTPUT; WR_OUTPUT; RS_OUTPUT; Tft.all_pin_output(); Tft.all_pin_low(); delay(100); sendCommand(0x0001); sendData(0x0100); sendCommand(0x0002); sendData(0x0700); sendCommand(0x0003); sendData(0x1030); sendCommand(0x0004); sendData(0x0000); sendCommand(0x0008); sendData(0x0302); sendCommand(0x000A); sendData(0x0000); sendCommand(0x000C); sendData(0x0000); sendCommand(0x000D); sendData(0x0000); sendCommand(0x000F); sendData(0x0000); delay(100); sendCommand(0x0030); sendData(0x0000); sendCommand(0x0031); sendData(0x0405); sendCommand(0x0032); sendData(0x0203); sendCommand(0x0035); sendData(0x0004); sendCommand(0x0036); sendData(0x0B07); sendCommand(0x0037); sendData(0x0000); sendCommand(0x0038); sendData(0x0405); sendCommand(0x0039); sendData(0x0203); sendCommand(0x003c); sendData(0x0004); sendCommand(0x003d); sendData(0x0B07); sendCommand(0x0020); sendData(0x0000); sendCommand(0x0021); sendData(0x0000); sendCommand(0x0050); sendData(0x0000); sendCommand(0x0051); sendData(0x00ef); sendCommand(0x0052); sendData(0x0000); sendCommand(0x0053); sendData(0x013f); delay(100); sendCommand(0x0060); sendData(0xa700); sendCommand(0x0061); sendData(0x0001); sendCommand(0x0090); sendData(0x003A); sendCommand(0x0095); sendData(0x021E); sendCommand(0x0080); sendData(0x0000); sendCommand(0x0081); sendData(0x0000); sendCommand(0x0082); sendData(0x0000); sendCommand(0x0083); sendData(0x0000); sendCommand(0x0084); sendData(0x0000); sendCommand(0x0085); sendData(0x0000); sendCommand(0x00FF); sendData(0x0001); sendCommand(0x00B0); sendData(0x140D); sendCommand(0x00FF); sendData(0x0000); delay(100); sendCommand(0x0007); sendData(0x0133); delay(50); exitStandBy(); sendCommand(0x0022); //paint screen black paintScreenBlack(); } void TFT::paintScreenBlack(void) { for(unsigned char i=0;i<2;i++) { for(unsigned int f=0;f<38400;f++) { sendData(BLACK); } } } void TFT::exitStandBy(void) { sendCommand(0x0010); sendData(0x14E0); delay(100); sendCommand(0x0007); sendData(0x0133); } void TFT::setOrientation(unsigned int HV)//horizontal or vertical { sendCommand(0x03); if(HV==1)//vertical { sendData(0x5038); } else//horizontal { sendData(0x5030); } sendCommand(0x0022); //Start to write to display RAM } void TFT::setDisplayDirect(unsigned char Direction) { DisplayDirect = Direction; } void TFT::setXY(unsigned int poX, unsigned int poY) { sendCommand(0x0020);//X sendData(poX); sendCommand(0x0021);//Y sendData(poY); sendCommand(0x0022);//Start to write to display RAM } void TFT::setPixel(unsigned int poX, unsigned int poY,unsigned int color) { setXY(poX,poY); sendData(color); } void TFT::drawCircle(int poX, int poY, int r,unsigned int color) { int x = -r, y = 0, err = 2-2*r, e2; do { setPixel(poX-x, poY+y,color); setPixel(poX+x, poY+y,color); setPixel(poX+x, poY-y,color); setPixel(poX-x, poY-y,color); e2 = err; if (e2 <= y) { err += ++y*2+1; if (-x == y && e2 <= x) e2 = 0; } if (e2 > x) err += ++x*2+1; } while (x <= 0); } void TFT::fillCircle(int poX, int poY, int r,unsigned int color) { int x = -r, y = 0, err = 2-2*r, e2; do { drawVerticalLine(poX-x,poY-y,2*y,color); drawVerticalLine(poX+x,poY-y,2*y,color); e2 = err; if (e2 <= y) { err += ++y*2+1; if (-x == y && e2 <= x) e2 = 0; } if (e2 > x) err += ++x*2+1; } while (x <= 0); } void TFT::drawLine(unsigned int x0,unsigned int y0,unsigned int x1,unsigned int y1,unsigned int color) { int x = x1-x0; int y = y1-y0; int dx = abs(x), sx = x0<x1 ? 1 : -1; int dy = -abs(y), sy = y0<y1 ? 1 : -1; int err = dx+dy, e2; /* error value e_xy */ for (;;){ /* loop */ setPixel(x0,y0,color); e2 = 2*err; if (e2 >= dy) { /* e_xy+e_x > 0 */ if (x0 == x1) break; err += dy; x0 += sx; } if (e2 <= dx) { /* e_xy+e_y < 0 */ if (y0 == y1) break; err += dx; y0 += sy; } } } void TFT::drawVerticalLine(unsigned int poX, unsigned int poY,unsigned int length,unsigned int color) { setXY(poX,poY); setOrientation(1); if(length+poY>MAX_Y) { length=MAX_Y-poY; } for(unsigned int i=0;i<length;i++) { sendData(color); } } void TFT::drawHorizontalLine(unsigned int poX, unsigned int poY,unsigned int length,unsigned int color) { setXY(poX,poY); setOrientation(0); if(length+poX>MAX_X) { length=MAX_X-poX; } for(unsigned int i=0;i<length;i++) { sendData(color); } } void TFT::drawRectangle(unsigned int poX, unsigned int poY, unsigned int length,unsigned int width,unsigned int color) { drawHorizontalLine(poX, poY, length, color); drawHorizontalLine(poX, poY+width, length, color); drawVerticalLine(poX, poY, width,color); drawVerticalLine(poX + length, poY, width,color); } void TFT::fillRectangle(unsigned int poX, unsigned int poY, unsigned int length, unsigned int width, unsigned int color) { for(unsigned int i=0;i<width;i++) { if(DisplayDirect == LEFT2RIGHT) drawHorizontalLine(poX, poY+i, length, color); else if (DisplayDirect == DOWN2UP) drawHorizontalLine(poX, poY-i, length, color); else if(DisplayDirect == RIGHT2LEFT) drawHorizontalLine(poX, poY-i, length, color); else if(DisplayDirect == UP2DOWN) drawHorizontalLine(poX, poY+i, length, color); } } void TFT::drawChar(unsigned char ascii,unsigned int poX, unsigned int poY,unsigned int size, unsigned int fgcolor) { setXY(poX,poY); if((ascii < 0x20)||(ascii > 0x7e))//Unsupported char. { ascii = '?'; } for(unsigned char i=0;i<8;i++) { unsigned char temp = pgm_read_byte(&simpleFont[ascii-0x20][i]); for(unsigned char f=0;f<8;f++) { if((temp>>f)&0x01) { if(DisplayDirect == LEFT2RIGHT) fillRectangle(poX+i*size, poY+f*size, size, size, fgcolor); else if(DisplayDirect == DOWN2UP) fillRectangle(poX+f*size, poY-i*size, size, size, fgcolor); else if(DisplayDirect == RIGHT2LEFT) fillRectangle(poX-i*size, poY-f*size, size, size, fgcolor); else if(DisplayDirect == UP2DOWN) fillRectangle(poX-f*size, poY+i*size, size, size, fgcolor); } } } } void TFT::drawString(char *string,unsigned int poX, unsigned int poY,unsigned int size,unsigned int fgcolor) { while(*string) { for(unsigned char i=0;i<8;i++) { drawChar(*string, poX, poY, size, fgcolor); } *string++; if(DisplayDirect == LEFT2RIGHT) { if(poX < MAX_X) { poX+=8*size; // Move cursor right } } else if(DisplayDirect == DOWN2UP) { if(poY > 0) { poY-=8*size; // Move cursor right } } else if(DisplayDirect == RIGHT2LEFT) { if(poX > 0) { poX-=8*size; // Move cursor right } } else if(DisplayDirect == UP2DOWN) { if(poY < MAX_Y) { poY+=8*size; // Move cursor right } } } } void TFT::all_pin_input(void) { for(int x=2; x<10; x++){pinMode(x,INPUT);} } void TFT::all_pin_output(void) { for(int x=2; x<10; x++){pinMode(x,OUTPUT);} } void TFT::all_pin_low(void) { for(int x=2; x<10; x++){digitalWrite(x,LOW);} } TFT Tft=TFT();
mit
csipiemonte/smartlab
reference-realtime/arduino-secure/libraries/SDPMessage/src/csvline.cpp
1
3215
/* * Copyright (C) 2014 CSP Innovazione nelle ICT s.c.a r.l. (http://www.csp.it/) * All rights reserved. * * All information contained herein is, and remains the property of * CSP Innovazione nelle ICT s.c.a r.l. and its suppliers, if any. * The intellectual and technical concepts contained herein are proprietary to * CSP Innovazione nelle ICT s.c.a r.l. and its suppliers and may be covered * by Italian and Foreign Patents, in process, and are protected by trade secret * or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from CSP Innovazione nelle ICT s.c.a r.l. * * cspvine.cpp * <description> * * Authors: * Marco Boeris Frusca <marco.boeris@csp.it> * */ #include "Arduino.h" #include "csvline.h" namespace sdp { namespace message { const size_t CSVLine::LINE_SIZE = 128; const char CSVLine::FS = ';'; CSVLine::CSVLine() : m_nf(0), m_fields(0), m_isCopy(false), m_line(0), m_length(0) { } CSVLine::CSVLine(const CSVLine& l) { m_nf = l.m_nf; m_length = l.m_length; m_line = l.m_line; m_fields = l.m_fields; m_isCopy = true; } CSVLine::~CSVLine() { if (m_fields != 0 && !m_isCopy) { delete[] m_fields; m_fields = 0; m_nf = 0; } if (m_line != 0 && !m_isCopy) { delete[] m_line; m_line = 0; } } void CSVLine::set(const char* line, size_t length) { size_t m_length = LINE_SIZE + 1; // Check line size if (length > strlen(line)) { length = strlen(line); } if (length < m_length) { m_length = length + 1; } if (m_line != 0) { delete[] m_line; m_line = 0; } if (m_fields != 0) { delete[] m_fields; m_fields = 0; } // Create line m_line = new char[m_length]; memset(m_line, 0, m_length); memcpy(m_line, line, m_length - 1); length = strlen(m_line); if (m_line[length - 1] == FS) { m_line[length -1] = 0; } m_nf = 0; for (size_t i = 0; i < m_length; i++) { if (m_line[i] == FS) { m_nf++; } } if (m_length > 2 && m_line[length - 1] != FS && m_line[length] == 0) { m_nf++; } m_fields = new size_t[m_nf]; memset(m_fields, 0, sizeof(size_t) * m_nf); size_t j = 0; size_t i = 0; for (; i < m_length; i++) { if (i == 0) { m_fields[j++] = i; } if ( i > 0 && j < m_nf && m_line[i -1] == FS) { m_line[i -1] = 0; m_fields[j++] = i; } } } bool CSVLine::getItemAsInt(size_t index, int &n) { char* field = getItem(index); return StringParser::toInt(field, n); } bool CSVLine::getItemAsLong(size_t index, long &n) { char* field = getItem(index); return StringParser::toLong(field, n, strlen(field)); } } /* namespace message */ } /* namespace sdp */
mit
dezGusty/serpents
src/model/SerpentBase.cpp
1
10439
// This file is part of Gusty's Serpents // Copyright (C) 2009 Augustin Preda (thegusty999@gmail.com) // // Gusty's Serpents is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // Class to allow manipulation of a serpent. #include <model/SerpentBase.h> #include <guslib/trace/trace.h> #include <stdio.h> #include <math.h> using namespace GUtils; namespace Serpents { #if 0 SerpentBase::SerpentBase( ) : fractionOfLength(0.0) , hungerLevel(0.0) { path = new SerpentPath(); this->turnSpeed = 1; this->speed = 1; this->speedStep = 1; this->timeSinceLastBonusPicked = 0; this->hungerGrowthRatio = 1; this->hungerDamagingLimit = 1; bodyParts.clear(); } SerpentBase::~SerpentBase(void) { GTRACE(4, "SerpentBase destructr: Removing serpent & all "<< getLength() << " bodyparts"); for( unsigned i=0; i<bodyParts.size(); i++ ) { delete bodyParts[i]; } bodyParts.clear(); } void SerpentBase::addPart(Serpents::BodyPartBase *partToAdd) { BodyPartBase * myBodyPart = partToAdd; myBodyPart->setSize( spawnBodyPartSize ); GTRACE(4, "Adding bodypart; size=" <<spawnBodyPartSize.x<<","<<spawnBodyPartSize.y); if( this->getLength() <= 0 ) { myBodyPart->angleInRads = this->spawnAngle; } bodyParts.push_back( myBodyPart ); this->onAddedBodyPart(); } void SerpentBase::addParts( double numParts ) { GTRACE(4, "SerpentBase: adding " << numParts<< " bodyparts"); if( numParts <= 0 ) { // must use removeparts function, instead of supplying a negative number. return; } bool canStillAdd = true; while( canStillAdd ) { if( numParts >= 1 ) { // need to add a bodypart; // set the currently last bp to full if( getLength() > 1 ) { this->getBodyPart(this->getLength()-1)->setFraction( 1.0 ); } BodyPartBase * myBodyPart = this->createBodyPart( bodyParts.size() == 0); if( myBodyPart ) { myBodyPart->setSize( spawnBodyPartSize ); GTRACE(4, "Adding bodypart; size=" <<spawnBodyPartSize.x<<","<<spawnBodyPartSize.y); if( this->getLength() <= 0 ) { myBodyPart->setAngleInRadians(this->spawnAngle ); } myBodyPart->setFraction( 1.0 + fractionOfLength ); bodyParts.push_back( myBodyPart ); this->onAddedBodyPart(); } numParts--; } else { fractionOfLength = fractionOfLength + numParts; if( fractionOfLength > 0 ) { // set the currently last bp to full if( getLength() > 1 ) { this->getBodyPart(this->getLength()-1)->setFraction( 1.0 ); } BodyPartBase * myBodyPart = this->createBodyPart( bodyParts.size() == 0); if( myBodyPart ) { myBodyPart->setSize( spawnBodyPartSize ); GTRACE(4, "Adding bodypart; size=" <<spawnBodyPartSize.x<<","<<spawnBodyPartSize.y); if( this->getLength() <= 0 ) { myBodyPart->setAngleInRadians(this->spawnAngle ); } fractionOfLength -= 1.0; myBodyPart->setFraction( 1.0 + fractionOfLength ); bodyParts.push_back( myBodyPart ); this->onAddedBodyPart(); } } this->getBodyPart(this->getLength()-1)->setFraction( 1.0 + fractionOfLength ); canStillAdd = false; } } } void SerpentBase::initialize( double initialLength ) { maxlength = 100; minlength = MIN_SERP_LEN; spawnBodyPartSize.x = 15; spawnBodyPartSize.y = 15; addParts(initialLength); if( bodyParts.size()> 0 ) { DPOINT hsz = {20,20}; this->bodyParts[0]->setSize( hsz ); } minSpeed = DEFAULT_MIN_SPEED; maxSpeed = DEFAULT_MAX_SPEED; setSpeed(1); setSpeedInfluenceOnTurn(0); setSpeedStep(0.001); fractionOfLength = 0; } void SerpentBase::onAddedBodyPart() { path->addStrip(); } void SerpentBase::onRemovedBodyPart() { path->removeStrip(); } void SerpentBase::removeParts( double numParts ) { GTRACE(4, "SerpentBase: removing " << numParts << " bodyparts"); bool canRemoveParts = true; double partsStillToRemove = numParts; while( canRemoveParts ) { if( partsStillToRemove >= 1 ) { if( getLength() - 1 <= minlength ) canRemoveParts = false; if( getLength() - 1 <= MIN_SERP_LEN ) canRemoveParts = false; if( canRemoveParts ) { delete bodyParts[bodyParts.size()-1]; bodyParts.pop_back(); this->onRemovedBodyPart(); if( fractionOfLength >= 0 ) bodyParts[getLength()-1]->setFraction( fractionOfLength ); else bodyParts[getLength()-1]->setFraction( 1.0 + fractionOfLength ); -- partsStillToRemove; } } else { fractionOfLength -= partsStillToRemove; if( fractionOfLength <= -1 ) { if( getLength() > 1 ) { delete bodyParts[getLength()-1]; bodyParts.pop_back(); this->onRemovedBodyPart(); } fractionOfLength ++; bodyParts[getLength()-1]->setFraction( 1.0 + fractionOfLength ); } canRemoveParts = false; } } } void SerpentBase::setBodyPartSpawnSize( double width, double height ) { this->spawnBodyPartSize.x = width; this->spawnBodyPartSize.y = height; } void SerpentBase::setSpawnPosition(double x, double y) { this->spawnPosition.x = x; this->spawnPosition.y = y; } void SerpentBase::spawn(double x, double y) { for( int i = 0; i< this->getLength(); i++ ) { this->bodyParts[i]->setLocation(x,y); if( i==0) { bodyParts[i]->spawned = true; } else { bodyParts[i]->spawned = false; } } } void SerpentBase::spawn() { this->spawn( spawnPosition.x, spawnPosition.y ); } void SerpentBase::setAngleInRadians(double angle, bool affectAll ) { int maxIter = (affectAll ? 1 : this->getLength() ); for( int i=0; i< maxIter && i< this->getLength(); i++ ) { this->bodyParts[i]->angleInRads = angle; } spawnAngle = angle; } void SerpentBase::setSpeed( double newSpeed ) { this->speed = newSpeed; if( newSpeed < minSpeed ) { this->speed = minSpeed; } if( newSpeed > maxSpeed ) { this->speed = maxSpeed; } if( newSpeed < DEFAULT_MIN_SPEED ) { this->speed = DEFAULT_MIN_SPEED; } if( newSpeed > DEFAULT_MAX_SPEED ) { this->speed = DEFAULT_MAX_SPEED; } } void SerpentBase::setTurnSpeed(double newTurnSpeed) { if( newTurnSpeed > MIN_TURN_SPEED && newTurnSpeed < MAX_TURN_SPEED ) { this->turnSpeed = newTurnSpeed; } } void SerpentBase::move( double timeUnits ) { GTRACE(5, "*** SerpentBase::move"); if( getLength() <= 0 ) return; if( timeUnits <=0 ) { timeUnits = DEFAULT_TIME_INTERVAL; } GTRACE(5, "*** SerpentBase::move, len="<<getLength()); if( getLength() <= minlength ) { return; } // spawn the parts that are not yet visible. int lastNonSpawn = getLength(); for(int i=getLength()-1;i>=0;i-- ) { if( ! bodyParts[i]->spawned ) { lastNonSpawn = i; } } if( lastNonSpawn > 0 ) { for( int i= lastNonSpawn; i < getLength(); i++ ) { if( bodyParts[i]->collidesWith( bodyParts[i-1] )) { break; } else { bodyParts[i]->spawned = bodyParts[i-1]->spawned; } } } // Calculate the new location of the head. SPoint<double> newLocation = bodyParts[0]->getLocation(); newLocation.x += GusUtils::Cos( bodyParts[0]->getAngleInRadians() ) * this->speed * timeUnits; newLocation.y -= GusUtils::Sin( bodyParts[0]->getAngleInRadians() ) * this->speed * timeUnits; // Distance between the path elements. // The head is (by standard at least) a bit larger than the rest of the bodyparts. So the distance between it // and another bodypart is the radius of the head + the radius of a regular bodypart. double xsz = bodyParts[0]->getSizeFromCenter() + (bodyParts[1] ? bodyParts[1]->getSizeFromCenter() : 0); // Move the head strip. path->moveHeadStrip( newLocation.x, newLocation.y, xsz); // Move all strips, and set the bodyparts according to their location. path->getAndSetPositionOfAllParts( bodyParts ); } // // get the bodypart at a certain index // BodyPartBase* SerpentBase::getBodyPart(int index) { if( index >= (int)bodyParts.size() ) throw std::exception("Tried to get bodypart, but index out of range!"); return bodyParts[index]; } // // turn the snake left or right // void SerpentBase::turn( double angle, bool useRadians ) { double angleRad = angle; if( ! useRadians ) { angleRad = angle * GusUtils::PI() / 180 ; } BodyPartBase * temp = getBodyPart(0); if( temp ) { temp->setAngleInRadians( temp->getAngleInRadians() + angleRad * turnSpeed * (1 + speedInfluenceOnTurn * sqrt(speed)) ); } } void SerpentBase::setFractionOfLength( double value ) { if( value >=0 && value <=1 ) { fractionOfLength = value; } else { if( value > 1 ) fractionOfLength = 1; else // value <0 fractionOfLength = 0; } } void SerpentBase::setMinAllowedSpeed( double value ) { minSpeed = value; setSpeed(getSpeed()); } void SerpentBase::setMaxAllowedSpeed( double value ) { maxSpeed = value; setSpeed(getSpeed()); } void SerpentBase::setSpeedStep( double value ) { speedStep = value; } void SerpentBase::setHungerLevel( double value ) { if( value <= 0 ) { hungerLevel = 0; } else { hungerLevel = value; } } void SerpentBase::setAlive( bool bAlive ) { this->alive = bAlive; } #endif } // namespace Serpents
mit
kreischtauf/CSRST
src/PoissonSolver.cpp
1
23889
/*************************************************************************** PoissonSolver.cpp ------------------- begin : Tue Jun 28 2011 copyright : (C) 2011 by Christof Kraus email : christof.kraus-csrst@my.mail.de ***************************************************************************/ #include "PoissonSolver.hh" #include "utils.hh" #include "Epetra_VbrMatrix.h" #include "Epetra_LinearProblem.h" #include "Epetra_Operator.h" #include "Epetra_Time.h" #include "EpetraExt_RowMatrixOut.h" #include "Teuchos_Array.hpp" #include "BelosConfigDefs.hpp" #include "BelosLinearProblem.hpp" #include "BelosEpetraAdapter.hpp" #include "BelosBlockCGSolMgr.hpp" #include "Ifpack.h" #include "Physics.hh" extern ostream dbg; #define DBGOUT dbg << "PoissonSolver.cpp: " << __LINE__ << "\t" struct IndexComp { bool operator()(const Index & a, const Index & b) { return (a.first() < b.first()); } }; typedef double ST; typedef Epetra_Operator OP; typedef Epetra_MultiVector MV; typedef Belos::OperatorTraits<ST,MV,OP> OPT; typedef Belos::MultiVecTraits<ST,MV> MVT; PoissonSolver::PoissonSolver(PartBunch & bunch, const Bend & bend, const std::vector<BoundaryCell>& bc, const Mesh_t & mesh, const FieldLayout<DIM> & fl, const BCType & bctX, const BCType & bctY): _gamma(0.0), _Nx(0), _Ny(0), _hr(DIM), _bctX(bctX), _bctY(bctY), _bunch(bunch), _bend(bend), _boundaryCells(bc), _mesh(mesh), _FL(fl) { Vector_t pmean; _bunch.get_pmean(pmean); _gamma = sqrt(dot(pmean, pmean) + 1); _lDom = _FL.getLocalNDIndex(); _gDom = _FL.getDomain(); _hr[0] = _mesh.get_meshSpacing(0) * _gamma; _hr[1] = _mesh.get_meshSpacing(1); #if DIM>2 _hr[2] = _mesh.get_meshSpacing(2); #endif _Nx = _gDom[0].length(); _Ny = _gDom[1].length(); _setupTimer = Timings::getTimer("setup poisson"); _solveTimer = Timings::getTimer("solve poisson"); } /// actual computation void PoissonSolver::computeField(VField_Edge_t & EFD, VField_Cell_t & HFD, VField_Edge_t & JFD, const double & dt, const double & tol, const int & maxIterations) { Mesh_t & mesh = EFD.get_mesh(); FieldLayout<DIM> & FL = EFD.getLayout(); const NDIndex<DIM> lDom = FL.getLocalNDIndex(); _bunch.saveR(); const GCS_t & gcs = EFD.getGuardCellSizes(); Timings::startTimer(_setupTimer); Epetra_Map* Map = getGlobalElements(); Teuchos::RCP<Epetra_Vector> LHS; LHS = Teuchos::rcp(new Epetra_Vector(*Map)); Teuchos::RCP<Epetra_Vector> RHS; RHS = Teuchos::rcp(new Epetra_Vector(*Map)); Teuchos::RCP<Epetra_CrsMatrix> A; A = Teuchos::rcp(new Epetra_CrsMatrix(Copy, *Map, 5)); StencilGeometry(RHS, A); // print("PoissonMatrix.dat", RHS, A); Teuchos::ParameterList belosList; belosList.set( "Maximum Iterations", maxIterations ); // Maximum number of iterations allowed belosList.set( "Convergence Tolerance", tol ); belosList.set( "Verbosity", (Belos::Errors + Belos::Warnings + Belos::TimingDetails + Belos::FinalSummary + Belos::StatusTestDetails) ); Teuchos::ParameterList MLList; SetupMLList(MLList); Teuchos::RCP<ML_Epetra::MultiLevelPreconditioner> MLPrec = Teuchos::rcp(new ML_Epetra::MultiLevelPreconditioner(*A, MLList,false)); MLPrec->ComputePreconditioner(); Teuchos::RCP<Belos::EpetraPrecOp> prec = Teuchos::rcp(new Belos::EpetraPrecOp(MLPrec)); Belos::LinearProblem<ST, MV, OP> problem; problem.setOperator(A); problem.setLHS(LHS); problem.setRHS(RHS); problem.setLeftPrec(prec); if (!problem.isProblemSet()) { if (!problem.setProblem()) { std::cerr << "\nERROR: Belos::LinearProblem failed to set up correctly!" << std::endl; } } Teuchos::RCP< Belos::SolverManager<ST, MV, OP> > solver; solver = Teuchos::rcp( new Belos::BlockCGSolMgr<ST, MV, OP>(Teuchos::rcp(&problem, false), Teuchos::rcp(&belosList, false))); Timings::stopTimer(_setupTimer); BinaryVtkFile vtkFile; SField_t rho(mesh, FL, gcs); _bunch.drift_particles(dt / 2); _bunch.scatterQ(rho); _bunch.drift_particles(-dt / 2); fillRHS(rho, RHS); LHS->Random(); problem.setProblem(Teuchos::null, RHS); Timings::startTimer(_solveTimer); solver->solve(); Timings::stopTimer(_solveTimer); plotPotential(vtkFile, LHS, EFD, 1); fillFields(LHS, EFD, HFD, 1); _bunch.move_by(Vector_t(-0.5 * _hr[0] / _gamma, 0.0)); _bunch.scatterQ(rho); fillRHS(rho, RHS); shiftLHS(rho, LHS, 1.0); problem.setProblem(Teuchos::null, RHS); belosList.set("Convergence Tolerance", 1e-6); solver->setParameters(Teuchos::rcp(&belosList, false)); Timings::startTimer(_solveTimer); solver->solve(); Timings::stopTimer(_solveTimer); plotPotential(vtkFile, LHS, EFD, 2); fillFields(LHS, EFD, HFD, 2); _bunch.restoreR(); _bunch.scatterQ(rho); vtkFile.addScalarField(rho, "rho"); JFD = 0.0; JFD[lDom[0]][lDom[1]](0) += Physics::c * sqrt(1.0 - 1.0 / (_gamma * _gamma)) * rho[lDom[0]][lDom[1]]; fillRHS(rho, RHS); shiftLHS(rho, LHS, -0.5); problem.setProblem(Teuchos::null, RHS); Timings::startTimer(_solveTimer); solver->solve(); Timings::stopTimer(_solveTimer); plotPotential(vtkFile, LHS, EFD, 0); fillFields(LHS, EFD, HFD, 0); vtkFile.writeFile("Data/potential"); delete Map; } /// building the stencil void PoissonSolver::StencilGeometry(Teuchos::RCP<Epetra_Vector> & RHS, Teuchos::RCP<Epetra_CrsMatrix> & A) { const Epetra_BlockMap & MyMap = RHS->Map(); int NumMyElements = MyMap.NumMyElements(); int* MyGlobalElements = MyMap.MyGlobalElements(); double * rhsvalues = RHS->Values(); std::vector<double> Values(5); std::vector<int> Indices(5); const auto & inside = _bend.getInsideMask(); for (int lid = 0; lid < NumMyElements; ++ lid) { size_t NumEntries = 0; const size_t & gid = MyGlobalElements[lid]; cutoffStencil(Indices, Values, rhsvalues[lid], NumEntries, inside, gid); A->InsertGlobalValues(gid, NumEntries, &Values[0], &Indices[0]); } A->FillComplete(); A->OptimizeStorage(); } void PoissonSolver::initializeLHS(Teuchos::RCP<Epetra_Vector> & LHS) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); ST * values = LHS->Values(); // size_t length = _bend.getLengthStraightSection() + 1; // size_t width = _bend.getWidthStraightSection() + 1; Vector_t position; _bunch.get_rmean(position); _bend.getPositionInCells(position); int lastX = (_bend.getGlobalDomain())[0].last(); int lastY = (_bend.getGlobalDomain())[1].last(); // NDIndex<DIM> initDom(Index(0,length), Index(lastY - width, lastY)); NDIndex<DIM> elem; for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); Vector_t contr; if (idx > position(0)) { contr(0) = (idx - position(0)) / (lastX - position(0)); } else { contr(0) = (position(0) - idx) / position(0); } if (idy > position(1)) { contr(1) = (idy - position(1)) / (lastY - position(1)); } else { contr(1) = (position(1) - idy) / position(1); } const double val = sqrt(dot(contr, contr)); dbg << std::min(10.0, -log(val)) << std::endl; values[lid] = -std::max(0.0, std::min(10.0,-log(val))); } } void PoissonSolver::shiftLHS(SField_t & rho, Teuchos::RCP<Epetra_Vector> & LHS, double tau) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); NDIndex<DIM> elem; NDIndex<DIM> ldom = rho.getLayout().getLocalNDIndex(); Index II = ldom[0], JJ = ldom[1]; ST * values = LHS->Values(); for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); rho.localElement(elem) = values[lid]; } rho.fillGuardCells(); if (tau > 0) { if (tau > 1) tau = 1; rho[II][JJ] += tau * rho[II+1][JJ] - tau * rho[II][JJ]; } else { tau = - tau; if (tau > 1) tau = 1; rho[II][JJ] += tau * rho[II-1][JJ] - tau * rho[II][JJ]; } for (int lid = 0; lid < NumMyElements; ++ lid) { const int idx = MyGlobalElements[lid] % _Nx; const int idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); values[lid] = rho.localElement(elem); } } void PoissonSolver::subtract(const SField_t & rho, Teuchos::RCP<Epetra_Vector> & LHS) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); NDIndex<DIM> elem; NDIndex<DIM> ldom = rho.getLayout().getLocalNDIndex(); Index II = ldom[0], JJ = ldom[1]; ST * values = LHS->Values(); for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); values[lid] -= rho.localElement(elem); } } void PoissonSolver::add(const SField_t & rho, Teuchos::RCP<Epetra_Vector> & LHS) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); NDIndex<DIM> elem; NDIndex<DIM> ldom = rho.getLayout().getLocalNDIndex(); Index II = ldom[0], JJ = ldom[1]; ST * values = LHS->Values(); for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); values[lid] += rho.localElement(elem); } } void PoissonSolver::initialGuessLHS(Teuchos::RCP<Epetra_Vector> & LHS) const { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); Vector_t spos; NDIndex<DIM> elem; Vector_t origin = _mesh.get_origin(); double totalQ = -_bunch.get_qtotal() / (2 * Physics::pi * Physics::epsilon_0); totalQ /= 97.63; double *values = LHS->Values(); _bunch.get_rmean(spos); spos[0] = (spos[0] - origin(0)) / _mesh.get_meshSpacing(0); spos[1] = (spos[1] - origin(1)) / _mesh.get_meshSpacing(1); for (int lid = 0; lid < NumMyElements; ++ lid) { const double dx = _hr[0] * (spos[0] - MyGlobalElements[lid] % _Nx); const double dy = _hr[1] * (spos[1] - MyGlobalElements[lid] / _Nx); values[lid] = totalQ / sqrt(dx*dx + dy*dy + _hr[0]*_hr[1]); } } void PoissonSolver::fillRHS(const SField_t & rho, Teuchos::RCP<Epetra_Vector> & RHS) { const ST couplingConstant = 1 / (Physics::epsilon_0 * _gamma); const Epetra_BlockMap & Map = RHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); NDIndex<DIM> elem; ST * values = RHS->Values(); // double minv = 0.0; // double maxv = 0.0; for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); values[lid] = rho.localElement(elem) * couplingConstant; // if (minv > values[lid]) minv = values[lid]; // if (maxv < values[lid]) maxv = values[lid]; } // dbg << "rhs_{min}: " << minv << " - rhs_{max}: " << maxv << endl; } void PoissonSolver::plotPotential(BinaryVtkFile & vtkFile, const Teuchos::RCP<Epetra_Vector> & LHS, const VField_Edge_t & EFD, const int & component) { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); boost::shared_ptr<SField_Vert_t> scalarField = Utils::getScalarVertField(EFD); NDIndex<DIM> elem; char fieldName[50]; ST * values = LHS->Values(); sprintf(fieldName, "potential_%d", component); for (int lid = 0; lid < NumMyElements; ++ lid) { const size_t idx = MyGlobalElements[lid] % _Nx; const size_t idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); scalarField->localElement(elem) = values[lid]; } vtkFile.addScalarField(*scalarField, fieldName); } void PoissonSolver::fillFields(const Teuchos::RCP<Epetra_Vector> & LHS, VField_Edge_t & EFD, VField_Cell_t & HFD, const int & components) { const Epetra_BlockMap & Map = LHS->Map(); const int * MyGlobalElements = Map.MyGlobalElements(); const int NumMyElements = Map.NumMyElements(); const Vector_t hr(_mesh.get_meshSpacing(0), _mesh.get_meshSpacing(1)); Index II = _lDom[0], JJ = _lDom[1]; NDIndex<DIM> elem, elem2; ST * values = LHS->Values(); switch (components) { case 0: for (int lid = 0; lid < NumMyElements; ++ lid) { const int idx = MyGlobalElements[lid] % _Nx; const int idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); EFD.localElement(elem)(0) = values[lid] / _hr[0]; } EFD.fillGuardCells(); EFD[II][JJ](0) -= EFD[II+1][JJ](0); break; case 1: for (int lid = 0; lid < NumMyElements; ++ lid) { const int idx = MyGlobalElements[lid] % _Nx; const int idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); EFD.localElement(elem)(1) = _gamma * values[lid] / _hr[1]; } EFD.fillGuardCells(); EFD[II][JJ](1) -= EFD[II][JJ+1](1); break; case 2: { double betaGamma = sqrt(_gamma * _gamma - 1); for (int lid = 0; lid < NumMyElements; ++ lid) { const int idx = MyGlobalElements[lid] % _Nx; const int idy = MyGlobalElements[lid] / _Nx; elem[0] = Index(idx, idx); elem[1] = Index(idy, idy); double hfd = betaGamma * values[lid] / (2 * Physics::c * Physics::mu_0 * _hr[1]); HFD.localElement(elem) = Vector_t(hfd, hfd); } HFD.fillGuardCells(); HFD[II][JJ](0) -= HFD[II][JJ+1](0); HFD[II][JJ](1) -= HFD[II][JJ+1](1); break; } case -1: default: ; } } bool PoissonSolver::isInside(const int & idx, const int & idy) { if (idx < 0 || idx > _gDom[0].last() || idy < 0 || idy > _gDom[1].last()) { return false; } return true; } void PoissonSolver::distance_bunch_to_boundary(std::vector<double> & dist, const double & x, const double & y) { Vector_t spos; _bunch.get_rmean(spos); dist[0] = std::abs(x - spos[0]); dist[1] = std::abs(y - spos[1]); } void PoissonSolver::print(const std::string & filename, Teuchos::RCP<Epetra_Vector> & RHS, Teuchos::RCP<Epetra_CrsMatrix> & A) const { EpetraExt::RowMatrixToMatlabFile(filename.c_str(), *A); // if (Ippl::getNodes() == 1) { // const Epetra_BlockMap & Map = RHS->Map(); // const int NumMyElements = Map.NumMyElements(); // ST * values = RHS->Values(); // ofstream out("rhs.dat"); // for (size_t lid = 0; lid < NumMyElements; ++ lid) { // out << values[lid] << "\n"; // } // out.close(); // } } void PoissonSolver::linearStencil(std::vector<int> & Indices, std::vector<double> & Values, double & rhs, size_t & NumEntries, const Field<bool, DIM, Mesh_t, Vert> & isInside, const size_t & gid) { const double EW = -1 / (_hr[0]*_hr[0]); const double NS = -1 / (_hr[1]*_hr[1]); const int idx = gid % _Nx; const int idy = gid / _Nx; const NDIndex<DIM> elem(Index(idx, idx), Index(idy, idy)); if (isInside.localElement(elem)) { NumEntries = 5; Values[0] = NS; Indices[0] = gid - _Nx; Values[1] = EW; Indices[1] = gid - 1; Values[2] = -2 * (EW + NS); Indices[2] = gid; Values[3] = EW; Indices[3] = gid + 1; Values[4] = NS; Indices[4] = gid + _Nx; return; } const std::vector<int> & localToBCellNr = _bend.getInverseMapDualGrid(); const int & localID = localToBCellNr[_bend.getLocalID(elem)]; if (localID == -1) { NumEntries = 1; Values[0] = 1; Indices[0] = gid; NDIndex<DIM> elemmy(elem[0], elem[1] - 1); int localIDmy = localToBCellNr[_bend.getLocalID(elemmy)]; if (localIDmy != -1 && _boundaryCells[localIDmy].lambda_m(1) > SPACE_EPS) { const BoundaryCell & bc = _boundaryCells[localIDmy]; const double & s = bc.lambda_m(1); Values[NumEntries] = (1/s - 1); Indices[NumEntries] = gid - _Nx; dbg << gid << " " << gid - _Nx << " " << Values[NumEntries] << std::endl; Values[0] = NumEntries; NumEntries += 1; } NDIndex<DIM> elemmx(elem[0] - 1, elem[1]); int localIDmx = localToBCellNr[_bend.getLocalID(elemmx)]; if (localIDmx != -1 && _boundaryCells[localIDmx].lambda_m(0) > SPACE_EPS) { const BoundaryCell & bc = _boundaryCells[localIDmx]; const double & s = bc.lambda_m(0); Values[NumEntries] = (1/s - 1); Indices[NumEntries] = gid - 1; dbg << gid << " " << gid - 1 << " " << Values[NumEntries] << std::endl; Values[0] = NumEntries; NumEntries += 1; } rhs = 0.0; return; } const BoundaryCell & bc = _boundaryCells[localID]; if (bc.lambda_m[0] > 1 - SPACE_EPS || bc.lambda_m[1] > 1 - SPACE_EPS) { NumEntries = 5; Values[0] = NS; Indices[0] = gid - _Nx; Values[1] = EW; Indices[1] = gid - 1; Values[2] = -2 * (EW + NS); Indices[2] = gid; Values[3] = EW; Indices[3] = gid + 1; Values[4] = NS; Indices[4] = gid + _Nx; } else { NumEntries = 1; Values[0] = 1; Indices[0] = gid; if (bc.lambda_m(0) > SPACE_EPS) { const double & s = bc.lambda_m(0); Values[NumEntries] = (1/s - 1); Indices[NumEntries] = gid + 1; dbg << gid << " " << gid + 1 << " " << Values[NumEntries] << std::endl; Values[0] = NumEntries; NumEntries += 1; } if (bc.lambda_m(1) > SPACE_EPS) { const double & s = bc.lambda_m(1); Values[NumEntries] = (1/s - 1); Indices[NumEntries] = gid + _Nx; dbg << gid << " " << gid + _Nx << " " << Values[NumEntries] << std::endl; Values[0] = NumEntries; NumEntries += 1; } rhs = 0.0; } return; } void PoissonSolver::cutoffStencil(std::vector<int> & Indices, std::vector<double> & Values, double & rhs, size_t & NumEntries, const Field<bool, DIM, Mesh_t, Cell> & isInside, const size_t & gid) { const double EW = -1 / (_hr[0]*_hr[0]); const double NS = -1 / (_hr[1]*_hr[1]); const int idx = gid % _Nx; const int idy = gid / _Nx; const NDIndex<DIM> elem(Index(idx, idx), Index(idy, idy)); const NDIndex<DIM> elemmx(elem[0] - 1, elem[1]); const NDIndex<DIM> elemmy(elem[0], elem[1] - 1); const NDIndex<DIM> elempx(elem[0] + 1, elem[1]); const NDIndex<DIM> elempy(elem[0], elem[1] + 1); const std::vector<int> & localToBCellNr = _bend.getInverseMap(); const int & localID = localToBCellNr[_bend.getLocalID(elem)]; const int & localIDmx = localToBCellNr[_bend.getLocalID(elemmx)]; const int & localIDmy = localToBCellNr[_bend.getLocalID(elemmy)]; const int & localIDpx = localToBCellNr[_bend.getLocalID(elempx)]; const int & localIDpy = localToBCellNr[_bend.getLocalID(elempy)]; long maxX = _bend.getLengthStraightSection(); if (idx < maxX && (isInside.localElement(elem) || (localID > -1 && _boundaryCells[localID].area_m > 0.5))) { NumEntries = 0; if (isInside.localElement(elemmy) || (localIDmy > -1 && _boundaryCells[localIDmy].area_m > 0.5)) { Indices[NumEntries] = gid - _Nx; Values[NumEntries] = NS; NumEntries ++; } if (isInside.localElement(elemmx) || (localIDmx > -1 && _boundaryCells[localIDmx].area_m > 0.5)) { Indices[NumEntries] = gid - 1; Values[NumEntries] = EW; NumEntries ++; } if (isInside.localElement(elempx) || (localIDpx > -1 && _boundaryCells[localIDpx].area_m > 0.5)) { Indices[NumEntries] = gid + 1; Values[NumEntries] = EW; NumEntries ++; } if (isInside.localElement(elempy) || (localIDpy > -1 && _boundaryCells[localIDpy].area_m > 0.5)) { Indices[NumEntries] = gid + _Nx; Values[NumEntries] = NS; NumEntries ++; } Indices[NumEntries] = gid; Values[NumEntries] = -2 * (EW + NS); NumEntries ++; return; } NumEntries = 1; Indices[0] = gid; Values[0] = 1; rhs = 0; return; }
mit
vnen/godot
scene/2d/canvas_modulate.cpp
1
4292
/*************************************************************************/ /* canvas_modulate.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "canvas_modulate.h" void CanvasModulate::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_CANVAS) { if (is_visible_in_tree()) { RS::get_singleton()->canvas_set_modulate(get_canvas(), color); add_to_group("_canvas_modulate_" + itos(get_canvas().get_id())); } } else if (p_what == NOTIFICATION_EXIT_CANVAS) { if (is_visible_in_tree()) { RS::get_singleton()->canvas_set_modulate(get_canvas(), Color(1, 1, 1, 1)); remove_from_group("_canvas_modulate_" + itos(get_canvas().get_id())); } } else if (p_what == NOTIFICATION_VISIBILITY_CHANGED) { if (is_visible_in_tree()) { RS::get_singleton()->canvas_set_modulate(get_canvas(), color); add_to_group("_canvas_modulate_" + itos(get_canvas().get_id())); } else { RS::get_singleton()->canvas_set_modulate(get_canvas(), Color(1, 1, 1, 1)); remove_from_group("_canvas_modulate_" + itos(get_canvas().get_id())); } update_configuration_warnings(); } } void CanvasModulate::_bind_methods() { ClassDB::bind_method(D_METHOD("set_color", "color"), &CanvasModulate::set_color); ClassDB::bind_method(D_METHOD("get_color"), &CanvasModulate::get_color); ADD_PROPERTY(PropertyInfo(Variant::COLOR, "color"), "set_color", "get_color"); } void CanvasModulate::set_color(const Color &p_color) { color = p_color; if (is_visible_in_tree()) { RS::get_singleton()->canvas_set_modulate(get_canvas(), color); } } Color CanvasModulate::get_color() const { return color; } TypedArray<String> CanvasModulate::get_configuration_warnings() const { TypedArray<String> warnings = Node::get_configuration_warnings(); if (is_visible_in_tree() && is_inside_tree()) { List<Node *> nodes; get_tree()->get_nodes_in_group("_canvas_modulate_" + itos(get_canvas().get_id()), &nodes); if (nodes.size() > 1) { warnings.push_back(TTR("Only one visible CanvasModulate is allowed per scene (or set of instantiated scenes). The first created one will work, while the rest will be ignored.")); } } return warnings; } CanvasModulate::CanvasModulate() { } CanvasModulate::~CanvasModulate() { }
mit
shiftf8/cs539
fall2016/hw6pointers.c
1
7413
// CS 539, HW 6, Rob Lamog #include <stdio.h> #include <stdlib.h> void show( const double * begin, const double * end ); double sum( const double * begin, const double * end ); void half( double * begin, double * end ); void add( double * resultBegin, double * resultEnd, const double *a0Begin, const double * a1Begin ); void maximum( double * resultBegin, double * resultEnd, const double *a0Begin, const double * a1Begin ); void stat( double * smallest, double * average, double * largest, const double * begin, const double * end ); void setFib( unsigned * begin, unsigned * end ); void reverse( double * begin, double * end ); int die( const char * msg ); void fillArraySequentially( double * begin, double * end ); void fillArrayRandomly( double * begin, double * end ); void fillUnsignedArraySequentially( unsigned * begin, unsigned * end ); unsigned fib( unsigned n ); void showUnsigned( const unsigned * begin, const unsigned * end ); int main(){ /* * Change size for ALL tests here. */ unsigned set_size = 4; /* * Initializing main variables. */ double *arr, *arr1, *arr2; unsigned *uarr; double szero = 0, azero = 0, lzero = 0; //An address for pointers s (smallest), a (average), l (largest), to point to for stat(). double *s = &szero, *a = &azero, *l = &lzero; //It's important to point to someplace that is defined. srand(time(NULL)); //Using srand() to seed pseudo random numbers for fillArrayRandomly(). /* * Building test arrays. */ arr = malloc(set_size * sizeof *arr); if (arr == NULL) die("malloc unsuccessful."); // printf("%p : %lf : %lu\n", &arr, *arr, sizeof *arr); arr1 = malloc(set_size * sizeof *arr1); if (arr1 == NULL) die("malloc unsuccessful."); arr2 = malloc(set_size * sizeof *arr2); if (arr2 == NULL) die("malloc unsuccessful."); uarr = malloc(set_size * sizeof *uarr); if (uarr == NULL) die("malloc unsuccessful."); /* * Filling test arrays with something worth manipulating. */ fillArraySequentially(arr, arr + set_size); // fillArrayRandomly(arr, arr + set_size); fillArraySequentially(arr1, arr1 + set_size); // fillArrayRandomly(arr1, arr1 + set_size); // fillArraySequentially(arr2, arr2 + set_size); fillArrayRandomly(arr2, arr2 + set_size); fillUnsignedArraySequentially(uarr, uarr + set_size); //Special unsigned array for setfib(). // printf("%lf\n", *(arr1 + (set_size - 1))); /* * Printing initialized arrays with show() and custom showUnsigned(). */ show(arr, arr + set_size); show(arr1, arr1 + set_size); show(arr2, arr2 + set_size); showUnsigned(uarr, uarr + set_size); printf("\n"); /* * Running tests. */ printf("sum = %lf\n", sum(arr, arr + set_size)); printf("half = "); half(arr, arr + set_size); show(arr, arr + set_size); printf("add = "); add(arr, arr + set_size, arr1, arr2); show(arr, arr + set_size); printf("maximum = "); maximum(arr, arr + set_size, arr1, arr2); show(arr, arr + set_size); stat(s, a, l, arr, arr + set_size); printf("smallest = %lf, average = %lf, largest = %lf of ", *s, *a, *l); show(arr, arr + set_size); printf("setFib = "); setFib(uarr, uarr + set_size); showUnsigned(uarr, uarr + set_size); //Utilizing custom showUnsigned(). Same as show(), except this function prints unsigned arrays instead of double arrays. printf("reverse = "); reverse(arr, arr + set_size); show(arr, arr + set_size); /* * It's important to free allocated memory and manage pointers safely. */ free(arr); arr = NULL; free(arr1); arr1 = NULL; free(arr2); arr2 = NULL; free(uarr); uarr = NULL; s = NULL; a = NULL; l = NULL; return 0; } //main void show( const double * begin, const double * end ){ printf("{"); while (begin < end){ printf("%lf", *begin); ++begin; if (begin < end) printf(", "); } printf("}\n"); } double sum( const double * begin, const double * end ){ double retVal = 0; while (begin < end){ retVal += *begin; ++begin; } return retVal; } void half( double * begin, double * end ){ while (begin < end){ *begin /= 2; ++begin; } } void add( double * resultBegin, double * resultEnd, const double *a0Begin, const double * a1Begin ){ unsigned i = 0; // printf("%lf / %lf : %lf", *(a0Begin + i), *(a1Begin + i), (*(a0Begin + i) + *(a1Begin + i))); while (resultBegin < resultEnd){ *resultBegin = *(a0Begin + i) + *(a1Begin + i); ++i; ++resultBegin; } } void maximum( double * resultBegin, double * resultEnd, const double *a0Begin, const double * a1Begin ){ unsigned i = 0; while (resultBegin < resultEnd){ if (*(a0Begin + i) < *(a1Begin + i)) *resultBegin = *(a1Begin + i); else *resultBegin = *(a0Begin + i); ++i; ++resultBegin; } } void stat( double * smallest, double * average, double * largest, const double * begin, const double * end ){ unsigned elements = end - begin; if (begin == end) die("Zero elements defined. stat() needs at least one element to examine."); //Be wary of dying before the rest of your test code can manage. //Initializing with first element. *smallest = *begin; *largest = *begin; while (begin < end){ //While loop will always run at least once given the nature of stat() arguments as pointers. Affording *average to be initialized properly. if (*smallest >= *begin) *smallest = *begin; *average += *begin; if (*largest <= *begin) *largest = *begin; ++begin; } *average = *average / elements; } void setFib( unsigned * begin, unsigned * end ){ while (begin < end){ *begin = fib(*begin); ++begin; } } void reverse( double * begin, double * end ){ double temp = 0; unsigned elements = end - begin; unsigned i = 0; // printf("%u\n", i); for (i; i < elements / 2; ++i){ temp = *(begin + i); *(begin + i) = *(begin + (elements - 1 - i)); *(begin + (elements - 1 - i)) = temp; } } int die( const char * msg ){ printf("Fatal error: %s\n", msg); exit(EXIT_FAILURE); } void fillArraySequentially( double * begin, double * end ){ //Range [0++] unsigned i = 0; while (begin < end){ *begin = i++; ++begin; } } void fillArrayRandomly( double * begin, double * end ){ //Pseudo random range [0-9] while (begin < end){ *begin = rand() % 10; //Simple unsigned range for quick test verification // *begin = rand() / (RAND_MAX / (10.0)); //Random range of doubles [0.0-9.9] ++begin; } } void fillUnsignedArraySequentially( unsigned * begin, unsigned * end ){ //Range [0++] unsigned i = 0; while (begin < end){ *begin = i++; ++begin; } } unsigned fib( unsigned n ){ if (n == 0) return 0; //Special 0 case if (n == 1) return 1; //Special 1 case return fib(n - 1) + fib(n - 2); } void showUnsigned( const unsigned * begin, const unsigned * end ){ printf("{"); while (begin < end){ printf("%u", *begin); ++begin; if (begin < end) printf(", "); } printf("}\n"); }
mit
cedar-renjun/air-conditioning-assistant
rt-thread/examples/kernel/thread_detach.c
1
3211
/* * 程序清单:线程脱离 * * 这个例子会创建两个线程,在其中一个线程中执行对另一个线程的脱离。 */ #include <rtthread.h> #include "tc_comm.h" /* 线程1控制块 */ static struct rt_thread thread1; /* 线程1栈 */ static rt_uint8_t thread1_stack[THREAD_STACK_SIZE]; /* 线程2控制块 */ static struct rt_thread thread2; /* 线程2栈 */ static rt_uint8_t thread2_stack[THREAD_STACK_SIZE]; /* 线程1入口 */ static void thread1_entry(void* parameter) { rt_uint32_t count = 0; while (1) { /* 线程1采用低优先级运行,一直打印计数值 */ rt_kprintf("thread count: %d\n", count ++); } } /* 线程2入口 */ static void thread2_entry(void* parameter) { /* 线程2拥有较高的优先级,以抢占线程1而获得执行 */ /* 线程2启动后先睡眠10个OS Tick */ rt_thread_delay(10); /* * 线程2唤醒后直接执行线程1脱离,线程1将从就绪线程队列中删除 */ rt_thread_detach(&thread1); /* * 线程2继续休眠10个OS Tick然后退出 */ rt_thread_delay(10); /* * 线程2运行结束后也将自动被从就绪队列中删除,并脱离线程队列 */ } int thread_detach_init() { rt_err_t result; /* 初始化线程1 */ result = rt_thread_init(&thread1, "t1", /* 线程名:t1 */ thread1_entry, RT_NULL, /* 线程的入口是thread1_entry,入口参数是RT_NULL*/ &thread1_stack[0], sizeof(thread1_stack), /* 线程栈是thread1_stack */ THREAD_PRIORITY, 10); if (result == RT_EOK) /* 如果返回正确,启动线程1 */ rt_thread_startup(&thread1); else tc_stat(TC_STAT_END | TC_STAT_FAILED); /* 初始化线程2 */ result = rt_thread_init(&thread2, "t2", /* 线程名:t2 */ thread2_entry, RT_NULL, /* 线程的入口是thread2_entry,入口参数是RT_NULL*/ &thread2_stack[0], sizeof(thread2_stack), /* 线程栈是thread2_stack */ THREAD_PRIORITY - 1, 10); if (result == RT_EOK) /* 如果返回正确,启动线程2 */ rt_thread_startup(&thread2); else tc_stat(TC_STAT_END | TC_STAT_FAILED); return 0; } #ifdef RT_USING_TC static void _tc_cleanup() { /* 调度器上锁,上锁后,将不再切换到其他线程,仅响应中断 */ rt_enter_critical(); /* 执行线程脱离 */ if (thread1.stat != RT_THREAD_CLOSE) rt_thread_detach(&thread1); if (thread2.stat != RT_THREAD_CLOSE) rt_thread_detach(&thread2); /* 调度器解锁 */ rt_exit_critical(); /* 设置TestCase状态 */ tc_done(TC_STAT_PASSED); } int _tc_thread_detach() { /* 设置TestCase清理回调函数 */ tc_cleanup(_tc_cleanup); thread_detach_init(); /* 返回TestCase运行的最长时间 */ return 25; } /* 输出函数命令到finsh shell中 */ FINSH_FUNCTION_EXPORT(_tc_thread_detach, a static thread example); #else /* 用户应用入口 */ int rt_application_init() { thread_detach_init(); return 0; } #endif
mit
Paregov/hexadiv
edno/software/nuttx/configs/mirtoo/src/up_leds.c
1
8433
/**************************************************************************** * configs/mirtoo/src/up_leds.c * arch/arm/src/board/up_leds.c * * Copyright (C) 2012 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * 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 NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <stdint.h> #include <stdbool.h> #include <debug.h> #include <arch/board/board.h> #include "pic32mx-internal.h" #include "mirtoo-internal.h" /**************************************************************************** * Definitions ****************************************************************************/ /* LED Configuration ********************************************************/ /* The Mirtoo module has 2 user LEDs labeled LED0 and LED1 in the schematics: * * --- ----- -------------------------------------------------------------- * PIN Board Notes * --- ----- -------------------------------------------------------------- * RC8 LED0 Grounded, high value illuminates * RC9 LED1 Grounded, high value illuminates * * The Dimitech DTX1-4000L EV-kit1 supports 3 more LEDs, but there are not * controllable from software. * * If CONFIG_ARCH_LEDS is defined, then NuttX will control these LEDs as * follows: * ON OFF * ------------------------- ---- ---- ---- ---- * LED0 LED1 LED0 LED1 * ------------------------- ---- ---- ---- ---- * LED_STARTED 0 OFF OFF --- --- * LED_HEAPALLOCATE 1 ON OFF --- --- * LED_IRQSENABLED 2 OFF ON --- --- * LED_STACKCREATED 3 ON ON --- --- * LED_INIRQ 4 ON N/C OFF N/C * LED_SIGNAL 4 ON N/C OFF N/C * LED_ASSERTION 4 ON N/C OFF N/C * LED_PANIC 4 ON N/C OFF N/C */ #define GPIO_LED_0 (GPIO_OUTPUT|GPIO_VALUE_ZERO|GPIO_PORTC|GPIO_PIN8) #define GPIO_LED_1 (GPIO_OUTPUT|GPIO_VALUE_ZERO|GPIO_PORTC|GPIO_PIN9) /* LED Management Definitions ***********************************************/ #ifdef CONFIG_ARCH_LEDS # define LED_OFF 0 # define LED_ON 1 # define LED_NC 2 #endif /* Debug ********************************************************************/ #if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_LEDS) # define leddbg lldbg # ifdef CONFIG_DEBUG_VERBOSE # define ledvdbg lldbg # else # define ledvdbg(x...) # endif #else # undef CONFIG_DEBUG_LEDS # undef CONFIG_DEBUG_VERBOSE # define leddbg(x...) # define ledvdbg(x...) #endif /**************************************************************************** * Private types ****************************************************************************/ #ifdef CONFIG_ARCH_LEDS struct led_setting_s { uint8_t led0 : 2; uint8_t led1 : 2; uint8_t unused : 4; }; #endif /**************************************************************************** * Private Data ****************************************************************************/ /* If CONFIG_ARCH_LEDS is defined then NuttX will control the LEDs. The * following structures identified the LED settings for each NuttX LED state. */ #ifdef CONFIG_ARCH_LEDS static const struct led_setting_s g_ledonvalues[LED_NVALUES] = { {LED_OFF, LED_OFF, 0}, {LED_ON, LED_OFF, 0}, {LED_OFF, LED_ON, 0}, {LED_ON, LED_ON, 0}, {LED_ON, LED_NC, 0}, }; static const struct led_setting_s g_ledoffvalues[LED_NVALUES] = { {LED_NC, LED_NC, 0}, {LED_NC, LED_NC, 0}, {LED_NC, LED_NC, 0}, {LED_NC, LED_NC, 0}, {LED_OFF, LED_NC, 0}, }; /* If CONFIG_ARCH_LEDS is not defined, then the user can control the LEDs in * any way. The following array simply maps the PIC32MX_MIRTOO_LEDn * index values to the correct LED pin configuration. */ #else static const uint16_t g_ledpincfg[PIC32MX_MIRTOO_NLEDS] = { GPIO_LED_0, GPIO_LED_1 }; #endif /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: up_setleds ****************************************************************************/ #ifdef CONFIG_ARCH_LEDS void up_setleds(FAR const struct led_setting_s *setting) { /* LEDs are pulled up so writing a low value (false) illuminates them */ if (setting->led0 != LED_NC) { pic32mx_gpiowrite(GPIO_LED_0, setting->led0 == LED_ON); } if (setting->led1 != LED_NC) { pic32mx_gpiowrite(GPIO_LED_1, setting->led1 == LED_ON); } } #endif /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: pic32mx_ledinit ****************************************************************************/ void pic32mx_ledinit(void) { /* Configure output pins */ pic32mx_configgpio(GPIO_LED_0); pic32mx_configgpio(GPIO_LED_1); } /**************************************************************************** * Name: pic32mx_setled ****************************************************************************/ #ifndef CONFIG_ARCH_LEDS void pic32mx_setled(int led, bool ledon) { /* LEDs are pulled up so writing a low value (false) illuminates them */ if ((unsigned)led < PIC32MX_MIRTOO_NLEDS) { pic32mx_gpiowrite(g_ledpincfg[led], ledon); } } #endif /**************************************************************************** * Name: pic32mx_setleds ****************************************************************************/ #ifndef CONFIG_ARCH_LEDS void pic32mx_setleds(uint8_t ledset) { /* Call pic32mx_setled() with ledon == true to illuminated the LED */ pic32mx_setled(PIC32MX_MIRTOO_LED0, (ledset & PIC32MX_MIRTOO_LED0_BIT) != 0); pic32mx_setled(PIC32MX_MIRTOO_LED1, (ledset & PIC32MX_MIRTOO_LED1_BIT) != 0); } #endif /**************************************************************************** * Name: board_led_on ****************************************************************************/ #ifdef CONFIG_ARCH_LEDS void board_led_on(int led) { if ((unsigned)led < LED_NVALUES) { up_setleds(&g_ledonvalues[led]); } } #endif /**************************************************************************** * Name: board_led_off ****************************************************************************/ #ifdef CONFIG_ARCH_LEDS void board_led_off(int led) { if ((unsigned)led < LED_NVALUES) { up_setleds(&g_ledoffvalues[led]); } } #endif
mit
Billary/BillaryCoinSource
src/qt/sendcoinsdialog.cpp
1
17904
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a BillaryCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid BillaryCoin address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
mit
ldorelli/tcc
src/draw_main.cpp
1
1377
#include <SFML/Graphics.hpp> #include <iostream> #include <cmath> #include <cstdlib> #include <util.h> #include <graph.h> #include <kuramoto.h> #include <time.h> using namespace std; #define BOLAS 2 int main() { srand ( time(NULL) ); Graph<KuramotoOscillator> g; KuramotoOscillator::simpleKuramotoNetwork(g, 2, 50); // create the window sf::RenderWindow window(sf::VideoMode(800, 600), "My window"); sf::View view( sf::Vector2f(0.0, 0.0), sf::Vector2f(200, 150) ); window.setView(view); // run the program as long as the window is open while (window.isOpen()) { for (int i = 0; i < 2000; ++i) { sf::Event event; while (window.pollEvent(event)) { // "close requested" event: we close the window if (event.type == sf::Event::Closed) window.close(); } // clear the window with black color window.clear(sf::Color::Black); for (int i = 0; i < 2; ++i) { sf::CircleShape sp(3); sp.setPosition(5*i, g.nodes[i].phase * 30.0); // int color = (57.0 + g.nodes[i].phase)/114.00 * 255; if (i) sp.setFillColor( sf::Color::Blue ); else sp.setFillColor( sf::Color::Red ); window.draw(sp); } // end the current frame window.display(); g.update(); sf::sleep( sf::seconds(0.1) ); } } return 0; }
mit
staycrypto/antimatter
src/test/test_bitcoin.cpp
1
1757
#define BOOST_TEST_MODULE Antimatter Test Suite #include <boost/test/unit_test.hpp> #include <boost/filesystem.hpp> #include "db.h" #include "txdb.h" #include "main.h" #include "wallet.h" #include "util.h" CWallet* pwalletMain; CClientUIInterface uiInterface; extern bool fPrintToConsole; extern void noui_connect(); struct TestingSetup { CCoinsViewDB *pcoinsdbview; boost::filesystem::path pathTemp; boost::thread_group threadGroup; TestingSetup() { fPrintToDebugger = true; // don't want to write to debug.log file noui_connect(); bitdb.MakeMock(); pathTemp = GetTempPath() / strprintf("test_antimatter_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); boost::filesystem::create_directories(pathTemp); mapArgs["-datadir"] = pathTemp.string(); pblocktree = new CBlockTreeDB(1 << 20, true); pcoinsdbview = new CCoinsViewDB(1 << 23, true); pcoinsTip = new CCoinsViewCache(*pcoinsdbview); InitBlockIndex(); bool fFirstRun; pwalletMain = new CWallet("wallet.dat"); pwalletMain->LoadWallet(fFirstRun); RegisterWallet(pwalletMain); nScriptCheckThreads = 3; for (int i=0; i < nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); } ~TestingSetup() { threadGroup.interrupt_all(); threadGroup.join_all(); delete pwalletMain; pwalletMain = NULL; delete pcoinsTip; delete pcoinsdbview; delete pblocktree; bitdb.Flush(true); boost::filesystem::remove_all(pathTemp); } }; BOOST_GLOBAL_FIXTURE(TestingSetup); void Shutdown(void* parg) { exit(0); } void StartShutdown() { exit(0); }
mit
julzor42/core32
src/uart.c
1
4586
/* MIT License Copyright (c) 2016 Julien Delmotte 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 <core32.h> #include <core32/uart.h> #ifdef UART_CONSOLE void _mon_putc(char c) { while (UART_IsFull(UART_CONSOLE)); UxTXREG(UART_CONSOLE) = c; } int _mon_getc(int canblock) { if (canblock) { while (!UART_HasData(UART_CONSOLE)); return UxRXREG(UART_CONSOLE); } if (UART_HasData(UART_CONSOLE)) return UxRXREG(UART_CONSOLE); return 0; } #endif void UART_Initialize(unsigned int Port, unsigned int Baud, unsigned int RdWr) { int Div4 = 0; // Disable and clear UART UxMODE(Port) = 0; PBDIV1_CYCLE_WAIT(); if (Div4) UxMODESET(Port) = UMODE_BRGH; if (RdWr & UART_WRITE) UxSTASET(Port) = USTA_UTXEN; if (RdWr & UART_READ) UxSTASET(Port) = USTA_URXEN; UxBRG(Port) = PBCLK / (Div4 ? 4 : 16) / Baud - 1; UART_Enable(Port); } void UART_PutChar(unsigned int Port, char Data) { while (UART_IsFull(Port)); UxTXREG(Port) = Data; } void UART_PutString(unsigned int Port, const char* Data) { while (*Data) UART_PutChar(Port, *Data++); } void UART_Write(unsigned int Port, const char* Data, unsigned int Length) { while (--Length) UART_PutChar(Port, *Data++); } char UART_GetChar(unsigned int Port) { while (!UART_HasData(Port)); return UxRXREG(Port); } void UART_Read(unsigned int Port, char* Data, unsigned int Length) { while (--Length) (*Data++) = UART_GetChar(Port); } void UART_ReadLine(unsigned int Port, char* Data, unsigned int MaxLength) { while (--MaxLength > 0) { *Data = UART_GetChar(Port); if (*Data == '\n') break; Data++; } *Data = 0; } void UART_SetInterrupt(unsigned int Port, unsigned int Mode, unsigned int Priority, unsigned int SubPriority) { UART_EnableInterrupt(Port, DISABLED); UART_EnableTXInterrupt(Port, DISABLED); UART_EnableRXInterrupt(Port, DISABLED); switch (Port) { case UART_2: IPC8bits.U2IP = Priority; IPC8bits.U2IS = SubPriority; break; } UART_ClearInterrupt(Port); UART_ClearTXInterrupt(Port); UART_ClearRXInterrupt(Port); UART_EnableInterrupt(Port, (Mode != 0) ? 1 : 0); UART_EnableTXInterrupt(Port, (Mode & UART_WRITE) ? 1 : 0); UART_EnableRXInterrupt(Port, (Mode & UART_READ) ? 1 : 0); } void UART_EnableInterrupt(unsigned int Port, unsigned int Enabled) { switch (Port) { case UART_2: IEC1bits.U2EIE = Enabled; break; } } void UART_EnableTXInterrupt(unsigned int Port, unsigned int Enabled) { switch (Port) { case UART_2: IEC1bits.U2TXIE = Enabled; break; } } void UART_EnableRXInterrupt(unsigned int Port, unsigned int Enabled) { switch (Port) { case UART_2: IEC1bits.U2RXIE = Enabled; break; } } void UART_ClearInterrupt(unsigned int Port) { switch (Port) { case UART_2: IFS1bits.U2EIF = 0; break; } } void UART_ClearTXInterrupt(unsigned int Port) { switch (Port) { case UART_2: IFS1bits.U2TXIF = 0; break; } } void UART_ClearRXInterrupt(unsigned int Port) { switch (Port) { case UART_2: IFS1bits.U2RXIF = 0; break; } } unsigned int UART_CheckInterrupt(unsigned int Port) { switch (Port) { case UART_2: return IFS1bits.U2EIF; } return 0; } unsigned int UART_CheckTXInterrupt(unsigned int Port) { switch (Port) { case UART_2: return IFS1bits.U2TXIF; } return 0; } unsigned int UART_CheckRXInterrupt(unsigned int Port) { switch (Port) { case UART_2: return IFS1bits.U2RXIF; } return 0; }
mit

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card